Buckets:

download
raw
46.9 kB
#!/usr/bin/env python3 """ SonarCloud Issue Management Tool Simple CLI for managing SonarCloud issues for the CIRIS project. Uses token from ~/.sonartoken for authentication. Usage: # Quality Gate Status (IMPORTANT: Shows both PR and main status!) python -m tools.analysis.sonar quality-gate # PR + main branch status python -m tools.analysis.sonar status # Main branch status only # Issue Management python -m tools.analysis.sonar list [--severity CRITICAL] [--limit 10] python -m tools.analysis.sonar mark-fp ISSUE_KEY [--comment "Reason"] python -m tools.analysis.sonar mark-wontfix ISSUE_KEY [--comment "Reason"] python -m tools.analysis.sonar reopen ISSUE_KEY python -m tools.analysis.sonar stats # Security & Coverage python -m tools.analysis.sonar hotspots [--status TO_REVIEW] python -m tools.analysis.sonar coverage [--new-code] [--pr PR_NUMBER] python -m tools.analysis.sonar pr PR_NUMBER # Detailed PR analysis NOTE: - 'quality-gate' shows BOTH PR and main status (use this for PR checks!) - 'status' only shows main branch (use for overall project health) - SonarCloud analysis runs ~15 minutes after CI completes """ import argparse import json import subprocess import sys from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import requests # Configuration SONAR_TOKEN_FILE = Path.home() / ".sonartoken" SONAR_API_BASE = "https://sonarcloud.io/api" PROJECT_KEY = "CIRISAI_CIRISAgent" class SonarClient: """Simple SonarCloud API client.""" def __init__(self, token: str): self.token = token self.session = requests.Session() self.session.headers.update({"Authorization": f"Bearer {token}"}) def search_issues( self, severity: Optional[str] = None, resolved: bool = False, limit: int = 20 ) -> List[Dict[str, Any]]: """Search for issues in the project.""" params = {"componentKeys": PROJECT_KEY, "resolved": str(resolved).lower(), "ps": limit} if severity: params["severities"] = severity.upper() response = self.session.get(f"{SONAR_API_BASE}/issues/search", params=params) response.raise_for_status() return response.json()["issues"] def transition_issue(self, issue_key: str, transition: str, comment: Optional[str] = None) -> Dict[str, Any]: """Transition an issue (mark as false positive, won't fix, etc).""" data = {"issue": issue_key, "transition": transition} if comment: data["comment"] = comment response = self.session.post( f"{SONAR_API_BASE}/issues/do_transition", data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}, ) response.raise_for_status() return response.json() def add_comment(self, issue_key: str, comment: str) -> Dict[str, Any]: """Add a comment to an issue.""" data = {"issue": issue_key, "text": comment} response = self.session.post( f"{SONAR_API_BASE}/issues/add_comment", data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}, ) response.raise_for_status() return response.json() def get_stats(self) -> Dict[str, Any]: """Get issue statistics for the project.""" response = self.session.get( f"{SONAR_API_BASE}/issues/search", params={"componentKeys": PROJECT_KEY, "resolved": "false", "facets": "severities,types,rules", "ps": 1}, ) response.raise_for_status() data = response.json() stats = {"total": data["total"], "by_severity": {}, "by_type": {}, "top_rules": []} for facet in data["facets"]: if facet["property"] == "severities": stats["by_severity"] = {v["val"]: v["count"] for v in facet["values"]} elif facet["property"] == "types": stats["by_type"] = {v["val"]: v["count"] for v in facet["values"]} elif facet["property"] == "rules": stats["top_rules"] = [(v["val"], v["count"]) for v in facet["values"][:5]] return stats def get_quality_gate_status( self, branch: Optional[str] = None, pull_request: Optional[str] = None ) -> Dict[str, Any]: """Get quality gate status for the project, branch, or PR. Args: branch: Branch name (e.g., 'main', '1.3.1') pull_request: Pull request ID (e.g., '432') Returns: Quality gate status with conditions and timestamp """ params = {"projectKey": PROJECT_KEY} if pull_request: params["pullRequest"] = pull_request elif branch: params["branch"] = branch response = self.session.get(f"{SONAR_API_BASE}/qualitygates/project_status", params=params) response.raise_for_status() return response.json()["projectStatus"] def get_project_analyses( self, branch: Optional[str] = None, pull_request: Optional[str] = None, limit: int = 1 ) -> Dict[str, Any]: """Get recent analyses for project, branch, or PR. Args: branch: Branch name pull_request: Pull request ID limit: Number of analyses to retrieve Returns: List of analyses with timestamps """ params = {"project": PROJECT_KEY, "ps": limit} if pull_request: params["pullRequest"] = pull_request elif branch: params["branch"] = branch response = self.session.get(f"{SONAR_API_BASE}/project_analyses/search", params=params) response.raise_for_status() return response.json() def search_hotspots(self, status: str = "TO_REVIEW", limit: int = 100) -> Dict[str, Any]: """Search for security hotspots.""" params = {"projectKey": PROJECT_KEY, "status": status, "ps": limit} response = self.session.get(f"{SONAR_API_BASE}/hotspots/search", params=params) response.raise_for_status() return response.json() def mark_hotspot_safe( self, hotspot_key: str, resolution: str = "SAFE", comment: Optional[str] = None ) -> Dict[str, Any]: """Mark a security hotspot as reviewed. Args: hotspot_key: The hotspot key resolution: SAFE, ACKNOWLEDGED, or FIXED comment: Optional comment explaining the resolution The SonarCloud API requires status=REVIEWED plus a resolution. """ data = {"hotspot": hotspot_key, "status": "REVIEWED", "resolution": resolution} if comment: data["comment"] = comment response = self.session.post( f"{SONAR_API_BASE}/hotspots/change_status", data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}, ) response.raise_for_status() # API returns empty response on success return {"status": "success", "hotspot": hotspot_key, "resolution": resolution} def get_coverage_metrics(self, new_code: bool = False, pull_request: Optional[str] = None) -> Dict[str, Any]: """Get coverage metrics for the project or a specific PR.""" metrics = [] if new_code: metrics = [ "new_coverage", "new_lines_to_cover", "new_uncovered_lines", "new_line_coverage", "new_branch_coverage", ] else: metrics = ["coverage", "lines_to_cover", "uncovered_lines", "line_coverage", "branch_coverage"] params = {"component": PROJECT_KEY, "metricKeys": ",".join(metrics)} if pull_request: params["pullRequest"] = pull_request response = self.session.get(f"{SONAR_API_BASE}/measures/component", params=params) response.raise_for_status() return response.json() def get_pr_analysis(self, pull_request: str) -> Dict[str, Any]: """Get analysis for a specific pull request.""" params = {"pullRequest": pull_request, "component": PROJECT_KEY} # Get PR quality gate status qg_response = self.session.get(f"{SONAR_API_BASE}/qualitygates/project_status", params=params) qg_response.raise_for_status() quality_gate = qg_response.json() # Get PR coverage metrics coverage_metrics = self.get_coverage_metrics(new_code=True, pull_request=pull_request) # Get PR issues issues_params = { "componentKeys": PROJECT_KEY, "pullRequest": pull_request, "resolved": "false", "ps": 100, } issues_response = self.session.get(f"{SONAR_API_BASE}/issues/search", params=issues_params) issues_response.raise_for_status() issues_data = issues_response.json() return { "quality_gate": quality_gate, "coverage": coverage_metrics, "issues": issues_data, } def get_uncovered_files(self, pull_request: Optional[str] = None) -> List[Dict[str, Any]]: """Get list of files with uncovered lines in a PR.""" params = { "component": PROJECT_KEY, "metricKeys": ( "new_uncovered_lines,new_lines_to_cover" if pull_request else "uncovered_lines,lines_to_cover" ), "ps": 500, "strategy": "leaves", } if pull_request: params["pullRequest"] = pull_request response = self.session.get(f"{SONAR_API_BASE}/measures/component_tree", params=params) response.raise_for_status() data = response.json() files_with_uncovered = [] metric_key = "new_uncovered_lines" if pull_request else "uncovered_lines" cover_key = "new_lines_to_cover" if pull_request else "lines_to_cover" for comp in data.get("components", []): # Parse measures - handle both direct value and periods format measures = {} for m in comp.get("measures", []): metric = m["metric"] if "value" in m: measures[metric] = int(float(m["value"])) elif "periods" in m and m["periods"]: measures[metric] = int(float(m["periods"][0].get("value", "0"))) uncovered = measures.get(metric_key, 0) to_cover = measures.get(cover_key, 0) if uncovered > 0: files_with_uncovered.append( { "path": comp.get("path", ""), "key": comp.get("key", ""), "uncovered": uncovered, "to_cover": to_cover, "coverage": ((to_cover - uncovered) / to_cover * 100) if to_cover > 0 else 0, } ) return sorted(files_with_uncovered, key=lambda x: -x["uncovered"]) def get_source_lines(self, component_key: str, pull_request: Optional[str] = None) -> List[Dict[str, Any]]: """Get source lines with coverage info for a specific file.""" params = {"key": component_key} if pull_request: params["pullRequest"] = pull_request response = self.session.get(f"{SONAR_API_BASE}/sources/lines", params=params) response.raise_for_status() return response.json().get("sources", []) def get_uncovered_lines(self, component_key: str, pull_request: Optional[str] = None) -> List[int]: """Get list of uncovered line numbers for a specific file.""" sources = self.get_source_lines(component_key, pull_request) uncovered = [] for line_info in sources: # Line is uncovered if it's coverable (lineHits exists) but has 0 hits line_hits = line_info.get("lineHits") if line_hits is not None and line_hits == 0: # Check if it's new code (for PR analysis) if pull_request: if line_info.get("isNew", False): uncovered.append(line_info["line"]) else: uncovered.append(line_info["line"]) return uncovered def get_dependencies(self, branch: Optional[str] = None) -> Dict[str, Any]: """Get dependency information for the project. Returns dependency cycles (tangles) and component relationships. """ params = {"component": PROJECT_KEY} if branch: params["branch"] = branch # Try the dependencies endpoint response = self.session.get(f"{SONAR_API_BASE}/dependencies/show", params=params) response.raise_for_status() return response.json() def get_measures_component_tree( self, metrics: List[str], branch: Optional[str] = None, qualifier: str = "FIL" ) -> Dict[str, Any]: """Get measures for all components in the project tree. Args: metrics: List of metric keys to retrieve branch: Optional branch name qualifier: Component qualifier (FIL=files, DIR=directories, TRK=project) """ params = { "component": PROJECT_KEY, "metricKeys": ",".join(metrics), "ps": 500, "qualifiers": qualifier, } if branch: params["branch"] = branch response = self.session.get(f"{SONAR_API_BASE}/measures/component_tree", params=params) response.raise_for_status() return response.json() def get_architecture_info(self, branch: Optional[str] = None) -> Dict[str, Any]: """Get architecture analysis information including tangles. Note: This endpoint may require specific SonarCloud plan features. """ params = {"component": PROJECT_KEY} if branch: params["branch"] = branch # Try multiple potential endpoints for architecture data endpoints_to_try = [ f"{SONAR_API_BASE}/architecture/tangles", f"{SONAR_API_BASE}/measures/component", ] # For component measures, get architecture-related metrics complexity_params = { "component": PROJECT_KEY, "metricKeys": "complexity,cognitive_complexity,file_complexity,function_complexity,duplicated_lines_density,sqale_index,sqale_debt_ratio", } if branch: complexity_params["branch"] = branch try: response = self.session.get(f"{SONAR_API_BASE}/measures/component", params=complexity_params) response.raise_for_status() return {"type": "measures", "data": response.json()} except Exception as e: return {"type": "error", "error": str(e)} def get_recent_prs(limit: int = 2) -> List[Tuple[str, str]]: """Get recent open PRs from GitHub. Returns: List of (PR number, branch name) tuples """ try: result = subprocess.run( ["gh", "pr", "list", "--limit", str(limit), "--json", "number,headRefName"], capture_output=True, text=True, check=True, ) prs = json.loads(result.stdout) return [(str(pr["number"]), pr["headRefName"]) for pr in prs] except (subprocess.CalledProcessError, json.JSONDecodeError, KeyError): return [] def format_time_ago(iso_timestamp: str) -> str: """Format ISO timestamp as 'X minutes ago' or 'X hours ago'. Args: iso_timestamp: ISO format timestamp Returns: Human-readable time ago string """ try: # Parse ISO timestamp dt = datetime.fromisoformat(iso_timestamp.replace("Z", "+00:00")) now = datetime.now(timezone.utc) delta = now - dt # Calculate time ago seconds = int(delta.total_seconds()) if seconds < 60: return f"{seconds}s ago" elif seconds < 3600: minutes = seconds // 60 return f"{minutes}m ago" elif seconds < 86400: hours = seconds // 3600 return f"{hours}h ago" else: days = seconds // 86400 return f"{days}d ago" except (ValueError, AttributeError): return "unknown" def format_quality_gate_summary(qg_status: Dict[str, Any], label: str, timestamp: Optional[str] = None) -> str: """Format quality gate status as a summary line. Args: qg_status: Quality gate status from API label: Label for this check (e.g., "Main", "PR #432") timestamp: Optional analysis timestamp Returns: Formatted summary string """ status = qg_status["status"] status_icon = "✅" if status == "OK" else "❌" time_str = "" if timestamp: time_str = f" ({format_time_ago(timestamp)})" metric_labels = { "reliability_rating": "Reliability Rating", "security_rating": "Security Rating", "coverage": "Coverage", "new_coverage": "Coverage", "security_hotspots_reviewed": "Security Hotspots Reviewed", "new_security_hotspots_reviewed": "Security Hotspots Reviewed", } percentage_metrics = { "coverage", "new_coverage", "security_hotspots_reviewed", "new_security_hotspots_reviewed", } # Find failed conditions failed_conditions = [] if qg_status.get("conditions"): for condition in qg_status["conditions"]: if condition["status"] != "OK": metric_key = condition["metricKey"] metric = metric_labels.get(metric_key, metric_key.replace("_", " ").replace("new ", "").title()) actual = condition.get("actualValue", "?") threshold = condition["errorThreshold"] comparator = "≥" if condition["comparator"] == "LT" else "≤" if metric_key in percentage_metrics: actual = f"{actual}%" threshold = f"{threshold}%" failed_conditions.append(f"{metric}: {actual} (needs {comparator} {threshold})") result = f"{status_icon} {label}: {status}{time_str}" if failed_conditions: result += "\n " + "\n ".join(failed_conditions) return result def format_hotspot(hotspot: Dict[str, Any]) -> str: """Format a security hotspot for display.""" file_path = hotspot["component"].split(":")[-1] created = datetime.fromisoformat(hotspot["creationDate"].replace("Z", "+00:00")) created_str = created.strftime("%Y-%m-%d") return ( f"[{hotspot['vulnerabilityProbability']} RISK] {hotspot['key']} - {hotspot['securityCategory'].upper()}\n" f" File: {file_path}:{hotspot.get('line', '?')}\n" f" Message: {hotspot['message']}\n" f" Status: {hotspot['status']}\n" f" Created: {created_str}\n" ) def format_issue(issue: Dict[str, Any]) -> str: """Format an issue for display.""" file_path = issue["component"].split(":")[-1] created = datetime.fromisoformat(issue["creationDate"].replace("Z", "+00:00")) created_str = created.strftime("%Y-%m-%d") return ( f"[{issue['severity']}] {issue['key']} - {issue['rule']}\n" f" File: {file_path}:{issue.get('line', '?')}\n" f" Message: {issue['message']}\n" f" Created: {created_str}\n" ) def main(): parser = argparse.ArgumentParser(description="SonarCloud Issue Management Tool") subparsers = parser.add_subparsers(dest="command", help="Commands") # List command list_parser = subparsers.add_parser("list", help="List issues") list_parser.add_argument( "--severity", choices=["BLOCKER", "CRITICAL", "MAJOR", "MINOR", "INFO"], help="Filter by severity" ) list_parser.add_argument("--limit", type=int, default=20, help="Number of issues to show") list_parser.add_argument("--resolved", action="store_true", help="Show resolved issues") # Mark false positive fp_parser = subparsers.add_parser("mark-fp", help="Mark issue as false positive") fp_parser.add_argument("issue_key", help="Issue key to mark") fp_parser.add_argument("--comment", help="Comment explaining why it's a false positive") # Mark won't fix wf_parser = subparsers.add_parser("mark-wontfix", help="Mark issue as won't fix") wf_parser.add_argument("issue_key", help="Issue key to mark") wf_parser.add_argument("--comment", help="Comment explaining why it won't be fixed") # Reopen reopen_parser = subparsers.add_parser("reopen", help="Reopen a resolved issue") reopen_parser.add_argument("issue_key", help="Issue key to reopen") # Stats stats_parser = subparsers.add_parser("stats", help="Show issue statistics") # Comment comment_parser = subparsers.add_parser("comment", help="Add comment to an issue") comment_parser.add_argument("issue_key", help="Issue key to comment on") comment_parser.add_argument("comment", help="Comment text") # Quality Gate (PR + Main status) qg_parser = subparsers.add_parser("quality-gate", help="Show quality gate status (PR + main)") # Status (Main branch only) status_parser = subparsers.add_parser("status", help="Show main branch status only") # Security Hotspots hotspots_parser = subparsers.add_parser("hotspots", help="List security hotspots") hotspots_parser.add_argument( "--status", choices=["TO_REVIEW", "REVIEWED", "SAFE", "FIXED"], default="TO_REVIEW", help="Filter by status" ) hotspots_parser.add_argument("--limit", type=int, default=20, help="Number of hotspots to show") # Mark hotspot safe safe_parser = subparsers.add_parser("mark-safe", help="Mark security hotspot as safe") safe_parser.add_argument("hotspot_key", help="Hotspot key to mark") safe_parser.add_argument( "--resolution", choices=["SAFE", "ACKNOWLEDGED", "FIXED"], default="SAFE", help="Resolution type (default: SAFE)", ) safe_parser.add_argument("--comment", help="Comment explaining the resolution") # Coverage coverage_parser = subparsers.add_parser("coverage", help="Show coverage metrics") coverage_parser.add_argument("--new-code", action="store_true", help="Show metrics for new code only") coverage_parser.add_argument("--pr", type=str, help="Pull request number (e.g., 430)") # PR Analysis pr_parser = subparsers.add_parser("pr", help="Analyze a specific pull request") pr_parser.add_argument("pr_number", type=str, help="Pull request number") # Uncovered Lines uncovered_parser = subparsers.add_parser("uncovered", help="Show uncovered lines in PR") uncovered_parser.add_argument("pr_number", type=str, help="Pull request number") uncovered_parser.add_argument("--file", type=str, help="Filter to specific file path pattern") uncovered_parser.add_argument("--lines", action="store_true", help="Show specific line numbers") uncovered_parser.add_argument("--limit", type=int, default=20, help="Max files to show (default: 20)") # Architecture / Tangles tangles_parser = subparsers.add_parser("tangles", help="Show architecture tangles (cyclic dependencies)") tangles_parser.add_argument("--branch", type=str, default="main", help="Branch to analyze (default: main)") args = parser.parse_args() # Load token if not SONAR_TOKEN_FILE.exists(): print(f"Error: Token file not found at {SONAR_TOKEN_FILE}") print("Please save your SonarCloud token to ~/.sonartoken") sys.exit(1) token = SONAR_TOKEN_FILE.read_text().strip() client = SonarClient(token) try: if args.command == "list": issues = client.search_issues(severity=args.severity, resolved=args.resolved, limit=args.limit) if not issues: print("No issues found matching criteria.") else: print(f"\nFound {len(issues)} issues:\n") for issue in issues: print(format_issue(issue)) elif args.command == "mark-fp": if args.comment: # Add comment first client.add_comment(args.issue_key, f"Marking as false positive: {args.comment}") result = client.transition_issue(args.issue_key, "falsepositive") print(f"[OK] Marked {args.issue_key} as false positive") print(f" Status: {result['issue']['issueStatus']}") elif args.command == "mark-wontfix": if args.comment: # Add comment first client.add_comment(args.issue_key, f"Marking as won't fix: {args.comment}") result = client.transition_issue(args.issue_key, "wontfix") print(f"[OK] Marked {args.issue_key} as won't fix") print(f" Status: {result['issue']['issueStatus']}") elif args.command == "reopen": result = client.transition_issue(args.issue_key, "reopen") print(f"[OK] Reopened {args.issue_key}") print(f" Status: {result['issue']['status']}") elif args.command == "comment": client.add_comment(args.issue_key, args.comment) print(f"[OK] Added comment to {args.issue_key}") elif args.command == "stats": stats = client.get_stats() print(f"\nSonarCloud Statistics for {PROJECT_KEY}") print("=" * 50) print(f"Total Open Issues: {stats['total']}") print("\nBy Severity:") for severity in ["BLOCKER", "CRITICAL", "MAJOR", "MINOR", "INFO"]: count = stats["by_severity"].get(severity, 0) if count > 0: print(f" {severity}: {count}") print("\nBy Type:") for issue_type, count in stats["by_type"].items(): print(f" {issue_type}: {count}") print("\nTop 5 Rules:") for rule, count in stats["top_rules"]: print(f" {rule}: {count} issues") elif args.command == "status": # Quick status - main branch only try: main_qg = client.get_quality_gate_status(branch="main") metrics = client.get_coverage_metrics() measures = {m["metric"]: m.get("value", "0") for m in metrics["component"].get("measures", [])} print("CIRIS Quality Status") print("=" * 40) coverage = float(measures.get("coverage", 0)) print(f"Coverage: {coverage:.1f}% (Target: 80%)") print(f"Quality Gate: {main_qg['status']}") except Exception as e: print(f"Error getting status: {e}") sys.exit(1) elif args.command == "quality-gate": print("\n SonarCloud Quality Gate Status") print("=" * 70) print("\n[INFO] Note: SonarCloud analysis runs after successful CI (~15 minutes)") print("=" * 70) # Get main branch status try: main_qg = client.get_quality_gate_status(branch="main") main_analyses = client.get_project_analyses(branch="main", limit=1) main_timestamp = None if main_analyses.get("analyses"): main_timestamp = main_analyses["analyses"][0]["date"] print(f"\n{format_quality_gate_summary(main_qg, 'Main', main_timestamp)}") except Exception as e: print(f"\n[FAIL] Main: Could not retrieve status ({e})") # Get recent PRs recent_prs = get_recent_prs(limit=2) if recent_prs: print("\nRecent Pull Requests:") for pr_num, branch_name in recent_prs: try: # Try PR-based query first pr_qg = client.get_quality_gate_status(pull_request=pr_num) pr_analyses = client.get_project_analyses(pull_request=pr_num, limit=1) pr_timestamp = None if pr_analyses.get("analyses"): pr_timestamp = pr_analyses["analyses"][0]["date"] print(f"{format_quality_gate_summary(pr_qg, f'PR #{pr_num} ({branch_name})', pr_timestamp)}") except requests.exceptions.HTTPError as pr_error: # Fall back to branch-based query try: branch_qg = client.get_quality_gate_status(branch=branch_name) branch_analyses = client.get_project_analyses(branch=branch_name, limit=1) branch_timestamp = None if branch_analyses.get("analyses"): branch_timestamp = branch_analyses["analyses"][0]["date"] print( f"{format_quality_gate_summary(branch_qg, f'PR #{pr_num} ({branch_name})', branch_timestamp)}" ) except Exception as branch_error: print(f"[FAIL] PR #{pr_num} ({branch_name}): No SonarCloud analysis yet") else: print("\nNo recent open PRs found.") elif args.command == "hotspots": result = client.search_hotspots(status=args.status, limit=args.limit) hotspots = result["hotspots"] if not hotspots: print(f"No security hotspots found with status {args.status}.") else: print(f"\nFound {result['paging']['total']} security hotspots (showing {len(hotspots)}):") print("=" * 70) # Group by vulnerability probability by_risk = {} for hotspot in hotspots: risk = hotspot["vulnerabilityProbability"] if risk not in by_risk: by_risk[risk] = [] by_risk[risk].append(hotspot) for risk in ["HIGH", "MEDIUM", "LOW"]: if risk in by_risk: print(f"\n{risk} RISK ({len(by_risk[risk])} hotspots):\n") for hotspot in by_risk[risk]: print(format_hotspot(hotspot)) elif args.command == "mark-safe": resolution = args.resolution comment = args.comment or f"Reviewed and determined to be {resolution.lower()}" result = client.mark_hotspot_safe(args.hotspot_key, resolution=resolution, comment=comment) print(f"[OK] Marked {args.hotspot_key} as {resolution}") elif args.command == "coverage": pr_number = getattr(args, "pr", None) metrics = client.get_coverage_metrics(new_code=args.new_code, pull_request=pr_number) component = metrics["component"] # Extract measures - handle both value and periods formats measures = {} for m in component.get("measures", []): if "value" in m: measures[m["metric"]] = m["value"] elif "periods" in m and m["periods"]: measures[m["metric"]] = m["periods"][0]["value"] scope_label = f"PR #{pr_number}" if pr_number else PROJECT_KEY print(f"\nCoverage Metrics for {scope_label}") print("=" * 50) prefix = "new_" if args.new_code else "" scope = "New Code" if args.new_code else "Overall" if f"{prefix}coverage" in measures: coverage = float(measures[f"{prefix}coverage"]) print(f"{scope} Coverage: {coverage:.1f}%") if coverage < 80 and args.new_code: print("[WARN] New code coverage is below 80% threshold!") if f"{prefix}lines_to_cover" in measures: lines_to_cover = int(float(measures.get(f"{prefix}lines_to_cover", 0))) uncovered_lines = int(float(measures.get(f"{prefix}uncovered_lines", 0))) covered_lines = lines_to_cover - uncovered_lines print("\nLines:") print(f" Total to cover: {lines_to_cover}") print(f" Covered: {covered_lines}") print(f" Uncovered: {uncovered_lines}") if f"{prefix}line_coverage" in measures: print(f"\nLine Coverage: {float(measures[f'{prefix}line_coverage']):.1f}%") if f"{prefix}branch_coverage" in measures: print(f"Branch Coverage: {float(measures[f'{prefix}branch_coverage']):.1f}%") elif args.command == "pr": # Get PR and branch info from GitHub try: pr_result = subprocess.run( ["gh", "pr", "view", args.pr_number, "--json", "headRefName"], capture_output=True, text=True, check=True, ) pr_info = json.loads(pr_result.stdout) branch_name = pr_info["headRefName"] except (subprocess.CalledProcessError, json.JSONDecodeError, KeyError): print(f"Error: Could not retrieve PR #{args.pr_number} from GitHub") sys.exit(1) print(f"\n Pull Request #{args.pr_number} ({branch_name}) Analysis") print("=" * 70) metric_labels = { "reliability_rating": "Reliability Rating", "security_rating": "Security Rating", "coverage": "Coverage", "new_coverage": "Coverage", "security_hotspots_reviewed": "Security Hotspots Reviewed", "new_security_hotspots_reviewed": "Security Hotspots Reviewed", } percentage_metrics = { "coverage", "new_coverage", "security_hotspots_reviewed", "new_security_hotspots_reviewed", } # Use PR-aware Sonar API path first; fall back to branch only if needed. try: qg_status = client.get_quality_gate_status(pull_request=args.pr_number) status = qg_status["status"] status_icon = "✅" if status == "OK" else "❌" print(f"\nQuality Gate: {status_icon} {status}") if qg_status.get("conditions"): print("\nConditions:") for condition in qg_status["conditions"]: cond_status = "✓" if condition["status"] == "OK" else "✗" metric_key = condition["metricKey"] metric = metric_labels.get(metric_key, metric_key.replace("_", " ").title()) actual = condition.get("actualValue", "N/A") threshold = condition["errorThreshold"] comparator = "≥" if condition["comparator"] == "LT" else "≤" if metric_key in percentage_metrics: actual = f"{actual}%" threshold = f"{threshold}%" print(f" {cond_status} {metric}: {actual} (needs {comparator} {threshold})") except Exception as e: try: qg_status = client.get_quality_gate_status(branch=branch_name) status = qg_status["status"] status_icon = "✅" if status == "OK" else "❌" print(f"\nQuality Gate: {status_icon} {status} (branch fallback)") except Exception: print(f"\n[FAIL] Quality Gate: Could not retrieve status ({e})") # Coverage Metrics try: coverage_metrics = client.get_coverage_metrics(new_code=True, pull_request=args.pr_number) coverage_comp = coverage_metrics["component"] measures = {} for m in coverage_comp.get("measures", []): if "value" in m: measures[m["metric"]] = m["value"] elif "periods" in m and m["periods"]: measures[m["metric"]] = m["periods"][0]["value"] print("\n Coverage on New Code:") if "new_coverage" in measures: coverage = float(measures["new_coverage"]) print(f" Coverage: {coverage:.1f}%") if coverage < 80: print(" [WARN] Below 80% threshold!") if "new_lines_to_cover" in measures: lines_to_cover = int(float(measures.get("new_lines_to_cover", 0))) uncovered_lines = int(float(measures.get("new_uncovered_lines", 0))) covered_lines = lines_to_cover - uncovered_lines print(f" Lines to cover: {lines_to_cover}") print(f" Covered: {covered_lines}") print(f" Uncovered: {uncovered_lines}") print(f"\n Need {int(lines_to_cover * 0.8) - covered_lines} more lines covered for 80%") except Exception as e: print(f"\n[FAIL] Coverage: Could not retrieve metrics ({e})") # Issues try: issues_params = { "componentKeys": PROJECT_KEY, "pullRequest": args.pr_number, "resolved": "false", "ps": 100, } issues_response = client.session.get(f"{SONAR_API_BASE}/issues/search", params=issues_params) issues_response.raise_for_status() issues_data = issues_response.json() total_issues = issues_data["total"] print(f"\n Issues: {total_issues}") if total_issues > 0: # Group by severity by_severity = {} for issue in issues_data["issues"]: severity = issue["severity"] by_severity[severity] = by_severity.get(severity, 0) + 1 print(" By severity:") for sev in ["BLOCKER", "CRITICAL", "MAJOR", "MINOR", "INFO"]: if sev in by_severity: print(f" {sev}: {by_severity[sev]}") # Show detailed issues for BLOCKER and CRITICAL print("\n Critical Issues:") for issue in issues_data["issues"]: if issue["severity"] in ["BLOCKER", "CRITICAL"]: severity = issue["severity"] msg = issue.get("message", "No message") file_path = issue.get("component", "").split(":")[-1] line = issue.get("line", "?") rule = issue.get("rule", "") print(f"\n [{severity}] {rule}") print(f" {msg}") print(f" {file_path}:{line}") except Exception as e: print(f"\n[FAIL] Issues: Could not retrieve issues ({e})") elif args.command == "uncovered": print(f"\n Uncovered Lines in PR #{args.pr_number}") print("=" * 70) try: files = client.get_uncovered_files(pull_request=args.pr_number) if args.file: files = [f for f in files if args.file.lower() in f["path"].lower()] if not files: print("\nNo files with uncovered new lines found.") else: shown = 0 for f in files: if shown >= args.limit: remaining = len(files) - shown print(f"\n... and {remaining} more files (use --limit to show more)") break print(f"\n {f['path']}") print(f" {f['uncovered']}/{f['to_cover']} uncovered ({f['coverage']:.0f}% covered)") if args.lines: try: uncovered_lines = client.get_uncovered_lines(f["key"], pull_request=args.pr_number) if uncovered_lines: # Group consecutive lines ranges = [] start = end = uncovered_lines[0] if uncovered_lines else 0 for line in uncovered_lines[1:]: if line == end + 1: end = line else: ranges.append(f"{start}-{end}" if start != end else str(start)) start = end = line if uncovered_lines: ranges.append(f"{start}-{end}" if start != end else str(start)) print(f" Lines: {', '.join(ranges[:20])}") if len(ranges) > 20: print(f" ... and {len(ranges) - 20} more ranges") except Exception as e: print(f" (Could not get line details: {e})") shown += 1 print(f"\n\nTotal: {sum(f['uncovered'] for f in files)} uncovered lines across {len(files)} files") except Exception as e: print(f"Error: {e}") import traceback traceback.print_exc() elif args.command == "tangles": print(f"\n Architecture Analysis for {PROJECT_KEY}") print("=" * 70) print(f"Branch: {args.branch}") try: # Try to get architecture/dependency info arch_info = client.get_architecture_info(branch=args.branch) if arch_info.get("type") == "measures": measures_data = arch_info.get("data", {}) component = measures_data.get("component", {}) measures = {m["metric"]: m.get("value", "N/A") for m in component.get("measures", [])} print("\n Complexity Metrics:") if "complexity" in measures: print(f" Cyclomatic Complexity: {measures['complexity']}") if "cognitive_complexity" in measures: print(f" Cognitive Complexity: {measures['cognitive_complexity']}") if "file_complexity" in measures: print(f" Avg File Complexity: {measures['file_complexity']}") if "function_complexity" in measures: print(f" Avg Function Complexity: {measures['function_complexity']}") if "duplicated_lines_density" in measures: print(f" Duplicated Lines: {measures['duplicated_lines_density']}%") if "sqale_debt_ratio" in measures: print(f" Technical Debt Ratio: {measures['sqale_debt_ratio']}%") print("\n Note: SonarCloud's architecture tangle visualization") print(" requires viewing in the web UI:") print(f" https://sonarcloud.io/project/architecture/tangles?id={PROJECT_KEY}") print("\n A 'tangle' is a group of files with cyclic dependencies") print(" (A→B→C→A). These make code harder to maintain and test.") elif arch_info.get("type") == "error": print(f"\n[WARN] Could not retrieve architecture data: {arch_info.get('error')}") print("\n The tangle visualization may require viewing in the web UI:") print(f" https://sonarcloud.io/project/architecture/tangles?id={PROJECT_KEY}") # Try to get high-complexity files as proxy for architecture issues print("\n High Complexity Files (potential tangle participants):") try: tree_data = client.get_measures_component_tree( metrics=["complexity", "cognitive_complexity"], branch=args.branch, qualifier="FIL" ) components = tree_data.get("components", []) # Sort by complexity complex_files = [] for comp in components: measures = {m["metric"]: float(m.get("value", 0)) for m in comp.get("measures", [])} complexity = measures.get("complexity", 0) + measures.get("cognitive_complexity", 0) if complexity > 50: # Threshold for "high complexity" complex_files.append( { "path": comp.get("path", comp.get("key", "").split(":")[-1]), "complexity": measures.get("complexity", 0), "cognitive": measures.get("cognitive_complexity", 0), } ) complex_files.sort(key=lambda x: -(x["complexity"] + x["cognitive"])) if complex_files: for f in complex_files[:15]: print(f" {f['path']}") print(f" Cyclomatic: {f['complexity']:.0f}, Cognitive: {f['cognitive']:.0f}") else: print(" No files with complexity > 50 found.") except Exception as e: print(f" Could not retrieve complexity data: {e}") except Exception as e: print(f"Error: {e}") import traceback traceback.print_exc() else: parser.print_help() except requests.exceptions.HTTPError as e: print(f"Error: {e}") if e.response.status_code == 401: print("Authentication failed. Check your token in ~/.sonartoken") elif e.response.status_code == 403: print("Permission denied. You may not have access to perform this action.") sys.exit(1) except Exception as e: print(f"Error: {e}") sys.exit(1) if __name__ == "__main__": main()
#!/usr/bin/env python3
"""
SonarCloud Issue Management Tool
Simple CLI for managing SonarCloud issues for the CIRIS project.
Uses token from ~/.sonartoken for authentication.
Usage:
# Quality Gate Status (IMPORTANT: Shows both PR and main status!)
python -m tools.analysis.sonar quality-gate # PR + main branch status
python -m tools.analysis.sonar status # Main branch status only
# Issue Management
python -m tools.analysis.sonar list [--severity CRITICAL] [--limit 10]
python -m tools.analysis.sonar mark-fp ISSUE_KEY [--comment "Reason"]
python -m tools.analysis.sonar mark-wontfix ISSUE_KEY [--comment "Reason"]
python -m tools.analysis.sonar reopen ISSUE_KEY
python -m tools.analysis.sonar stats
# Security & Coverage
python -m tools.analysis.sonar hotspots [--status TO_REVIEW]
python -m tools.analysis.sonar coverage [--new-code] [--pr PR_NUMBER]
python -m tools.analysis.sonar pr PR_NUMBER # Detailed PR analysis
NOTE:
- 'quality-gate' shows BOTH PR and main status (use this for PR checks!)
- 'status' only shows main branch (use for overall project health)
- SonarCloud analysis runs ~15 minutes after CI completes
"""
import argparse
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import requests
# Configuration
SONAR_TOKEN_FILE = Path.home() / ".sonartoken"
SONAR_API_BASE = "https://sonarcloud.io/api"
PROJECT_KEY = "CIRISAI_CIRISAgent"
class SonarClient:
"""Simple SonarCloud API client."""
def __init__(self, token: str):
self.token = token
self.session = requests.Session()
self.session.headers.update({"Authorization": f"Bearer {token}"})
def search_issues(
self, severity: Optional[str] = None, resolved: bool = False, limit: int = 20
) -> List[Dict[str, Any]]:
"""Search for issues in the project."""
params = {"componentKeys": PROJECT_KEY, "resolved": str(resolved).lower(), "ps": limit}
if severity:
params["severities"] = severity.upper()
response = self.session.get(f"{SONAR_API_BASE}/issues/search", params=params)
response.raise_for_status()
return response.json()["issues"]
def transition_issue(self, issue_key: str, transition: str, comment: Optional[str] = None) -> Dict[str, Any]:
"""Transition an issue (mark as false positive, won't fix, etc)."""
data = {"issue": issue_key, "transition": transition}
if comment:
data["comment"] = comment
response = self.session.post(
f"{SONAR_API_BASE}/issues/do_transition",
data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
response.raise_for_status()
return response.json()
def add_comment(self, issue_key: str, comment: str) -> Dict[str, Any]:
"""Add a comment to an issue."""
data = {"issue": issue_key, "text": comment}
response = self.session.post(
f"{SONAR_API_BASE}/issues/add_comment",
data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
response.raise_for_status()
return response.json()
def get_stats(self) -> Dict[str, Any]:
"""Get issue statistics for the project."""
response = self.session.get(
f"{SONAR_API_BASE}/issues/search",
params={"componentKeys": PROJECT_KEY, "resolved": "false", "facets": "severities,types,rules", "ps": 1},
)
response.raise_for_status()
data = response.json()

Xet Storage Details

Size:
46.9 kB
·
Xet hash:
77cf4d551f3717465e5e0cf4c4239d895c27039c2590eaa0fa8b12ff23bf80af

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.