blob: d9707c07a70747b4ea395933e50c002d7d23116f [file] [log] [blame]
Hal Canaryb5680ca2018-04-03 17:25:15 -04001#!/usr/bin/env python2
Hal Canaryd2ded552017-12-18 12:01:18 -05002# Copyright 2017 Google Inc.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Hal Canaryd2ded552017-12-18 12:01:18 -05006import json
7import re
8import subprocess
9import sys
Hal Canarye0dc3462018-12-05 10:18:30 -050010import urllib
11
12# TODO(halcanary): document functions and script usage.
Hal Canaryd2ded552017-12-18 12:01:18 -050013
14def retrieve_changeid(commit_or_branch):
Hal Canarye0dc3462018-12-05 10:18:30 -050015 try:
16 cmd = ['git', 'log', '-1', '--format=%B', commit_or_branch, '--']
17 body = subprocess.check_output(cmd)
18 except OSError:
19 raise Exception('git not found')
20 except subprocess.CalledProcessError:
21 raise Exception('`%s` failed' % ' '.join(cmd))
22 match = re.search(r'^Change-Id: *(.*) *$', body, re.MULTILINE)
23 if match is None:
24 raise Exception('Change-Id field missing from commit %s' % commit_or_branch)
25 return match.group(1)
Hal Canaryd2ded552017-12-18 12:01:18 -050026
Hal Canarye0dc3462018-12-05 10:18:30 -050027
28def gerrit_change_id_to_number(site, cid):
29 url = 'https://%s/changes/?q=change:%s' % (site, cid)
30 try:
31 content = urllib.urlopen(url).read()
32 except IOError:
33 raise Exception('error reading "%s"' % url)
34 try:
35 parsed = json.loads(content[content.find('['):])
36 except ValueError:
37 raise Exception('unable to parse content\n"""\n%s\n"""' % content)
38 try:
39 return parsed[0]['_number']
40 except (IndexError, KeyError):
41 raise Exception('Content missing\n"""\n%s\n"""' %
42 json.dumps(parsed, indent=2))
43
44
45def args_to_changeid(argv):
46 if len(argv) == 2 and len(argv[1]) == 41 and argv[1][0] == 'I':
47 return argv[1]
48 else:
49 return retrieve_changeid(argv[1] if len(argv) == 2 else 'HEAD')
50
Hal Canaryd2ded552017-12-18 12:01:18 -050051
52if __name__ == '__main__':
53 try:
Hal Canarye0dc3462018-12-05 10:18:30 -050054 sys.stdout.write('%d\n' %
55 gerrit_change_id_to_number('skia-review.googlesource.com',
56 args_to_changeid(sys.argv)))
57 except Exception as e:
58 sys.stderr.write('%s\n' % e)
59 sys.exit(1)
60
61