Last active
July 4, 2022 02:35
-
-
Save sttor/8af3c401195082e31977a324639f2d6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests, json, os, time, sys | |
| class SonarQubeReportSlack: | |
| def __init__(self): | |
| self.slack_token = os.getenv("slack_token") | |
| self.fail_build = os.getenv("fail_build", "false") | |
| self.component = os.getenv("component") | |
| self.slack_channel = os.getenv("slack_channel") | |
| self.sonar_url = os.getenv("sonar_url") | |
| self.sonar_username = os.getenv("sonar_username") | |
| self.sonar_password = os.getenv("sonar_password") | |
| def wait_for_analysis(self): | |
| print("waiting for analysis") | |
| ATTEMPTS = 10 | |
| url = self.sonar_url + "/api/ce/component?component=%s"%(self.component,) | |
| while True: | |
| res = requests.get(url, auth=(self.sonar_username, self.sonar_password)).json() | |
| print(res) | |
| if "queue" not in res.keys() or ATTEMPTS == 0: | |
| break | |
| time.sleep(10) | |
| ATTEMPTS-=1 | |
| def generate_summary_and_report(self): | |
| cmd = """sonar-report --sonarurl="%s" --sonarusername="%s" --sonarpassword="%s" --sonarcomponent="%s" --allbugs="false" > sonar_report.html""" | |
| cmd=cmd%(self.sonar_url,self.sonar_username,self.sonar_password, self.component) | |
| os.system(cmd) | |
| with open('sonar_report.html') as f: report = f.read() | |
| print("report:",report) | |
| count, summary = self.generate_summary() | |
| print(summary) | |
| print("::set-output name=summary::%s."%summary) | |
| self.post_file_to_slack( | |
| summary, | |
| 'Report.html', | |
| report) | |
| # Block Build in case of blocker | |
| print("done") | |
| if int(count) > 1 and self.fail_build == "true": | |
| sys.exit(1) | |
| def generate_summary(self): | |
| url = self.sonar_url + "/api/issues/search?types=VULNERABILITY&severities=BLOCKER,CRITICAL" | |
| res = requests.get(url, auth=(self.sonar_username, self.sonar_password)).json() | |
| count = str(res["paging"]["total"]) | |
| return count,"%s Blocker and Critical Security Issues Identified in the Repository"%(count,) | |
| def post_file_to_slack( | |
| self, text, file_name, file_bytes, file_type=None, title='SonarQube HTML Report ' | |
| ): | |
| return requests.post( | |
| 'https://slack.com/api/files.upload', | |
| { | |
| 'token': self.slack_token, | |
| 'filename': file_name, | |
| 'channels': self.slack_channel, | |
| 'filetype': file_type, | |
| 'initial_comment': text, | |
| 'title': title | |
| }, | |
| files={'file': file_bytes}).json() | |
| def run(self): | |
| self.wait_for_analysis() | |
| self.generate_summary_and_report() | |
| SonarQubeReportSlack().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment