merge_to_branch.py 9.79 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#!/usr/bin/env python
# Copyright 2014 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials provided
#       with the distribution.
#     * Neither the name of Google Inc. nor the names of its
#       contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

29 30 31
# for py2/py3 compatibility
from __future__ import print_function

32
import argparse
33
from collections import OrderedDict
34
import sys
35 36

from common_includes import *
37
from git_recipes import GetCommitMessageFooterMap
38

39 40 41
def IsSvnNumber(rev):
  return rev.isdigit() and len(rev) < 8

42 43 44 45
class Preparation(Step):
  MESSAGE = "Preparation."

  def RunStep(self):
46
    if os.path.exists(self.Config("ALREADY_MERGING_SENTINEL_FILE")):
47
      if self._options.force:
48
        os.remove(self.Config("ALREADY_MERGING_SENTINEL_FILE"))
49
      elif self._options.step == 0:  # pragma: no cover
50
        self.Die("A merge is already in progress. Use -f to continue")
51
    open(self.Config("ALREADY_MERGING_SENTINEL_FILE"), "a").close()
52

53
    self.InitialEnvironmentChecks(self.default_cwd)
54 55

    self["merge_to_branch"] = self._options.branch
56 57 58 59 60 61 62 63 64

    self.CommonPrepare()
    self.PrepareBranch()


class CreateBranch(Step):
  MESSAGE = "Create a fresh branch for the patch."

  def RunStep(self):
65
    self.GitCreateBranch(self.Config("BRANCHNAME"),
66
                         self.vc.RemoteBranch(self["merge_to_branch"]))
67 68 69 70 71 72


class SearchArchitecturePorts(Step):
  MESSAGE = "Search for corresponding architecture ports."

  def RunStep(self):
73 74
    self["full_revision_list"] = list(OrderedDict.fromkeys(
        self._options.revisions))
75
    port_revision_list = []
76
    for revision in self["full_revision_list"]:
77
      # Search for commits which matches the "Port XXX" pattern.
78
      git_hashes = self.GitLog(reverse=True, format="%H",
79
                               grep="^[Pp]ort %s" % revision,
80
                               branch=self.vc.RemoteMainBranch())
81 82
      for git_hash in git_hashes.splitlines():
        revision_title = self.GitLog(n=1, format="%s", git_hash=git_hash)
83 84

        # Is this revision included in the original revision list?
85 86 87
        if git_hash in self["full_revision_list"]:
          print("Found port of %s -> %s (already included): %s"
                % (revision, git_hash, revision_title))
88
        else:
89 90 91
          print("Found port of %s -> %s: %s"
                % (revision, git_hash, revision_title))
          port_revision_list.append(git_hash)
92 93 94 95 96 97

    # Do we find any port?
    if len(port_revision_list) > 0:
      if self.Confirm("Automatically add corresponding ports (%s)?"
                      % ", ".join(port_revision_list)):
        #: 'y': Add ports to revision list.
98
        self["full_revision_list"].extend(port_revision_list)
99 100


101 102
class CreateCommitMessage(Step):
  MESSAGE = "Create commit message."
103

104 105 106 107 108 109
  def _create_commit_description(self, commit_hash):
    patch_merge_desc = self.GitLog(n=1, format="%s", git_hash=commit_hash)
    description = "Merged: " + patch_merge_desc + "\n"
    description += "Revision: " + commit_hash + "\n\n"
    return description

110 111
  def RunStep(self):

112 113
    # Stringify: ["abcde", "12345"] -> "abcde, 12345"
    self["revision_list"] = ", ".join(self["full_revision_list"])
114

115
    if not self["revision_list"]:  # pragma: no cover
116 117
      self.Die("Revision list is empty.")

118
    msg_pieces = []
119

120 121 122 123 124 125 126
    if len(self["full_revision_list"]) > 1:
      self["commit_title"] = "Merged: Squashed multiple commits."
      for commit_hash in self["full_revision_list"]:
        msg_pieces.append(self._create_commit_description(commit_hash))
    else:
      commit_hash = self["full_revision_list"][0]
      full_description = self._create_commit_description(commit_hash).split("\n")
127

128 129 130 131 132 133 134
      #Truncate title because of code review tool
      title = full_description[0]
      if len(title) > 100:
        title = title[:96] + " ..."

      self["commit_title"] = title
      msg_pieces.append(full_description[1] + "\n\n")
135 136

    bugs = []
137
    for commit_hash in self["full_revision_list"]:
138
      msg = self.GitLog(n=1, git_hash=commit_hash)
139 140
      for bug in re.findall(r"^[ \t]*BUG[ \t]*=[ \t]*(.*?)[ \t]*$", msg, re.M):
        bugs.extend(s.strip() for s in bug.split(","))
141 142 143 144
      gerrit_bug = GetCommitMessageFooterMap(msg).get('Bug', '')
      bugs.extend(s.strip() for s in gerrit_bug.split(","))
    bug_aggregate = ",".join(
        sorted(filter(lambda s: s and s != "none", set(bugs))))
145
    if bug_aggregate:
146 147
      # TODO(machenbach): Use proper gerrit footer for bug after switch to
      # gerrit. Keep BUG= for now for backwards-compatibility.
148
      msg_pieces.append("BUG=%s\n" % bug_aggregate)
149

150 151
    msg_pieces.append("NOTRY=true\nNOPRESUBMIT=true\nNOTREECHECKS=true\n")

152
    self["new_commit_msg"] = "".join(msg_pieces)
153 154 155 156 157 158


class ApplyPatches(Step):
  MESSAGE = "Apply patches for selected revisions."

  def RunStep(self):
159
    for commit_hash in self["full_revision_list"]:
160
      print("Applying patch for %s to %s..."
161
            % (commit_hash, self["merge_to_branch"]))
162
      patch = self.GitGetPatch(commit_hash)
163
      TextToFile(patch, self.Config("TEMPORARY_PATCH_FILE"))
164
      self.ApplyPatch(self.Config("TEMPORARY_PATCH_FILE"))
165
    if self._options.patch:
166
      self.ApplyPatch(self._options.patch)
167 168 169 170 171

class CommitLocal(Step):
  MESSAGE = "Commit to local branch."

  def RunStep(self):
172
    # Add a commit message title.
173 174
    self["new_commit_msg"] = "%s\n\n%s" % (self["commit_title"],
                                           self["new_commit_msg"])
175 176
    TextToFile(self["new_commit_msg"], self.Config("COMMITMSG_FILE"))
    self.GitCommit(file_name=self.Config("COMMITMSG_FILE"))
177 178 179 180 181

class CommitRepository(Step):
  MESSAGE = "Commit to the repository."

  def RunStep(self):
182
    self.GitCheckout(self.Config("BRANCHNAME"))
183
    self.WaitForLGTM()
184
    self.GitPresubmit()
185
    self.vc.CLLand()
186 187 188 189 190 191

class CleanUp(Step):
  MESSAGE = "Cleanup."

  def RunStep(self):
    self.CommonCleanup()
192 193
    print("*** SUMMARY ***")
    print("branch: %s" % self["merge_to_branch"])
194
    if self["revision_list"]:
195
      print("patches: %s" % self["revision_list"])
196 197


198 199 200
class MergeToBranch(ScriptsBase):
  def _Description(self):
    return ("Performs the necessary steps to merge revisions from "
201
            "main to release branches like 4.5. This script does not "
202 203
            "version the commit. See http://goo.gl/9ke2Vw for more "
            "information.")
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

  def _PrepareOptions(self, parser):
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--branch", help="The branch to merge to.")
    parser.add_argument("revisions", nargs="*",
                        help="The revisions to merge.")
    parser.add_argument("-f", "--force",
                        help="Delete sentinel file.",
                        default=False, action="store_true")
    parser.add_argument("-m", "--message",
                        help="A commit message for the patch.")
    parser.add_argument("-p", "--patch",
                        help="A patch file to apply as part of the merge.")

  def _ProcessOptions(self, options):
    if len(options.revisions) < 1:
      if not options.patch:
221
        print("Either a patch file or revision numbers must be specified")
222 223
        return False
      if not options.message:
224
        print("You must specify a merge comment if no patches are specified")
225
        return False
226
    options.bypass_upload_hooks = True
227

228 229 230 231 232
    if len(options.branch.split('.')) > 2:
      print ("This script does not support merging to roll branches. "
             "Please use tools/release/roll_merge.py for this use case.")
      return False

233 234 235 236
    # Make sure to use git hashes in the new workflows.
    for revision in options.revisions:
      if (IsSvnNumber(revision) or
          (revision[0:1] == "r" and IsSvnNumber(revision[1:]))):
237 238
        print("Please provide full git hashes of the patches to merge.")
        print("Got: %s" % revision)
239
        return False
240 241
    return True

242 243 244
  def _Config(self):
    return {
      "BRANCHNAME": "prepare-merge",
245
      "PERSISTFILE_BASENAME": RELEASE_WORKDIR + "v8-merge-to-branch-tempfile",
246
      "ALREADY_MERGING_SENTINEL_FILE":
247 248 249 250
          RELEASE_WORKDIR + "v8-merge-to-branch-tempfile-already-merging",
      "TEMPORARY_PATCH_FILE":
          RELEASE_WORKDIR + "v8-prepare-merge-tempfile-temporary-patch",
      "COMMITMSG_FILE": RELEASE_WORKDIR + "v8-prepare-merge-tempfile-commitmsg",
251 252
    }

253 254 255 256 257
  def _Steps(self):
    return [
      Preparation,
      CreateBranch,
      SearchArchitecturePorts,
258
      CreateCommitMessage,
259 260 261 262 263 264 265
      ApplyPatches,
      CommitLocal,
      UploadStep,
      CommitRepository,
      CleanUp,
    ]

266

267
if __name__ == "__main__":  # pragma: no cover
268
  sys.exit(MergeToBranch().Run())