|
| 1 | +""" |
| 2 | +This script runs only on travis to create the status for the latest commit |
| 3 | +in the PR. |
| 4 | +
|
| 5 | +Reference: https://developer.github.com/v3/repos/statuses/#create-a-status |
| 6 | +""" |
| 7 | +import os |
| 8 | +import requests |
| 9 | + |
| 10 | +GITHUB_REPO = 'sympy/sympy_gamma' |
| 11 | +GITHUB_API_URL = 'https://api.github.com' |
| 12 | +GITHUB_API_REF_URL = "%s/repos/%s/git/matching-refs/heads/" % (GITHUB_API_URL, GITHUB_REPO) |
| 13 | +GITHUB_API_UPDATE_STATUS_URL = "%s/repos/%s/statuses/" % (GITHUB_API_URL, GITHUB_REPO) |
| 14 | +SYMPY_BOT_TOKEN_VAR = 'SYMPY_BOT_TOKEN' |
| 15 | + |
| 16 | + |
| 17 | +def get_branch_commit_sha(branch_name): |
| 18 | + """Gets the SHA of the last commit of the given branch |
| 19 | + :param branch_name: str name of branch on Github |
| 20 | + :return: str SHA |
| 21 | + """ |
| 22 | + response = requests.get(GITHUB_API_REF_URL + branch_name) |
| 23 | + if response.status_code == 200: |
| 24 | + response_json = response.json() |
| 25 | + else: |
| 26 | + raise ValueError('Invalid response from github API') |
| 27 | + return response_json[0]['object']['sha'] |
| 28 | + |
| 29 | + |
| 30 | +def update_pr_status_with_deployment(branch_name, commit_sha): |
| 31 | + """Updates the Status of the commit identified by commit SHA, which is reflected |
| 32 | + at the bottom of the PR, above merge button. |
| 33 | + :param branch_name: str name of branch on github |
| 34 | + :param commit_sha: str SHA |
| 35 | + :return: Response POST request to Github API |
| 36 | + """ |
| 37 | + sympy_bot_token = os.environ.get(SYMPY_BOT_TOKEN_VAR) |
| 38 | + deployment_url = "https://%s-dot-sympy-gamma-hrd.appspot.com" % branch_name |
| 39 | + payload = { |
| 40 | + "state": "success", |
| 41 | + "target_url": deployment_url, |
| 42 | + "description": "Deployed to version: %s" % branch_name, |
| 43 | + "context": "PR Deployment" |
| 44 | + } |
| 45 | + |
| 46 | + headers = { |
| 47 | + 'Authorization': 'Bearer %s' % sympy_bot_token, |
| 48 | + 'Content-Type': 'application/json' |
| 49 | + } |
| 50 | + |
| 51 | + update_status_url = GITHUB_API_UPDATE_STATUS_URL + commit_sha |
| 52 | + print "Update status URL: %s" % update_status_url |
| 53 | + response = requests.post(update_status_url, headers=headers, json=payload) |
| 54 | + print "Response: %s" % response.json() |
| 55 | + |
| 56 | + |
| 57 | +def main(): |
| 58 | + is_on_travis = os.environ.get('TRAVIS') |
| 59 | + if not is_on_travis: |
| 60 | + raise ValueError('This script run only on travis!') |
| 61 | + branch_name = os.environ.get('TRAVIS_BRANCH') |
| 62 | + commit_sha = get_branch_commit_sha(branch_name) |
| 63 | + print "Branch name: %s Commit SHA: %s" % (branch_name, commit_sha) |
| 64 | + print "Creating commit status ..." |
| 65 | + update_pr_status_with_deployment(branch_name, commit_sha) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == '__main__': |
| 69 | + main() |
0 commit comments