Skip to content
This repository has been archived by the owner on Feb 19, 2024. It is now read-only.

Commit

Permalink
Lint files
Browse files Browse the repository at this point in the history
  • Loading branch information
Chelsea Boling committed Nov 3, 2021
1 parent 41284a5 commit e9a9a3c
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 104 deletions.
64 changes: 30 additions & 34 deletions ghlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def alerts_helper(self, api_segment, state=None):

try:
resp = requests.get(
'{api_url}/repos/{repo_id}/{api_segment}/alerts?per_page={results_per_page}{state}'.format(
"{api_url}/repos/{repo_id}/{api_segment}/alerts?per_page={results_per_page}{state}".format(
api_url=self.gh.url,
repo_id=self.repo_id,
api_segment=api_segment,
Expand Down Expand Up @@ -194,32 +194,28 @@ def alerts_helper(self, api_segment, state=None):

def get_info(self):
resp = requests.get(
'{api_url}/repos/{repo_id}'.format(
api_url=self.gh.url,
repo_id=self.repo_id
"{api_url}/repos/{repo_id}".format(
api_url=self.gh.url, repo_id=self.repo_id
),
headers=self.gh.default_headers(),
timeout=util.REQUEST_TIMEOUT
timeout=util.REQUEST_TIMEOUT,
)
resp.raise_for_status()
return resp.json()


def isprivate(self):
return self.get_info()['private']

return self.get_info()["private"]

def get_alerts(self, state=None):
for a in self.alerts_helper('code-scanning', state):
for a in self.alerts_helper("code-scanning", state):
yield Alert(self, a)


def get_secrets(self, state=None):
# secret scanning alerts are only accessible on private repositories, so
# we return an empty list on public ones
if not self.isprivate():
return
for a in self.alerts_helper('secret-scanning', state):
for a in self.alerts_helper("secret-scanning", state):
yield Secret(self, a)

def get_alert(self, alert_num):
Expand Down Expand Up @@ -249,13 +245,13 @@ def __init__(self, github_repo, json):
self.json = json

def get_state(self):
return self.json['state'] == 'open'
return self.json["state"] == "open"

def get_type(self):
return type(self).__name__

def number(self):
return int(self.json['number'])
return int(self.json["number"])

def short_desc(self):
raise NotImplementedError
Expand All @@ -264,7 +260,7 @@ def long_desc(self):
raise NotImplementedError

def hyperlink(self):
return self.json['html_url']
return self.json["html_url"]

def can_transition(self):
return True
Expand All @@ -279,9 +275,9 @@ def adjust_state(self, target_state):
logger.info(
'{action} {atype} {alert_num} of repository "{repo_id}".'.format(
atype=self.get_type(),
action='Reopening' if target_state else 'Closing',
action="Reopening" if target_state else "Closing",
alert_num=self.number(),
repo_id=self.github_repo.repo_id
repo_id=self.github_repo.repo_id,
)
)
self.do_adjust_state(target_state)
Expand All @@ -292,24 +288,22 @@ def __init__(self, github_repo, json):
AlertBase.__init__(self, github_repo, json)

def can_transition(self):
return self.json['state'] != 'fixed'
return self.json["state"] != "fixed"

def long_desc(self):
return self.json['rule']['description']
return self.json["rule"]["description"]

def short_desc(self):
return self.json['rule']['id']
return self.json["rule"]["id"]

def get_key(self):
return util.make_key(
self.github_repo.repo_id + '/' + str(self.number())
)
return util.make_key(self.github_repo.repo_id + "/" + str(self.number()))

def do_adjust_state(self, target_state):
state = 'open'
reason = ''
state = "open"
reason = ""
if not target_state:
state = 'dismissed'
state = "dismissed"
reason = ', "dismissed_reason": "won\'t fix"'
data = '{{"state": "{state}"{reason}}}'.format(state=state, reason=reason)
resp = requests.patch(
Expand All @@ -333,31 +327,33 @@ def can_transition(self):
return True

def long_desc(self):
return self.json['secret_type']
return self.json["secret_type"]

def short_desc(self):
return self.long_desc()

def get_key(self):
return util.make_key(
self.github_repo.repo_id + '/' + self.get_type() + '/' + str(self.number())
self.github_repo.repo_id + "/" + self.get_type() + "/" + str(self.number())
)

def do_adjust_state(self, target_state):
state = 'open'
resolution = ''
state = "open"
resolution = ""
if not target_state:
state = 'resolved'
state = "resolved"
resolution = ', "resolution": "wont_fix"'
data = '{{"state": "{state}"{resolution}}}'.format(state=state, resolution=resolution)
data = '{{"state": "{state}"{resolution}}}'.format(
state=state, resolution=resolution
)
resp = requests.patch(
'{api_url}/repos/{repo_id}/secret-scanning/alerts/{alert_num}'.format(
"{api_url}/repos/{repo_id}/secret-scanning/alerts/{alert_num}".format(
api_url=self.gh.url,
repo_id=self.github_repo.repo_id,
alert_num=self.number()
alert_num=self.number(),
),
data=data,
headers=self.gh.default_headers(),
timeout=util.REQUEST_TIMEOUT
timeout=util.REQUEST_TIMEOUT,
)
resp.raise_for_status()
40 changes: 18 additions & 22 deletions jiralib.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@


TITLE_PREFIXES = {
'Alert': '[Code Scanning Alert]:',
'Secret': '[Secret Scanning Alert]:'
"Alert": "[Code Scanning Alert]:",
"Secret": "[Secret Scanning Alert]:",
}

DESC_TEMPLATE="""
DESC_TEMPLATE = """
{long_desc}
{alert_url}
Expand Down Expand Up @@ -162,12 +162,9 @@ def save_repo_state(self, repo_id, state, issue_key="-"):

# attach the new state file
self.jira.attach_file(
i.key,
repo_id_to_fname(repo_id),
util.state_to_json(state)
i.key, repo_id_to_fname(repo_id), util.state_to_json(state)
)


def create_issue(
self,
repo_id,
Expand All @@ -177,14 +174,12 @@ def create_issue(
alert_type,
alert_num,
repo_key,
alert_key
alert_key,
):
raw = self.j.create_issue(
project=self.projectkey,
summary='{prefix} {short_desc} in {repo}'.format(
prefix=TITLE_PREFIXES[alert_type],
short_desc=short_desc,
repo=repo_id
summary="{prefix} {short_desc} in {repo}".format(
prefix=TITLE_PREFIXES[alert_type], short_desc=short_desc, repo=repo_id
),
description=DESC_TEMPLATE.format(
long_desc=long_desc,
Expand All @@ -193,7 +188,7 @@ def create_issue(
alert_type=alert_type,
alert_num=alert_num,
repo_key=repo_key,
alert_key=alert_key
alert_key=alert_key,
),
issuetype={"name": "Bug"},
labels=self.labels,
Expand All @@ -203,16 +198,17 @@ def create_issue(
issue_key=raw.key, alert_num=alert_num, repo_id=repo_id
)
)
logger.info('Created issue {issue_key} for {alert_type} {alert_num} in {repo_id}.'.format(
issue_key=raw.key,
alert_type=alert_type,
alert_num=alert_num,
repo_id=repo_id
))
logger.info(
"Created issue {issue_key} for {alert_type} {alert_num} in {repo_id}.".format(
issue_key=raw.key,
alert_type=alert_type,
alert_num=alert_num,
repo_id=repo_id,
)
)

return JiraIssue(self, raw)


def fetch_issues(self, key):
issue_search = 'project={jira_project} and description ~ "{key}"'.format(
jira_project='"{}"'.format(self.projectkey), key=key
Expand Down Expand Up @@ -325,12 +321,12 @@ def parse_alert_info(desc):
return failed
repo_id = m.group(1)

m = re.search('ALERT_TYPE=(.*)$', desc, re.MULTILINE)
m = re.search("ALERT_TYPE=(.*)$", desc, re.MULTILINE)
if m is None:
alert_type = None
else:
alert_type = m.group(1)
m = re.search('ALERT_NUMBER=(.*)$', desc, re.MULTILINE)
m = re.search("ALERT_NUMBER=(.*)$", desc, re.MULTILINE)

if m is None:
return failed
Expand Down
6 changes: 3 additions & 3 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def jira_webhook():
):
return jsonify({"code": 403, "error": "Unauthorized"}), 403

payload = json.loads(request.data.decode('utf-8'))
event = payload['webhookEvent']
desc = payload['issue']['fields']['description']
payload = json.loads(request.data.decode("utf-8"))
event = payload["webhookEvent"]
desc = payload["issue"]["fields"]["description"]
repo_id, _, _, _, _ = jiralib.parse_alert_info(desc)

app.logger.debug('Received JIRA webhook for event "{event}"'.format(event=event))
Expand Down
43 changes: 8 additions & 35 deletions sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,54 +19,30 @@ def __init__(self, github, jira_project, direction=DIRECTION_BOTH):

def alert_created(self, repo_id, alert_num):
a = self.github.getRepository(repo_id).get_alert(alert_num)
self.sync(
a,
self.jira.fetch_issues(a.get_key()),
DIRECTION_G2J
)
self.sync(a, self.jira.fetch_issues(a.get_key()), DIRECTION_G2J)

def alert_changed(self, repo_id, alert_num):
a = self.github.getRepository(repo_id).get_alert(alert_num)
self.sync(
a,
self.jira.fetch_issues(a.get_key()),
DIRECTION_G2J
)
self.sync(a, self.jira.fetch_issues(a.get_key()), DIRECTION_G2J)

def alert_fixed(self, repo_id, alert_num):
a = self.github.getRepository(repo_id).get_alert(alert_num)
self.sync(
a,
self.jira.fetch_issues(a.get_key()),
DIRECTION_G2J
)
self.sync(a, self.jira.fetch_issues(a.get_key()), DIRECTION_G2J)

def issue_created(self, desc):
repo_id, alert_num, _, _, _ = jiralib.parse_alert_info(desc)
a = self.github.getRepository(repo_id).get_alert(alert_num)
self.sync(
a,
self.jira.fetch_issues(a.get_key()),
DIRECTION_J2G
)
self.sync(a, self.jira.fetch_issues(a.get_key()), DIRECTION_J2G)

def issue_changed(self, desc):
repo_id, alert_num, _, _, _ = jiralib.parse_alert_info(desc)
a = self.github.getRepository(repo_id).get_alert(alert_num)
self.sync(
a,
self.jira.fetch_issues(a.get_key()),
DIRECTION_J2G
)
self.sync(a, self.jira.fetch_issues(a.get_key()), DIRECTION_J2G)

def issue_deleted(self, desc):
repo_id, alert_num, _, _, _ = jiralib.parse_alert_info(desc)
a = self.github.getRepository(repo_id).get_alert(alert_num)
self.sync(
a,
self.jira.fetch_issues(a.get_key()),
DIRECTION_J2G
)
self.sync(a, self.jira.fetch_issues(a.get_key()), DIRECTION_J2G)

def sync(self, alert, issues, in_direction):
if alert is None:
Expand All @@ -87,7 +63,7 @@ def sync(self, alert, issues, in_direction):
alert.get_type(),
alert.number(),
alert.github_repo.get_key(),
alert.get_key()
alert.get_key(),
)
newissue.adjust_state(alert.get_state())
return alert.get_state()
Expand Down Expand Up @@ -132,10 +108,7 @@ def sync_repo(self, repo_id, states=None):
pairs = {}

# gather alerts
for a in itertools.chain(
repo.get_secrets(),
repo.get_alerts()
):
for a in itertools.chain(repo.get_secrets(), repo.get_alerts()):
pairs[a.get_key()] = (a, [])

# gather issues
Expand Down
13 changes: 3 additions & 10 deletions util.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,12 @@ def state_from_json(s):
j = json.loads(s)
if not "version" in j:
return {}
return j['states']
return j["states"]


def state_to_json(state):
final = {
'version': 2,
'states': state
}
return json.dumps(
final,
indent=2,
sort_keys=True
)
final = {"version": 2, "states": state}
return json.dumps(final, indent=2, sort_keys=True)


def state_from_file(fpath):
Expand Down

0 comments on commit e9a9a3c

Please sign in to comment.