Skip to content

Instantly share code, notes, and snippets.

@mccutchen
Last active November 6, 2019 00:16
Show Gist options
  • Save mccutchen/6acb68768f363ee7d0c4b72f14c33e2c to your computer and use it in GitHub Desktop.
Save mccutchen/6acb68768f363ee7d0c4b72f14c33e2c to your computer and use it in GitHub Desktop.
Proof-of-concept showing how to use GitHub's v4 GraphQL API to look up the pull request associated with an arbitrary commit
#!/usr/bin/env python3
import os
import sys
import requests
def run_query(api_token, query):
url = 'https://api.github.com/graphql'
headers = {'Authorization': f'bearer {api_token}'}
body = {'query': query}
resp = requests.post(url, json=body, headers=headers)
if resp.status_code != 200:
raise Exception(f'Query failed: HTTP {resp.status_code}: {resp.content}')
return resp.json()
def lookup_pull_requests(api_token, commit, limit):
results = run_query(api_token, """
{
repository(name: "mono", owner: "buzzfeed") {
commit: object(expression: "%(commit)s") {
... on Commit {
associatedPullRequests(first:%(limit)d){
edges{
node{
number
}
}
}
}
}
}
}
""" % dict(commit=commit, limit=limit))
return [
edge['node']['number'] for edge in
results['data']['repository']['commit']['associatedPullRequests']['edges']
]
def main(api_token, commit):
pull_request = lookup_pull_requests(api_token, commit, 1)[0]
print(pull_request)
if __name__ == '__main__':
if len(sys.argv) < 2:
print(f'Usage: {sys.argv[0]} COMMIT_HASH', file=sys.stderr)
sys.exit(1)
commit = sys.argv[1]
api_token = os.environ.get('GITHUB_API_TOKEN')
if not api_token:
print('Error: GITHUB_API_TOKEN env var required', file=sys.stderr)
sys.exit(1)
main(api_token, commit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment