common_includes.py 14.4 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 29 30 31 32
#!/usr/bin/env python
# Copyright 2013 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.

import os
import re
import subprocess
import sys
33
import textwrap
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

PERSISTFILE_BASENAME = "PERSISTFILE_BASENAME"
TEMP_BRANCH = "TEMP_BRANCH"
BRANCHNAME = "BRANCHNAME"
DOT_GIT_LOCATION = "DOT_GIT_LOCATION"
VERSION_FILE = "VERSION_FILE"
CHANGELOG_FILE = "CHANGELOG_FILE"
CHANGELOG_ENTRY_FILE = "CHANGELOG_ENTRY_FILE"
COMMITMSG_FILE = "COMMITMSG_FILE"
PATCH_FILE = "PATCH_FILE"


def TextToFile(text, file_name):
  with open(file_name, "w") as f:
    f.write(text)


def AppendToFile(text, file_name):
  with open(file_name, "a") as f:
    f.write(text)


def LinesInFile(file_name):
  with open(file_name) as f:
    for line in f:
      yield line


def FileToText(file_name):
  with open(file_name) as f:
    return f.read()


def MSub(rexp, replacement, text):
  return re.sub(rexp, replacement, text, flags=re.MULTILINE)


71 72 73 74 75
def Fill80(line):
  return textwrap.fill(line, width=80, initial_indent="        ",
                       subsequent_indent="        ")


76 77 78 79 80 81 82 83
def GetLastChangeLogEntries(change_log_file):
  result = []
  for line in LinesInFile(change_log_file):
    if re.search(r"^\d{4}-\d{2}-\d{2}:", line) and result: break
    result.append(line)
  return "".join(result)


84 85 86 87 88 89 90 91 92 93
def MakeComment(text):
  return MSub(r"^( ?)", "#", text)


def StripComments(text):
  # Use split not splitlines to keep terminal newlines.
  return "\n".join(filter(lambda x: not x.startswith("#"), text.split("\n")))


def MakeChangeLogBody(commit_messages, auto_format=False):
94
  result = ""
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  added_titles = set()
  for (title, body, author) in commit_messages:
    # TODO(machenbach): Reload the commit description from rietveld in order to
    # catch late changes.
    title = title.rstrip()
    if auto_format:
      # Only add commits that set the LOG flag correctly.
      log_exp = r"^[ \t]*LOG[ \t]*=[ \t]*(?:Y(?:ES)?)|TRUE"
      if not re.search(log_exp, body, flags=re.I | re.M):
        continue
      # Never include reverts.
      if title.startswith("Revert "):
        continue
      # Don't include duplicates.
      if title in added_titles:
        continue

    # TODO(machenbach): Let python do all formatting. Get raw git title, attach
    # issue and add/move dot to the end - all in one line. Make formatting and
    # indentation afterwards.

116
    # Add the commit's title line.
117 118
    result += "%s\n" % title
    added_titles.add(title)
119

120 121
    # Add bug references.
    result += MakeChangeLogBugReference(body)
122

123 124 125 126 127
    # Append the commit's author for reference if not in auto-format mode.
    if not auto_format:
      result += "%s\n" % author.rstrip()

    result += "\n"
128 129 130
  return result


131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
def MakeChangeLogBugReference(body):
  """Grep for "BUG=xxxx" lines in the commit message and convert them to
  "(issue xxxx)".
  """
  crbugs = []
  v8bugs = []

  def AddIssues(text):
    ref = re.match(r"^BUG[ \t]*=[ \t]*(.+)$", text.strip())
    if not ref:
      return
    for bug in ref.group(1).split(","):
      bug = bug.strip()
      match = re.match(r"^v8:(\d+)$", bug)
      if match: v8bugs.append(int(match.group(1)))
      else:
        match = re.match(r"^(?:chromium:)?(\d+)$", bug)
        if match: crbugs.append(int(match.group(1)))

  # Add issues to crbugs and v8bugs.
  map(AddIssues, body.splitlines())

  # Filter duplicates, sort, stringify.
  crbugs = map(str, sorted(set(crbugs)))
  v8bugs = map(str, sorted(set(v8bugs)))

  bug_groups = []
  def FormatIssues(prefix, bugs):
    if len(bugs) > 0:
      plural = "s" if len(bugs) > 1 else ""
      bug_groups.append("%sissue%s %s" % (prefix, plural, ", ".join(bugs)))

  FormatIssues("", v8bugs)
  FormatIssues("Chromium ", crbugs)

  if len(bug_groups) > 0:
    # Format with 8 characters indentation and max 80 character lines.
    return "%s\n" % Fill80("(%s)" % ", ".join(bug_groups))
  else:
    return ""


173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
# Some commands don't like the pipe, e.g. calling vi from within the script or
# from subscripts like git cl upload.
def Command(cmd, args="", prefix="", pipe=True):
  cmd_line = "%s %s %s" % (prefix, cmd, args)
  print "Command: %s" % cmd_line
  try:
    if pipe:
      return subprocess.check_output(cmd_line, shell=True)
    else:
      return subprocess.check_call(cmd_line, shell=True)
  except subprocess.CalledProcessError:
    return None


# Wrapper for side effects.
class SideEffectHandler(object):
  def Command(self, cmd, args="", prefix="", pipe=True):
    return Command(cmd, args, prefix, pipe)

  def ReadLine(self):
    return sys.stdin.readline().strip()

DEFAULT_SIDE_EFFECT_HANDLER = SideEffectHandler()


class Step(object):
  def __init__(self, text="", requires=None):
    self._text = text
    self._number = -1
202
    self._options = None
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    self._requires = requires
    self._side_effect_handler = DEFAULT_SIDE_EFFECT_HANDLER

  def SetNumber(self, number):
    self._number = number

  def SetConfig(self, config):
    self._config = config

  def SetState(self, state):
    self._state = state

  def SetOptions(self, options):
    self._options = options

  def SetSideEffectHandler(self, handler):
    self._side_effect_handler = handler

  def Config(self, key):
    return self._config[key]

  def Run(self):
    assert self._number >= 0
    assert self._config is not None
    assert self._state is not None
    assert self._side_effect_handler is not None
    if self._requires:
      self.RestoreIfUnset(self._requires)
      if not self._state[self._requires]:
        return
    print ">>> Step %d: %s" % (self._number, self._text)
    self.RunStep()

  def RunStep(self):
    raise NotImplementedError

239 240 241 242 243 244 245
  def ReadLine(self, default=None):
    # Don't prompt in forced mode.
    if self._options and self._options.f and default is not None:
      print "%s (forced)" % default
      return default
    else:
      return self._side_effect_handler.ReadLine()
246 247 248 249 250 251 252 253 254 255 256 257 258 259

  def Git(self, args="", prefix="", pipe=True):
    return self._side_effect_handler.Command("git", args, prefix, pipe)

  def Editor(self, args):
    return self._side_effect_handler.Command(os.environ["EDITOR"], args,
                                             pipe=False)

  def Die(self, msg=""):
    if msg != "":
      print "Error: %s" % msg
    print "Exiting"
    raise Exception(msg)

260 261 262 263 264
  def DieInForcedMode(self, msg=""):
    if self._options and self._options.f:
      msg = msg or "Not implemented in forced mode."
      self.Die(msg)

265 266
  def Confirm(self, msg):
    print "%s [Y/n] " % msg,
267
    answer = self.ReadLine(default="Y")
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    return answer == "" or answer == "Y" or answer == "y"

  def DeleteBranch(self, name):
    git_result = self.Git("branch").strip()
    for line in git_result.splitlines():
      if re.match(r".*\s+%s$" % name, line):
        msg = "Branch %s exists, do you want to delete it?" % name
        if self.Confirm(msg):
          if self.Git("branch -D %s" % name) is None:
            self.Die("Deleting branch '%s' failed." % name)
          print "Branch %s deleted." % name
        else:
          msg = "Can't continue. Please delete branch %s and try again." % name
          self.Die(msg)

  def Persist(self, var, value):
    value = value or "__EMPTY__"
    TextToFile(value, "%s-%s" % (self._config[PERSISTFILE_BASENAME], var))

  def Restore(self, var):
    value = FileToText("%s-%s" % (self._config[PERSISTFILE_BASENAME], var))
    value = value or self.Die("Variable '%s' could not be restored." % var)
    return "" if value == "__EMPTY__" else value

  def RestoreIfUnset(self, var_name):
    if self._state.get(var_name) is None:
      self._state[var_name] = self.Restore(var_name)

  def InitialEnvironmentChecks(self):
    # Cancel if this is not a git checkout.
    if not os.path.exists(self._config[DOT_GIT_LOCATION]):
      self.Die("This is not a git checkout, this script won't work for you.")

301 302
    # TODO(machenbach): Don't use EDITOR in forced mode as soon as script is
    # well tested.
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    # Cancel if EDITOR is unset or not executable.
    if (not os.environ.get("EDITOR") or
        Command("which", os.environ["EDITOR"]) is None):
      self.Die("Please set your EDITOR environment variable, you'll need it.")

  def CommonPrepare(self):
    # Check for a clean workdir.
    if self.Git("status -s -uno").strip() != "":
      self.Die("Workspace is not clean. Please commit or undo your changes.")

    # Persist current branch.
    current_branch = ""
    git_result = self.Git("status -s -b -uno").strip()
    for line in git_result.splitlines():
      match = re.match(r"^## (.+)", line)
      if match:
        current_branch = match.group(1)
        break
    self.Persist("current_branch", current_branch)

    # Fetch unfetched revisions.
    if self.Git("svn fetch") is None:
      self.Die("'git svn fetch' failed.")

327
  def PrepareBranch(self):
328
    # Get ahold of a safe temporary branch and check it out.
329 330
    self.RestoreIfUnset("current_branch")
    if self._state["current_branch"] != self._config[TEMP_BRANCH]:
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
      self.DeleteBranch(self._config[TEMP_BRANCH])
      self.Git("checkout -b %s" % self._config[TEMP_BRANCH])

    # Delete the branch that will be created later if it exists already.
    self.DeleteBranch(self._config[BRANCHNAME])

  def CommonCleanup(self):
    self.RestoreIfUnset("current_branch")
    self.Git("checkout -f %s" % self._state["current_branch"])
    if self._config[TEMP_BRANCH] != self._state["current_branch"]:
      self.Git("branch -D %s" % self._config[TEMP_BRANCH])
    if self._config[BRANCHNAME] != self._state["current_branch"]:
      self.Git("branch -D %s" % self._config[BRANCHNAME])

    # Clean up all temporary files.
    Command("rm", "-f %s*" % self._config[PERSISTFILE_BASENAME])

  def ReadAndPersistVersion(self, prefix=""):
    def ReadAndPersist(var_name, def_name):
      match = re.match(r"^#define %s\s+(\d*)" % def_name, line)
      if match:
        value = match.group(1)
        self.Persist("%s%s" % (prefix, var_name), value)
        self._state["%s%s" % (prefix, var_name)] = value
    for line in LinesInFile(self._config[VERSION_FILE]):
      for (var_name, def_name) in [("major", "MAJOR_VERSION"),
                                   ("minor", "MINOR_VERSION"),
                                   ("build", "BUILD_NUMBER"),
                                   ("patch", "PATCH_LEVEL")]:
        ReadAndPersist(var_name, def_name)

  def RestoreVersionIfUnset(self, prefix=""):
    for v in ["major", "minor", "build", "patch"]:
      self.RestoreIfUnset("%s%s" % (prefix, v))

  def WaitForLGTM(self):
    print ("Please wait for an LGTM, then type \"LGTM<Return>\" to commit "
           "your change. (If you need to iterate on the patch or double check "
           "that it's sane, do so in another shell, but remember to not "
           "change the headline of the uploaded CL.")
    answer = ""
    while answer != "LGTM":
      print "> ",
374 375
      # TODO(machenbach): Add default="LGTM" to avoid prompt when script is
      # well tested and when prepare push cl has TBR flag.
376 377 378 379 380 381 382 383
      answer = self.ReadLine()
      if answer != "LGTM":
        print "That was not 'LGTM'."

  def WaitForResolvingConflicts(self, patch_file):
    print("Applying the patch \"%s\" failed. Either type \"ABORT<Return>\", "
          "or resolve the conflicts, stage *all* touched files with "
          "'git add', and type \"RESOLVED<Return>\"")
384
    self.DieInForcedMode()
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    answer = ""
    while answer != "RESOLVED":
      if answer == "ABORT":
        self.Die("Applying the patch failed.")
      if answer != "":
        print "That was not 'RESOLVED' or 'ABORT'."
      print "> ",
      answer = self.ReadLine()

  # Takes a file containing the patch to apply as first argument.
  def ApplyPatch(self, patch_file, reverse_patch=""):
    args = "apply --index --reject %s \"%s\"" % (reverse_patch, patch_file)
    if self.Git(args) is None:
      self.WaitForResolvingConflicts(patch_file)


class UploadStep(Step):
  def __init__(self):
    Step.__init__(self, "Upload for code review.")

  def RunStep(self):
406
    if self._options.r:
407 408 409 410 411 412
      print "Using account %s for review." % self._options.r
      reviewer = self._options.r
    else:
      print "Please enter the email address of a V8 reviewer for your patch: ",
      self.DieInForcedMode("A reviewer must be specified in forced mode.")
      reviewer = self.ReadLine()
413 414 415 416 417
    force_flag = " -f" if self._options.f else ""
    args = "cl upload -r \"%s\" --send-mail%s" % (reviewer, force_flag)
    # TODO(machenbach): Check output in forced mode. Verify that all required
    # base files were uploaded, if not retry.
    if self.Git(args, pipe=False) is None:
418
      self.Die("'git cl upload' failed, please try again.")
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441


def RunScript(step_classes,
              config,
              options,
              side_effect_handler=DEFAULT_SIDE_EFFECT_HANDLER):
  state = {}
  steps = []
  number = 0

  for step_class in step_classes:
    # TODO(machenbach): Factory methods.
    step = step_class()
    step.SetNumber(number)
    step.SetConfig(config)
    step.SetOptions(options)
    step.SetState(state)
    step.SetSideEffectHandler(side_effect_handler)
    steps.append(step)
    number += 1

  for step in steps[options.s:]:
    step.Run()