def get_last_successfully_built_commit(branch):
''' Returns the hash of the latest successfully built commit
on the given branch according to Travis CI. '''
API_ENDPOINT='https://api.travis-ci.org/'
REPO_SLUG='kobotoolbox/kobocat'
COMMON_HEADERS={'accept': 'application/vnd.travis-ci.2+json'}
''' Travis only lets us specify `number`, `after_number`, and `event_type`.
It'd be great to filter by state and branch, but it seems we can't
(http://docs.travis-ci.com/api/?http#builds). '''
request = requests.get(
'{}repos/{}/builds'.format(API_ENDPOINT, REPO_SLUG),
headers=COMMON_HEADERS
)
if request.status_code != 200:
raise Exception('Travis returned unexpected code {}.'.format(
request.status_code
))
response = json.loads(request.text)
builds = response['builds']
commits = {commit['id']: commit for commit in response['commits']}
for build in builds:
if build['state'] != 'passed' or build['pull_request']:
# No interest in non-passing builds or PRs
continue
commit = commits[build['commit_id']]
if commit['branch'] == branch:
# Assumes the builds are in descending chronological order
if re.match('^[0-9a-f]+$', commit['sha']) is None:
raise Exception('Travis returned the invalid SHA {}.'.format(
commit['sha']))
return commit['sha']
raise Exception("Couldn't find a passing build for the branch {}. "
"This could be due to pagination, in which case this code "
"must be made more robust!".format(branch))
评论列表
文章目录