bin/try: automatically set 'git cl issue' when not found

This eases the workflow for developers who don't use git-cl to upload
changes, but it doesn't remove the dependency on git-cl for triggering
try jobs. Doing so would require using the Buildbucket API directly,
which we're not well set up to do in Python. Eventually we'll be forced
to either migrate this tool to Python 3 or rewrite in Go, and at that
point we can use the API clients we already use from Go code to remove
the dependency on Depot Tools.

Change-Id: I749007a2150cfeb2442643db6f2a01a7a56c10a4
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/298748
Commit-Queue: Eric Boren <borenet@google.com>
Reviewed-by: Mike Klein <mtklein@google.com>
diff --git a/bin/try.py b/bin/try.py
index ccf9c2f..889b58c 100755
--- a/bin/try.py
+++ b/bin/try.py
@@ -16,6 +16,7 @@
 import subprocess
 import sys
 import tempfile
+import urllib2
 
 
 BUCKET_SKIA_PRIMARY = 'skia/skia.primary'
@@ -75,6 +76,31 @@
                       help='Job name or regular expression to match job names.')
   args = parser.parse_args()
 
+  # First, find the Gerrit issue number. If the change was uploaded using Depot
+  # Tools, this configuration will be present in the git config.
+  branch = subprocess.check_output(['git', 'branch', '--show-current']).rstrip()
+  if not branch:
+    print 'Not on any branch; cannot trigger try jobs.'
+    sys.exit(1)
+  branch_issue_config = 'branch.%s.gerritissue' % branch
+  try:
+    issue = subprocess.check_output([
+        'git', 'config', '--local', branch_issue_config])
+  except subprocess.CalledProcessError:
+    # Not using Depot Tools. Find the Change-Id line in the most recent commit
+    # and obtain the issue number using that.
+    print '"git cl issue" not set; searching for Change-Id footer.'
+    msg = subprocess.check_output(['git', 'log', '-n1', branch])
+    m = re.search('Change-Id: (I[a-f0-9]+)', msg)
+    if not m:
+      print ('No gerrit issue found in `git config --local %s` and no Change-Id'
+             ' found in most recent commit message.')
+      sys.exit(1)
+    url = 'https://skia-review.googlesource.com/changes/%s' % m.groups()[0]
+    resp = urllib2.urlopen(url).read()
+    issue = str(json.loads('\n'.join(resp.splitlines()[1:]))['_number'])
+    print 'Setting "git cl issue %s"' % issue
+    subprocess.check_call(['git', 'cl', 'issue', issue])
   # Load and filter the list of jobs.
   jobs = []
   tasks_json = os.path.join(find_repo_root(), TASKS_JSON)