#!/usr/bin/env python
# Copyright 2017 Google Inc.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import httplib
import json
import re
import subprocess
import sys

def retrieve_changeid(commit_or_branch):
  b = subprocess.check_output(['git', 'log', '-1', '--format=%B', commit_or_branch])
  r = re.compile(r'^Change-Id: (.*)$')
  for l in b.split('\n'):
    m = r.match(l)
    if m:
      return m.group(1)
  return None

def gerrit_change_id_to_number(cid):
    conn = httplib.HTTPSConnection('skia-review.googlesource.com')
    conn.request('GET', '/changes/?q=change:%s' % cid)
    r = conn.getresponse()
    assert(r.status == 200)
    x = r.read()
    i = 0
    while i < len(x) and x[i] != '[':
      i += 1
    print json.loads(x[i:])[0]['_number']

if __name__ == '__main__':
  try:
    if len(sys.argv) == 2 and len(sys.argv[1]) == 41 and sys.argv[1][0] == 'I':
      gerrit_change_id_to_number(sys.argv[1])
    else:
      changeid = retrieve_changeid(sys.argv[1] if len(sys.argv) == 2 else 'HEAD')
      if changeid is None:
        exit(2)
      gerrit_change_id_to_number(changeid)
  except:
    exit(1)