Teach 'repo upload --replace' how to add replacement patch sets

Users are prompted with the list of known changes we are about
to upload, and they can fill out the current change numbers for
any changes which already exist in the data store.  For each of
those changes the change number and commit id is sent as part of
the upload request, so Gerrit can insert the new commit as a new
patch set of the existing change, rather than make a new change.

This facility permits developers to replace a patch so they can
address comments made on a prior version of the same change.

Signed-off-by: Shawn O. Pearce <sop@google.com>
diff --git a/subcmds/upload.py b/subcmds/upload.py
index 9018455..11f035d 100644
--- a/subcmds/upload.py
+++ b/subcmds/upload.py
@@ -29,7 +29,7 @@
   common = True
   helpSummary = "Upload changes for code review"
   helpUsage="""
-%prog [<project>]...
+%prog {[<project>]... | --replace <project>}
 """
   helpDescription = """
 The '%prog' command is used to send changes to the Gerrit code
@@ -46,6 +46,11 @@
 changes in all projects listed in the manifest.
 """
 
+  def _Options(self, p):
+    p.add_option('--replace',
+                 dest='replace', action='store_true',
+                 help='Upload replacement patchesets from this branch')
+
   def _SingleBranch(self, branch):
     project = branch.project
     name = branch.name
@@ -129,6 +134,50 @@
       _die("nothing uncommented for upload")
     self._UploadAndReport(todo)
 
+  def _ReplaceBranch(self, project):
+    branch = project.CurrentBranch
+    if not branch:
+      print >>sys.stdout, "no branches ready for upload"
+      return
+    branch = project.GetUploadableBranch(branch)
+    if not branch:
+      print >>sys.stdout, "no branches ready for upload"
+      return
+
+    script = []
+    script.append('# Replacing from branch %s' % branch.name)
+    for commit in branch.commits:
+      script.append('[      ] %s' % commit)
+    script.append('')
+    script.append('# Insert change numbers in the brackets to add a new patch set.')
+    script.append('# To create a new change record, leave the brackets empty.')
+
+    script = Editor.EditString("\n".join(script)).split("\n")
+
+    change_re = re.compile(r'^\[\s*(\d{1,})\s*\]\s*([0-9a-f]{1,}) .*$')
+    to_replace = dict()
+    full_hashes = branch.unabbrev_commits
+
+    for line in script:
+      m = change_re.match(line)
+      if m:
+        f = m.group(2)
+        try:
+          f = full_hashes[f]
+        except KeyError:
+          print 'fh = %s' % full_hashes
+          print >>sys.stderr, "error: commit %s not found" % f
+          sys.exit(1)
+        to_replace[m.group(1)] = f
+
+    if not to_replace:
+      print >>sys.stderr, "error: no replacements specified"
+      print >>sys.stderr, "       use 'repo upload' without --replace"
+      sys.exit(1)
+
+    branch.replace_changes = to_replace
+    self._UploadAndReport([branch])
+
   def _UploadAndReport(self, todo):
     have_errors = False
     for branch in todo:
@@ -168,6 +217,14 @@
     project_list = self.GetProjects(args)
     pending = []
 
+    if opt.replace:
+      if len(project_list) != 1:
+        print >>sys.stderr, \
+              'error: --replace requires exactly one project'
+        sys.exit(1)
+      self._ReplaceBranch(project_list[0])
+      return
+
     for project in project_list:
       avail = project.GetUploadableBranches()
       if avail: