• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python2
2# 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
6import json
7import re
8import subprocess
9import sys
10import urllib
11
12# TODO(halcanary): document functions and script usage.
13
14def retrieve_changeid(commit_or_branch):
15  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)
26
27
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
51
52if __name__ == '__main__':
53  try:
54    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
62