1+ import json
2+ import os
3+ import sys
4+
5+ import requests
6+
7+
8+ def export_sonar_metrics_to_json (token , project_key = "acts-project_acts" , filename = "sonar_report.json" ):
9+ # Endpoint for component measures (SonarCloud Web API)
10+ url = "https://sonarcloud.io/api/measures/component"
11+
12+ metrics = "bugs,vulnerabilities,code_smells,coverage,duplicated_lines_density,security_rating,reliability_rating"
13+
14+ params = {
15+ "component" : project_key ,
16+ "metricKeys" : metrics ,
17+ "branch" : "main" ,
18+ }
19+
20+ # 2. Fetch data from SonarCloud
21+ try :
22+ # Use Basic Auth: pass the token as the username with an empty password
23+ response = requests .get (url , params = params , auth = (token , '' ))
24+
25+ # Raise an exception for HTTP errors (4xx or 5xx)
26+ response .raise_for_status ()
27+
28+ # Parse the JSON response
29+ data = response .json ()
30+
31+ # 3. Save the result to a local JSON file
32+ # indent=4 makes the file human-readable (pretty-print)
33+ with open (filename , 'w' , encoding = 'utf-8' ) as f :
34+ json .dump (data , f , indent = 4 )
35+
36+ print (f"Success! Report saved to: { filename } " )
37+
38+ except requests .exceptions .RequestException as e :
39+ print (f"An error occurred during the API request: { e } " )
40+ raise SystemExit (1 ) from e
41+ except Exception as e :
42+ print (f"An unexpected error occurred: { e } " )
43+ raise SystemExit (1 ) from e
44+
45+
46+ if __name__ == "__main__" :
47+ token = os .environ .get ("SONAR_TOKEN" )
48+ if not token :
49+ print ("Error: SONAR_TOKEN environment variable is not set" , file = sys .stderr )
50+ raise SystemExit (1 )
51+ export_sonar_metrics_to_json (token )
0 commit comments