From 7d74758db35fc9345a4ac18e4c95e3373054f172 Mon Sep 17 00:00:00 2001 From: Jon Massey Date: Wed, 26 Jan 2022 16:14:38 +0000 Subject: [PATCH] feat: get most recent run of research action --- jobserver/github.py | 49 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/jobserver/github.py b/jobserver/github.py index 2063c9f70..9408edfaa 100644 --- a/jobserver/github.py +++ b/jobserver/github.py @@ -4,6 +4,7 @@ import requests from environs import Env from furl import furl +from ruamel.yaml import YAML env = Env() @@ -13,6 +14,7 @@ BASE_URL = "https://api.github.com" GITHUB_TOKEN = env.str("GITHUB_TOKEN") USER_AGENT = "OpenSAFELY Jobs" +RESEARCH_ACTION = "opensafely-core/research-action@v1" def _get_query_page(*, query, session, cursor, **kwargs): @@ -244,9 +246,9 @@ def get_repos_with_dates(): """ results = list(_iter_query_results(query)) for repo in results: - created_at = datetime.strptime(repo["createdAt"], "%Y-%m-%dT%H:%M:%SZ").replace( - tzinfo=timezone.utc - ) + created_at = datetime.strptime( + repo["createdAt"], "%Y-%m-%dT%H:%M:%SZ" + ).replace(tzinfo=timezone.utc) yield { "name": repo["name"], @@ -281,3 +283,44 @@ def is_member_of_org(org, username): return False r.raise_for_status() + + +def get_workflow_runs(org,repo,sha): + f = furl(BASE_URL) + f.path.segments += ["repos",org,repo,"actions","runs"] + headers = { + "Accept": "application/vnd.github.v3+json", + "Authorization": f"token {GITHUB_TOKEN}", + "User-Agent": USER_AGENT, + } + r = requests.get(f.url, headers=headers) + + if r.status_code == 404: + return + + r.raise_for_status() + for run in r.json()['workflow_runs']: + if run['head_sha'] == sha: + workflow_url = run['workflow_url'] + wr = requests.get(workflow_url,headers=headers) + wr.raise_for_status() + workflow = wr.json() + yamlurl = furl(workflow['html_url']) + yamlurl.path.segments[2]='raw' + yr = requests.get(yamlurl.url,headers=headers) + yr.raise_for_status() + yaml = YAML() + workflow_yaml = yaml.load(yr.text) + yield (workflow_yaml['jobs']['test']['steps'][0]['uses'], run['conclusion']) + + + +def check_research_action(org,repo,sha): + for workflow_run in get_workflow_runs(org,repo,sha): + if workflow_run[0] != RESEARCH_ACTION: + continue + if workflow_run[1] == "success": + return True + else: + return False + return False