test_scripts.py 73.7 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
#!/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
30
import shutil
31
import tempfile
32
import traceback
33 34
import unittest

35
import auto_push
36
from auto_push import LastReleaseBailout
37
import auto_roll
38 39
import common_includes
from common_includes import *
40 41
import create_release
from create_release import CreateRelease
42
import merge_to_branch
43
from merge_to_branch import MergeToBranch
44 45
import push_to_candidates
from push_to_candidates import *
46 47
import releases
from releases import Releases
48
from auto_tag import AutoTag
49 50
import roll_merge
from roll_merge import RollMerge
51 52

TEST_CONFIG = {
53
  "DEFAULT_CWD": None,
54
  "BRANCHNAME": "test-prepare-push",
machenbach's avatar
machenbach committed
55 56 57 58 59 60 61
  "CANDIDATESBRANCH": "test-candidates-push",
  "PERSISTFILE_BASENAME": "/tmp/test-v8-push-to-candidates-tempfile",
  "CHANGELOG_ENTRY_FILE":
      "/tmp/test-v8-push-to-candidates-tempfile-changelog-entry",
  "PATCH_FILE": "/tmp/test-v8-push-to-candidates-tempfile-patch",
  "COMMITMSG_FILE": "/tmp/test-v8-push-to-candidates-tempfile-commitmsg",
  "CHROMIUM": "/tmp/test-v8-push-to-candidates-tempfile-chromium",
62 63
  "SETTINGS_LOCATION": None,
  "ALREADY_MERGING_SENTINEL_FILE":
64
      "/tmp/test-merge-to-branch-tempfile-already-merging",
65
  "TEMPORARY_PATCH_FILE": "/tmp/test-merge-to-branch-tempfile-temporary-patch",
66 67
}

68

69
AUTO_PUSH_ARGS = [
70 71 72 73
  "-a", "author@chromium.org",
  "-r", "reviewer@chromium.org",
]

74

75
class ToplevelTest(unittest.TestCase):
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  def testSaniniziteVersionTags(self):
    self.assertEquals("4.8.230", SanitizeVersionTag("4.8.230"))
    self.assertEquals("4.8.230", SanitizeVersionTag("tags/4.8.230"))
    self.assertEquals(None, SanitizeVersionTag("candidate"))

  def testNormalizeVersionTags(self):
    input = ["4.8.230",
              "tags/4.8.230",
              "tags/4.8.224.1",
              "4.8.224.1",
              "4.8.223.1",
              "tags/4.8.223",
              "tags/4.8.231",
              "candidates"]
    expected = ["4.8.230",
                "4.8.230",
                "4.8.224.1",
                "4.8.224.1",
                "4.8.223.1",
                "4.8.223",
                "4.8.231",
                ]
    self.assertEquals(expected, NormalizeVersionTags(input))

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  def testSortBranches(self):
    S = releases.SortBranches
    self.assertEquals(["3.1", "2.25"], S(["2.25", "3.1"])[0:2])
    self.assertEquals(["3.0", "2.25"], S(["2.25", "3.0", "2.24"])[0:2])
    self.assertEquals(["3.11", "3.2"], S(["3.11", "3.2", "2.24"])[0:2])

  def testFilterDuplicatesAndReverse(self):
    F = releases.FilterDuplicatesAndReverse
    self.assertEquals([], F([]))
    self.assertEquals([["100", "10"]], F([["100", "10"]]))
    self.assertEquals([["99", "9"], ["100", "10"]],
                      F([["100", "10"], ["99", "9"]]))
    self.assertEquals([["98", "9"], ["100", "10"]],
                      F([["100", "10"], ["99", "9"], ["98", "9"]]))
    self.assertEquals([["98", "9"], ["99", "10"]],
                      F([["100", "10"], ["99", "10"], ["98", "9"]]))

  def testBuildRevisionRanges(self):
    B = releases.BuildRevisionRanges
    self.assertEquals({}, B([]))
    self.assertEquals({"10": "100"}, B([["100", "10"]]))
    self.assertEquals({"10": "100", "9": "99:99"},
                      B([["100", "10"], ["99", "9"]]))
    self.assertEquals({"10": "100", "9": "97:99"},
                      B([["100", "10"], ["98", "9"], ["97", "9"]]))
    self.assertEquals({"10": "100", "9": "99:99", "3": "91:98"},
                      B([["100", "10"], ["99", "9"], ["91", "3"]]))
    self.assertEquals({"13": "101", "12": "100:100", "9": "94:97",
128
                       "3": "91:93, 98:99"},
129 130 131
                      B([["101", "13"], ["100", "12"], ["98", "3"],
                         ["94", "9"], ["91", "3"]]))

132 133 134 135 136 137 138 139 140 141 142 143
  def testMakeComment(self):
    self.assertEquals("#   Line 1\n#   Line 2\n#",
                      MakeComment("    Line 1\n    Line 2\n"))
    self.assertEquals("#Line 1\n#Line 2",
                      MakeComment("Line 1\n Line 2"))

  def testStripComments(self):
    self.assertEquals("    Line 1\n    Line 3\n",
        StripComments("    Line 1\n#   Line 2\n    Line 3\n#\n"))
    self.assertEquals("\nLine 2 ### Test\n #",
        StripComments("###\n# \n\n#  Line 1\nLine 2 ### Test\n #"))

144
  def testMakeChangeLogBodySimple(self):
145
    commits = [
146
          ["Title text 1",
147
           "Title text 1\n\nBUG=\n",
148
           "author1@chromium.org"],
149
          ["Title text 2.",
150
           "Title text 2\n\nBUG=1234\n",
151
           "author2@chromium.org"],
152
        ]
153
    self.assertEquals("        Title text 1.\n"
154
                      "        (author1@chromium.org)\n\n"
155
                      "        Title text 2 (Chromium issue 1234).\n"
156
                      "        (author2@chromium.org)\n\n",
157 158 159
                      MakeChangeLogBody(commits))

  def testMakeChangeLogBodyEmpty(self):
160 161 162 163
    self.assertEquals("", MakeChangeLogBody([]))

  def testMakeChangeLogBodyAutoFormat(self):
    commits = [
164
          ["Title text 1!",
165
           "Title text 1\nLOG=y\nBUG=\n",
166 167
           "author1@chromium.org"],
          ["Title text 2",
168
           "Title text 2\n\nBUG=1234\n",
169 170
           "author2@chromium.org"],
          ["Title text 3",
171
           "Title text 3\n\nBUG=1234\nLOG = Yes\n",
172 173
           "author3@chromium.org"],
          ["Title text 3",
174
           "Title text 4\n\nBUG=1234\nLOG=\n",
175
           "author4@chromium.org"],
176
        ]
177 178
    self.assertEquals("        Title text 1.\n\n"
                      "        Title text 3 (Chromium issue 1234).\n\n",
179
                      MakeChangeLogBody(commits, True))
180

181 182 183 184 185 186 187 188 189 190 191
  def testRegressWrongLogEntryOnTrue(self):
    body = """
Check elimination: Learn from if(CompareMap(x)) on true branch.

BUG=
R=verwaest@chromium.org

Committed: https://code.google.com/p/v8/source/detail?r=18210
"""
    self.assertEquals("", MakeChangeLogBody([["title", body, "author"]], True))

192 193 194 195 196 197 198
  def testMakeChangeLogBugReferenceEmpty(self):
    self.assertEquals("", MakeChangeLogBugReference(""))
    self.assertEquals("", MakeChangeLogBugReference("LOG="))
    self.assertEquals("", MakeChangeLogBugReference(" BUG ="))
    self.assertEquals("", MakeChangeLogBugReference("BUG=none\t"))

  def testMakeChangeLogBugReferenceSimple(self):
199
    self.assertEquals("(issue 987654)",
200
                      MakeChangeLogBugReference("BUG = v8:987654"))
201
    self.assertEquals("(Chromium issue 987654)",
202 203 204
                      MakeChangeLogBugReference("BUG=987654 "))

  def testMakeChangeLogBugReferenceFromBody(self):
205
    self.assertEquals("(Chromium issue 1234567)",
206 207 208 209 210 211 212
                      MakeChangeLogBugReference("Title\n\nTBR=\nBUG=\n"
                                                " BUG=\tchromium:1234567\t\n"
                                                "R=somebody\n"))

  def testMakeChangeLogBugReferenceMultiple(self):
    # All issues should be sorted and grouped. Multiple references to the same
    # issue should be filtered.
213
    self.assertEquals("(issues 123, 234, Chromium issue 345)",
214 215 216 217 218
                      MakeChangeLogBugReference("Title\n\n"
                                                "BUG=v8:234\n"
                                                "  BUG\t= 345, \tv8:234,\n"
                                                "BUG=v8:123\n"
                                                "R=somebody\n"))
219
    self.assertEquals("(Chromium issues 123, 234)",
220 221 222
                      MakeChangeLogBugReference("Title\n\n"
                                                "BUG=234,,chromium:123 \n"
                                                "R=somebody\n"))
223
    self.assertEquals("(Chromium issues 123, 234)",
224 225 226
                      MakeChangeLogBugReference("Title\n\n"
                                                "BUG=chromium:234, , 123\n"
                                                "R=somebody\n"))
227
    self.assertEquals("(issues 345, 456)",
228 229 230
                      MakeChangeLogBugReference("Title\n\n"
                                                "\t\tBUG=v8:345,v8:456\n"
                                                "R=somebody\n"))
231
    self.assertEquals("(issue 123, Chromium issues 345, 456)",
232 233 234 235 236 237
                      MakeChangeLogBugReference("Title\n\n"
                                                "BUG=chromium:456\n"
                                                "BUG = none\n"
                                                "R=somebody\n"
                                                "BUG=456,v8:123, 345"))

238 239
  # TODO(machenbach): These test don't make much sense when the formatting is
  # done later.
240 241
  def testMakeChangeLogBugReferenceLong(self):
    # -----------------00--------10--------20--------30--------
242 243 244
    self.assertEquals("(issues 234, 1234567890, 1234567"
                      "8901234567890, Chromium issues 12345678,"
                      " 123456789)",
245 246 247 248 249 250
                      MakeChangeLogBugReference("BUG=v8:234\n"
                                                "BUG=v8:1234567890\n"
                                                "BUG=v8:12345678901234567890\n"
                                                "BUG=123456789\n"
                                                "BUG=12345678\n"))
    # -----------------00--------10--------20--------30--------
251 252 253
    self.assertEquals("(issues 234, 1234567890, 1234567"
                      "8901234567890, Chromium issues"
                      " 123456789, 1234567890)",
254 255 256 257 258 259
                      MakeChangeLogBugReference("BUG=v8:234\n"
                                                "BUG=v8:12345678901234567890\n"
                                                "BUG=v8:1234567890\n"
                                                "BUG=123456789\n"
                                                "BUG=1234567890\n"))
    # -----------------00--------10--------20--------30--------
260 261 262
    self.assertEquals("(Chromium issues 234, 1234567890"
                      ", 12345678901234567, "
                      "1234567890123456789)",
263 264 265 266 267
                      MakeChangeLogBugReference("BUG=234\n"
                                                "BUG=12345678901234567\n"
                                                "BUG=1234567890123456789\n"
                                                "BUG=1234567890\n"))

268

269
def Cmd(*args, **kwargs):
270
  """Convenience function returning a shell command test expectation."""
271
  return {
272
    "name": "command",
273
    "args": args,
274 275
    "ret": args[-1],
    "cb": kwargs.get("cb"),
276
    "cwd": kwargs.get("cwd", TEST_CONFIG["DEFAULT_CWD"]),
277 278 279 280 281
  }


def RL(text, cb=None):
  """Convenience function returning a readline test expectation."""
282 283 284 285 286 287 288
  return {
    "name": "readline",
    "args": [],
    "ret": text,
    "cb": cb,
    "cwd": None,
  }
289 290 291 292 293 294 295 296 297


def URL(*args, **kwargs):
  """Convenience function returning a readurl test expectation."""
  return {
    "name": "readurl",
    "args": args[:-1],
    "ret": args[-1],
    "cb": kwargs.get("cb"),
298
    "cwd": None,
299 300 301
  }


302
class SimpleMock(object):
303
  def __init__(self):
304 305 306 307 308 309
    self._recipe = []
    self._index = -1

  def Expect(self, recipe):
    self._recipe = recipe

310
  def Call(self, name, *args, **kwargs):  # pragma: no cover
311 312 313 314
    self._index += 1
    try:
      expected_call = self._recipe[self._index]
    except IndexError:
315
      raise NoRetryException("Calling %s %s" % (name, " ".join(args)))
316 317

    if not isinstance(expected_call, dict):
318 319
      raise NoRetryException("Found wrong expectation type for %s %s" %
                             (name, " ".join(args)))
320

321 322 323
    if expected_call["name"] != name:
      raise NoRetryException("Expected action: %s %s - Actual: %s" %
          (expected_call["name"], expected_call["args"], name))
324

325 326 327 328 329 330 331 332
    # Check if the given working directory matches the expected one.
    if expected_call["cwd"] != kwargs.get("cwd"):
      raise NoRetryException("Expected cwd: %s in %s %s - Actual: %s" %
          (expected_call["cwd"],
           expected_call["name"],
           expected_call["args"],
           kwargs.get("cwd")))

333 334
    # The number of arguments in the expectation must match the actual
    # arguments.
335
    if len(args) > len(expected_call['args']):
336
      raise NoRetryException("When calling %s with arguments, the "
337
          "expectations must consist of at least as many arguments." %
338
          name)
339 340

    # Compare expected and actual arguments.
341
    for (expected_arg, actual_arg) in zip(expected_call['args'], args):
342
      if expected_arg != actual_arg:
343 344
        raise NoRetryException("Expected: %s - Actual: %s" %
                               (expected_arg, actual_arg))
345

346 347 348
    # The expected call contains an optional callback for checking the context
    # at the time of the call.
    if expected_call['cb']:
349
      try:
350
        expected_call['cb']()
351 352 353
      except:
        tb = traceback.format_exc()
        raise NoRetryException("Caught exception from callback: %s" % tb)
354 355

    # If the return value is an exception, raise it instead of returning.
356 357 358
    if isinstance(expected_call['ret'], Exception):
      raise expected_call['ret']
    return expected_call['ret']
359

360
  def AssertFinished(self):  # pragma: no cover
361
    if self._index < len(self._recipe) -1:
362 363
      raise NoRetryException("Called mock too seldom: %d vs. %d" %
                             (self._index, len(self._recipe)))
364 365


366 367 368 369 370 371 372
class ScriptTest(unittest.TestCase):
  def MakeEmptyTempFile(self):
    handle, name = tempfile.mkstemp()
    os.close(handle)
    self._tmp_files.append(name)
    return name

373 374 375 376 377 378
  def MakeEmptyTempDirectory(self):
    name = tempfile.mkdtemp()
    self._tmp_files.append(name)
    return name


379
  def WriteFakeVersionFile(self, major=3, minor=22, build=4, patch=0):
380 381 382 383
    version_file = os.path.join(TEST_CONFIG["DEFAULT_CWD"], VERSION_FILE)
    if not os.path.exists(os.path.dirname(version_file)):
      os.makedirs(os.path.dirname(version_file))
    with open(version_file, "w") as f:
384 385
      f.write("  // Some line...\n")
      f.write("\n")
machenbach's avatar
machenbach committed
386 387 388 389
      f.write("#define V8_MAJOR_VERSION    %s\n" % major)
      f.write("#define V8_MINOR_VERSION    %s\n" % minor)
      f.write("#define V8_BUILD_NUMBER     %s\n" % build)
      f.write("#define V8_PATCH_LEVEL      %s\n" % patch)
390
      f.write("  // Some line...\n")
machenbach's avatar
machenbach committed
391
      f.write("#define V8_IS_CANDIDATE_VERSION 0\n")
392

393 394 395 396 397 398 399 400 401 402 403 404 405 406
  def WriteFakeWatchlistsFile(self):
    watchlists_file = os.path.join(TEST_CONFIG["DEFAULT_CWD"], WATCHLISTS_FILE)
    if not os.path.exists(os.path.dirname(watchlists_file)):
      os.makedirs(os.path.dirname(watchlists_file))
    with open(watchlists_file, "w") as f:

      content = """
    'merges': [
      # Only enabled on branches created with tools/release/create_release.py
      # 'v8-merges@googlegroups.com',
    ],
"""
      f.write(content)

407 408 409 410 411 412 413
  def MakeStep(self):
    """Convenience wrapper."""
    options = ScriptsBase(TEST_CONFIG, self, self._state).MakeOptions([])
    return MakeStep(step_class=Step, state=self._state,
                    config=TEST_CONFIG, side_effect_handler=self,
                    options=options)

machenbach's avatar
machenbach committed
414
  def RunStep(self, script=PushToCandidates, step_class=Step, args=None):
415
    """Convenience wrapper."""
416
    args = args if args is not None else ["-m"]
417
    return script(TEST_CONFIG, self, self._state).RunSteps([step_class], args)
418

419 420 421
  def Call(self, fun, *args, **kwargs):
    print "Calling %s with %s and %s" % (str(fun), str(args), str(kwargs))

422
  def Command(self, cmd, args="", prefix="", pipe=True, cwd=None):
423
    print "%s %s" % (cmd, args)
424 425
    print "in %s" % cwd
    return self._mock.Call("command", cmd + " " + args, cwd=cwd)
426 427

  def ReadLine(self):
428
    return self._mock.Call("readline")
429

430 431
  def ReadURL(self, url, params):
    if params is not None:
432
      return self._mock.Call("readurl", url, params)
433
    else:
434
      return self._mock.Call("readurl", url)
435

436 437 438
  def Sleep(self, seconds):
    pass

439 440 441
  def GetDate(self):
    return "1999-07-31"

442
  def GetUTCStamp(self):
443
    return "1000000"
444

445
  def Expect(self, *args):
446
    """Convenience wrapper."""
447
    self._mock.Expect(*args)
448 449

  def setUp(self):
450
    self._mock = SimpleMock()
451
    self._tmp_files = []
452
    self._state = {}
453
    TEST_CONFIG["DEFAULT_CWD"] = self.MakeEmptyTempDirectory()
454 455

  def tearDown(self):
456 457
    if os.path.exists(TEST_CONFIG["PERSISTFILE_BASENAME"]):
      shutil.rmtree(TEST_CONFIG["PERSISTFILE_BASENAME"])
458 459 460

    # Clean up temps. Doesn't work automatically.
    for name in self._tmp_files:
461
      if os.path.isfile(name):
462
        os.remove(name)
463 464
      if os.path.isdir(name):
        shutil.rmtree(name)
465

466
    self._mock.AssertFinished()
467 468

  def testGitMock(self):
469 470
    self.Expect([Cmd("git --version", "git version 1.2.3"),
                 Cmd("git dummy", "")])
471 472 473 474
    self.assertEquals("git version 1.2.3", self.MakeStep().Git("--version"))
    self.assertEquals("", self.MakeStep().Git("dummy"))

  def testCommonPrepareDefault(self):
475
    self.Expect([
476
      Cmd("git status -s -uno", ""),
477
      Cmd("git checkout -f origin/master", ""),
478
      Cmd("git fetch", ""),
479
      Cmd("git branch", "  branch1\n* %s" % TEST_CONFIG["BRANCHNAME"]),
480
      RL("Y"),
481
      Cmd("git branch -D %s" % TEST_CONFIG["BRANCHNAME"], ""),
482
    ])
483
    self.MakeStep().CommonPrepare()
484
    self.MakeStep().PrepareBranch()
485 486

  def testCommonPrepareNoConfirm(self):
487
    self.Expect([
488
      Cmd("git status -s -uno", ""),
489
      Cmd("git checkout -f origin/master", ""),
490
      Cmd("git fetch", ""),
491
      Cmd("git branch", "  branch1\n* %s" % TEST_CONFIG["BRANCHNAME"]),
492
      RL("n"),
493
    ])
494 495
    self.MakeStep().CommonPrepare()
    self.assertRaises(Exception, self.MakeStep().PrepareBranch)
496 497

  def testCommonPrepareDeleteBranchFailure(self):
498
    self.Expect([
499
      Cmd("git status -s -uno", ""),
500
      Cmd("git checkout -f origin/master", ""),
501
      Cmd("git fetch", ""),
502
      Cmd("git branch", "  branch1\n* %s" % TEST_CONFIG["BRANCHNAME"]),
503
      RL("Y"),
504
      Cmd("git branch -D %s" % TEST_CONFIG["BRANCHNAME"], None),
505
    ])
506 507
    self.MakeStep().CommonPrepare()
    self.assertRaises(Exception, self.MakeStep().PrepareBranch)
508 509

  def testInitialEnvironmentChecks(self):
510
    TextToFile("", os.path.join(TEST_CONFIG["DEFAULT_CWD"], ".git"))
511
    os.environ["EDITOR"] = "vi"
512 513 514
    self.Expect([
      Cmd("which vi", "/usr/bin/vi"),
    ])
515
    self.MakeStep().InitialEnvironmentChecks(TEST_CONFIG["DEFAULT_CWD"])
516

517 518 519 520 521 522 523 524 525 526 527
  def testTagTimeout(self):
    self.Expect([
      Cmd("git fetch", ""),
      Cmd("git log -1 --format=%H --grep=\"Title\" origin/candidates", ""),
      Cmd("git fetch", ""),
      Cmd("git log -1 --format=%H --grep=\"Title\" origin/candidates", ""),
      Cmd("git fetch", ""),
      Cmd("git log -1 --format=%H --grep=\"Title\" origin/candidates", ""),
      Cmd("git fetch", ""),
      Cmd("git log -1 --format=%H --grep=\"Title\" origin/candidates", ""),
    ])
528
    args = ["--branch", "candidates", "ab12345"]
529 530 531
    self._state["version"] = "tag_name"
    self._state["commit_title"] = "Title"
    self.assertRaises(Exception,
532
        lambda: self.RunStep(RollMerge, TagRevision, args))
533

534
  def testReadAndPersistVersion(self):
535
    self.WriteFakeVersionFile(build=5)
536 537
    step = self.MakeStep()
    step.ReadAndPersistVersion()
538 539 540 541
    self.assertEquals("3", step["major"])
    self.assertEquals("22", step["minor"])
    self.assertEquals("5", step["build"])
    self.assertEquals("0", step["patch"])
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558

  def testRegex(self):
    self.assertEqual("(issue 321)",
                     re.sub(r"BUG=v8:(.*)$", r"(issue \1)", "BUG=v8:321"))
    self.assertEqual("(Chromium issue 321)",
                     re.sub(r"BUG=(.*)$", r"(Chromium issue \1)", "BUG=321"))

    cl = "  too little\n\ttab\ttab\n         too much\n        trailing  "
    cl = MSub(r"\t", r"        ", cl)
    cl = MSub(r"^ {1,7}([^ ])", r"        \1", cl)
    cl = MSub(r"^ {9,80}([^ ])", r"        \1", cl)
    cl = MSub(r" +$", r"", cl)
    self.assertEqual("        too little\n"
                     "        tab        tab\n"
                     "        too much\n"
                     "        trailing", cl)

machenbach's avatar
machenbach committed
559 560
    self.assertEqual("//\n#define V8_BUILD_NUMBER  3\n",
                     MSub(r"(?<=#define V8_BUILD_NUMBER)(?P<space>\s+)\d*$",
561
                          r"\g<space>3",
machenbach's avatar
machenbach committed
562
                          "//\n#define V8_BUILD_NUMBER  321\n"))
563

564 565
  def testPreparePushRevision(self):
    # Tests the default push hash used when the --revision option is not set.
566
    self.Expect([
567
      Cmd("git log -1 --format=%H HEAD", "push_hash")
568 569
    ])

machenbach's avatar
machenbach committed
570
    self.RunStep(PushToCandidates, PreparePushRevision)
571 572
    self.assertEquals("push_hash", self._state["push_hash"])

573
  def testPrepareChangeLog(self):
574
    self.WriteFakeVersionFile()
575
    TEST_CONFIG["CHANGELOG_ENTRY_FILE"] = self.MakeEmptyTempFile()
576

577
    self.Expect([
578 579 580 581 582 583 584 585 586 587 588 589
      Cmd("git log --format=%H 1234..push_hash", "rev1\nrev2\nrev3\nrev4"),
      Cmd("git log -1 --format=%s rev1", "Title text 1"),
      Cmd("git log -1 --format=%B rev1", "Title\n\nBUG=\nLOG=y\n"),
      Cmd("git log -1 --format=%an rev1", "author1@chromium.org"),
      Cmd("git log -1 --format=%s rev2", "Title text 2."),
      Cmd("git log -1 --format=%B rev2", "Title\n\nBUG=123\nLOG= \n"),
      Cmd("git log -1 --format=%an rev2", "author2@chromium.org"),
      Cmd("git log -1 --format=%s rev3", "Title text 3"),
      Cmd("git log -1 --format=%B rev3", "Title\n\nBUG=321\nLOG=true\n"),
      Cmd("git log -1 --format=%an rev3", "author3@chromium.org"),
      Cmd("git log -1 --format=%s rev4", "Title text 4"),
      Cmd("git log -1 --format=%B rev4",
590
       ("Title\n\nBUG=456\nLOG=Y\n\n"
591 592 593
        "Review URL: https://codereview.chromium.org/9876543210\n")),
      URL("https://codereview.chromium.org/9876543210/description",
          "Title\n\nBUG=456\nLOG=N\n\n"),
594
      Cmd("git log -1 --format=%an rev4", "author4@chromium.org"),
595
    ])
596

machenbach's avatar
machenbach committed
597
    self._state["last_push_master"] = "1234"
598
    self._state["push_hash"] = "push_hash"
599
    self._state["version"] = "3.22.5"
machenbach's avatar
machenbach committed
600
    self.RunStep(PushToCandidates, PrepareChangeLog)
601

602
    actual_cl = FileToText(TEST_CONFIG["CHANGELOG_ENTRY_FILE"])
603

604
    expected_cl = """1999-07-31: Version 3.22.5
605

606
        Title text 1.
607

608
        Title text 3 (Chromium issue 321).
609

610
        Performance and stability improvements on all platforms.
611
#
612 613 614
# The change log above is auto-generated. Please review if all relevant
# commit messages from the list below are included.
# All lines starting with # will be stripped.
615
#
616
#       Title text 1.
617
#       (author1@chromium.org)
618
#
619 620
#       Title text 2 (Chromium issue 123).
#       (author2@chromium.org)
621
#
622 623
#       Title text 3 (Chromium issue 321).
#       (author3@chromium.org)
624
#
625 626
#       Title text 4 (Chromium issue 456).
#       (author4@chromium.org)
627
#
628 629
#"""

630
    self.assertEquals(expected_cl, actual_cl)
631 632

  def testEditChangeLog(self):
633 634
    TEST_CONFIG["CHANGELOG_ENTRY_FILE"] = self.MakeEmptyTempFile()
    TextToFile("  New  \n\tLines  \n", TEST_CONFIG["CHANGELOG_ENTRY_FILE"])
635
    os.environ["EDITOR"] = "vi"
636
    self.Expect([
637
      RL(""),  # Open editor.
638
      Cmd("vi %s" % TEST_CONFIG["CHANGELOG_ENTRY_FILE"], ""),
639
    ])
640

machenbach's avatar
machenbach committed
641
    self.RunStep(PushToCandidates, EditChangeLog)
642

643
    self.assertEquals("New\n        Lines",
644
                      FileToText(TEST_CONFIG["CHANGELOG_ENTRY_FILE"]))
645

646 647 648 649 650 651 652
  TAGS = """
4425.0
0.0.0.0
3.9.6
3.22.4
test_tag
"""
653

654 655
  # Version as tag: 3.22.4.0. Version on master: 3.22.6.
  # Make sure that the latest version is 3.22.6.0.
656
  def testIncrementVersion(self):
657
    self.Expect([
658
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
659
      Cmd("git tag", self.TAGS),
machenbach's avatar
machenbach committed
660
      Cmd("git checkout -f origin/master -- include/v8-version.h",
661
          "", cb=lambda: self.WriteFakeVersionFile(3, 22, 6)),
662
    ])
663

664
    self.RunStep(PushToCandidates, IncrementVersion)
665

666 667 668 669
    self.assertEquals("3", self._state["new_major"])
    self.assertEquals("22", self._state["new_minor"])
    self.assertEquals("7", self._state["new_build"])
    self.assertEquals("0", self._state["new_patch"])
670

671
  def _TestSquashCommits(self, change_log, expected_msg):
672 673
    TEST_CONFIG["CHANGELOG_ENTRY_FILE"] = self.MakeEmptyTempFile()
    with open(TEST_CONFIG["CHANGELOG_ENTRY_FILE"], "w") as f:
674
      f.write(change_log)
675

676
    self.Expect([
677
      Cmd("git diff origin/candidates hash1", "patch content"),
678
    ])
679

680
    self._state["push_hash"] = "hash1"
681
    self._state["date"] = "1999-11-11"
682

machenbach's avatar
machenbach committed
683
    self.RunStep(PushToCandidates, SquashCommits)
684
    self.assertEquals(FileToText(TEST_CONFIG["COMMITMSG_FILE"]), expected_msg)
685

686
    patch = FileToText(TEST_CONFIG["PATCH_FILE"])
687 688
    self.assertTrue(re.search(r"patch content", patch))

689 690 691 692 693 694 695
  def testSquashCommitsUnformatted(self):
    change_log = """1999-11-11: Version 3.22.5

        Log text 1.
        Chromium issue 12345

        Performance and stability improvements on all platforms.\n"""
696
    commit_msg = """Version 3.22.5 (based on hash1)
697 698 699 700 701 702 703 704 705 706 707 708 709

Log text 1. Chromium issue 12345

Performance and stability improvements on all platforms."""
    self._TestSquashCommits(change_log, commit_msg)

  def testSquashCommitsFormatted(self):
    change_log = """1999-11-11: Version 3.22.5

        Long commit message that fills more than 80 characters (Chromium issue
        12345).

        Performance and stability improvements on all platforms.\n"""
710
    commit_msg = """Version 3.22.5 (based on hash1)
711 712 713 714 715 716 717 718 719 720 721

Long commit message that fills more than 80 characters (Chromium issue 12345).

Performance and stability improvements on all platforms."""
    self._TestSquashCommits(change_log, commit_msg)

  def testSquashCommitsQuotationMarks(self):
    change_log = """Line with "quotation marks".\n"""
    commit_msg = """Line with "quotation marks"."""
    self._TestSquashCommits(change_log, commit_msg)

722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
  def testBootstrapper(self):
    work_dir = self.MakeEmptyTempDirectory()
    class FakeScript(ScriptsBase):
      def _Steps(self):
        return []

    # Use the test configuration without the fake testing default work dir.
    fake_config = dict(TEST_CONFIG)
    del(fake_config["DEFAULT_CWD"])

    self.Expect([
      Cmd("fetch v8", "", cwd=work_dir),
    ])
    FakeScript(fake_config, self).Run(["--work-dir", work_dir])

machenbach's avatar
machenbach committed
737
  def _PushToCandidates(self, force=False, manual=False):
738
    TextToFile("", os.path.join(TEST_CONFIG["DEFAULT_CWD"], ".git"))
739

machenbach's avatar
machenbach committed
740 741
    # The version file on master has build level 5, while the version
    # file from candidates has build level 4.
742 743
    self.WriteFakeVersionFile(build=5)

744
    TEST_CONFIG["CHANGELOG_ENTRY_FILE"] = self.MakeEmptyTempFile()
machenbach's avatar
machenbach committed
745 746
    master_change_log = "2014-03-17: Sentinel\n"
    TextToFile(master_change_log,
747
               os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))
748 749
    os.environ["EDITOR"] = "vi"

750 751 752 753 754 755 756 757 758 759 760 761
    commit_msg_squashed = """Version 3.22.5 (squashed - based on push_hash)

Log text 1 (issue 321).

Performance and stability improvements on all platforms."""

    commit_msg = """Version 3.22.5 (based on push_hash)

Log text 1 (issue 321).

Performance and stability improvements on all platforms."""

762
    def ResetChangeLog():
machenbach's avatar
machenbach committed
763 764 765 766
      """On 'git co -b new_branch origin/candidates',
      and 'git checkout -- ChangeLog',
      the ChangLog will be reset to its content on candidates."""
      candidates_change_log = """1999-04-05: Version 3.22.4
767 768

        Performance and stability improvements on all platforms.\n"""
machenbach's avatar
machenbach committed
769
      TextToFile(candidates_change_log,
770
                 os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))
771

machenbach's avatar
machenbach committed
772
    def ResetToCandidates():
773 774 775
      ResetChangeLog()
      self.WriteFakeVersionFile()

776
    def CheckVersionCommit():
777
      commit = FileToText(TEST_CONFIG["COMMITMSG_FILE"])
778
      self.assertEquals(commit_msg, commit)
779 780
      version = FileToText(
          os.path.join(TEST_CONFIG["DEFAULT_CWD"], VERSION_FILE))
machenbach's avatar
machenbach committed
781 782 783 784 785 786
      self.assertTrue(re.search(r"#define V8_MINOR_VERSION\s+22", version))
      self.assertTrue(re.search(r"#define V8_BUILD_NUMBER\s+5", version))
      self.assertFalse(re.search(r"#define V8_BUILD_NUMBER\s+6", version))
      self.assertTrue(re.search(r"#define V8_PATCH_LEVEL\s+0", version))
      self.assertTrue(
          re.search(r"#define V8_IS_CANDIDATE_VERSION\s+0", version))
787

machenbach's avatar
machenbach committed
788 789
      # Check that the change log on the candidates branch got correctly
      # modified.
790 791
      change_log = FileToText(
          os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))
792 793 794 795 796 797 798 799 800 801 802 803 804
      self.assertEquals(
"""1999-07-31: Version 3.22.5

        Log text 1 (issue 321).

        Performance and stability improvements on all platforms.


1999-04-05: Version 3.22.4

        Performance and stability improvements on all platforms.\n""",
          change_log)

805
    force_flag = " -f" if not manual else ""
806 807 808 809
    expectations = []
    if not force:
      expectations.append(Cmd("which vi", "/usr/bin/vi"))
    expectations += [
810
      Cmd("git status -s -uno", ""),
811
      Cmd("git checkout -f origin/master", ""),
812
      Cmd("git fetch", ""),
813 814
      Cmd("git branch", "  branch1\n* branch2\n"),
      Cmd("git branch", "  branch1\n* branch2\n"),
815
      Cmd(("git new-branch %s --upstream origin/master" %
816
           TEST_CONFIG["BRANCHNAME"]), ""),
817
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
818
      Cmd("git tag", self.TAGS),
machenbach's avatar
machenbach committed
819
      Cmd("git checkout -f origin/master -- include/v8-version.h",
820
          "", cb=self.WriteFakeVersionFile),
821 822 823
      Cmd("git log -1 --format=%H 3.22.4", "release_hash\n"),
      Cmd("git log -1 --format=%s release_hash",
          "Version 3.22.4 (based on abc3)\n"),
824
      Cmd("git log --format=%H abc3..push_hash", "rev1\n"),
825 826 827
      Cmd("git log -1 --format=%s rev1", "Log text 1.\n"),
      Cmd("git log -1 --format=%B rev1", "Text\nLOG=YES\nBUG=v8:321\nText\n"),
      Cmd("git log -1 --format=%an rev1", "author1@chromium.org\n"),
828
    ]
829 830
    if manual:
      expectations.append(RL(""))  # Open editor.
831
    if not force:
832 833
      expectations.append(
          Cmd("vi %s" % TEST_CONFIG["CHANGELOG_ENTRY_FILE"], ""))
834
    expectations += [
835 836 837 838
      Cmd("git fetch", ""),
      Cmd("git checkout -f origin/master", ""),
      Cmd("git diff origin/candidates push_hash", "patch content\n"),
      Cmd(("git new-branch %s --upstream origin/candidates" %
machenbach's avatar
machenbach committed
839
           TEST_CONFIG["CANDIDATESBRANCH"]), "", cb=ResetToCandidates),
840
      Cmd("git apply --index --reject \"%s\"" % TEST_CONFIG["PATCH_FILE"], ""),
841 842
      Cmd("git checkout -f origin/candidates -- ChangeLog", "",
          cb=ResetChangeLog),
machenbach's avatar
machenbach committed
843
      Cmd("git checkout -f origin/candidates -- include/v8-version.h", "",
844
          cb=self.WriteFakeVersionFile),
845 846 847 848 849 850 851 852
      Cmd("git commit -am \"%s\"" % commit_msg_squashed, ""),
    ]
    if manual:
      expectations.append(RL("Y"))  # Sanity check.
    expectations += [
      Cmd("git cl land -f --bypass-hooks", ""),
      Cmd("git checkout -f master", ""),
      Cmd("git fetch", ""),
machenbach's avatar
machenbach committed
853
      Cmd("git branch -D %s" % TEST_CONFIG["CANDIDATESBRANCH"], ""),
854
      Cmd(("git new-branch %s --upstream origin/candidates" %
machenbach's avatar
machenbach committed
855
           TEST_CONFIG["CANDIDATESBRANCH"]), "", cb=ResetToCandidates),
856
      Cmd("git commit -aF \"%s\"" % TEST_CONFIG["COMMITMSG_FILE"], "",
857
          cb=CheckVersionCommit),
858
      Cmd("git cl land -f --bypass-hooks", ""),
859
      Cmd("git fetch", ""),
machenbach@chromium.org's avatar
machenbach@chromium.org committed
860 861
      Cmd("git log -1 --format=%H --grep="
          "\"Version 3.22.5 (based on push_hash)\""
862 863 864
          " origin/candidates", "hsh_to_tag"),
      Cmd("git tag 3.22.5 hsh_to_tag", ""),
      Cmd("git push origin 3.22.5", ""),
865
      Cmd("git checkout -f origin/master", ""),
866
      Cmd("git branch -D %s" % TEST_CONFIG["BRANCHNAME"], ""),
machenbach's avatar
machenbach committed
867
      Cmd("git branch -D %s" % TEST_CONFIG["CANDIDATESBRANCH"], ""),
868
    ]
869
    self.Expect(expectations)
870

871
    args = ["-a", "author@chromium.org", "--revision", "push_hash"]
872 873 874
    if force: args.append("-f")
    if manual: args.append("-m")
    else: args += ["-r", "reviewer@chromium.org"]
machenbach's avatar
machenbach committed
875
    PushToCandidates(TEST_CONFIG, self).Run(args)
876

877
    cl = FileToText(os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))
878 879
    self.assertTrue(re.search(r"^\d\d\d\d\-\d+\-\d+: Version 3\.22\.5", cl))
    self.assertTrue(re.search(r"        Log text 1 \(issue 321\).", cl))
880 881 882
    self.assertTrue(re.search(r"1999\-04\-05: Version 3\.22\.4", cl))

    # Note: The version file is on build number 5 again in the end of this test
machenbach's avatar
machenbach committed
883
    # since the git command that merges to master is mocked out.
884

machenbach's avatar
machenbach committed
885 886
  def testPushToCandidatesManual(self):
    self._PushToCandidates(manual=True)
887

machenbach's avatar
machenbach committed
888 889
  def testPushToCandidatesSemiAutomatic(self):
    self._PushToCandidates()
890

machenbach's avatar
machenbach committed
891 892
  def testPushToCandidatesForced(self):
    self._PushToCandidates(force=True)
893

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
  def testCreateRelease(self):
    TextToFile("", os.path.join(TEST_CONFIG["DEFAULT_CWD"], ".git"))

    # The version file on master has build level 5.
    self.WriteFakeVersionFile(build=5)

    master_change_log = "2014-03-17: Sentinel\n"
    TextToFile(master_change_log,
               os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))

    commit_msg = """Version 3.22.5

Log text 1 (issue 321).

Performance and stability improvements on all platforms."""

    def ResetChangeLog():
      last_change_log = """1999-04-05: Version 3.22.4

        Performance and stability improvements on all platforms.\n"""
      TextToFile(last_change_log,
                 os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))


    def CheckVersionCommit():
      commit = FileToText(TEST_CONFIG["COMMITMSG_FILE"])
      self.assertEquals(commit_msg, commit)
      version = FileToText(
          os.path.join(TEST_CONFIG["DEFAULT_CWD"], VERSION_FILE))
machenbach's avatar
machenbach committed
923 924 925 926 927 928
      self.assertTrue(re.search(r"#define V8_MINOR_VERSION\s+22", version))
      self.assertTrue(re.search(r"#define V8_BUILD_NUMBER\s+5", version))
      self.assertFalse(re.search(r"#define V8_BUILD_NUMBER\s+6", version))
      self.assertTrue(re.search(r"#define V8_PATCH_LEVEL\s+0", version))
      self.assertTrue(
          re.search(r"#define V8_IS_CANDIDATE_VERSION\s+0", version))
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947

      # Check that the change log on the candidates branch got correctly
      # modified.
      change_log = FileToText(
          os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))
      self.assertEquals(
"""1999-07-31: Version 3.22.5

        Log text 1 (issue 321).

        Performance and stability improvements on all platforms.


1999-04-05: Version 3.22.4

        Performance and stability improvements on all platforms.\n""",
          change_log)

    expectations = [
948
      Cmd("git fetch origin +refs/heads/*:refs/heads/*", ""),
949 950 951 952
      Cmd("git checkout -f origin/master", ""),
      Cmd("git branch", ""),
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
      Cmd("git tag", self.TAGS),
machenbach's avatar
machenbach committed
953
      Cmd("git checkout -f origin/master -- include/v8-version.h",
954 955
          "", cb=self.WriteFakeVersionFile),
      Cmd("git log -1 --format=%H 3.22.4", "release_hash\n"),
956 957
      Cmd("git log -1 --format=%s release_hash", "Version 3.22.4\n"),
      Cmd("git log -1 --format=%H release_hash^", "abc3\n"),
958 959 960 961
      Cmd("git log --format=%H abc3..push_hash", "rev1\n"),
      Cmd("git log -1 --format=%s rev1", "Log text 1.\n"),
      Cmd("git log -1 --format=%B rev1", "Text\nLOG=YES\nBUG=v8:321\nText\n"),
      Cmd("git log -1 --format=%an rev1", "author1@chromium.org\n"),
962
      Cmd("git push origin push_hash:refs/heads/3.22.5", ""),
963
      Cmd("git reset --hard origin/master", ""),
964
      Cmd("git new-branch work-branch --upstream origin/3.22.5", ""),
965
      Cmd("git checkout -f 3.22.4 -- ChangeLog", "", cb=ResetChangeLog),
machenbach's avatar
machenbach committed
966
      Cmd("git checkout -f 3.22.4 -- include/v8-version.h", "",
967
          cb=self.WriteFakeVersionFile),
968 969
      Cmd("git checkout -f 3.22.4 -- WATCHLISTS", "",
          cb=self.WriteFakeWatchlistsFile),
970 971
      Cmd("git commit -aF \"%s\"" % TEST_CONFIG["COMMITMSG_FILE"], "",
          cb=CheckVersionCommit),
972
      Cmd("git cl land --bypass-hooks -f", ""),
973 974
      Cmd("git fetch", ""),
      Cmd("git log -1 --format=%H --grep="
975
          "\"Version 3.22.5\" origin/3.22.5", "hsh_to_tag"),
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
      Cmd("git tag 3.22.5 hsh_to_tag", ""),
      Cmd("git push origin 3.22.5", ""),
      Cmd("git checkout -f origin/master", ""),
      Cmd("git branch", "* master\n  work-branch\n"),
      Cmd("git branch -D work-branch", ""),
      Cmd("git gc", ""),
    ]
    self.Expect(expectations)

    args = ["-a", "author@chromium.org",
            "-r", "reviewer@chromium.org",
            "--revision", "push_hash"]
    CreateRelease(TEST_CONFIG, self).Run(args)

    cl = FileToText(os.path.join(TEST_CONFIG["DEFAULT_CWD"], CHANGELOG_FILE))
    self.assertTrue(re.search(r"^\d\d\d\d\-\d+\-\d+: Version 3\.22\.5", cl))
    self.assertTrue(re.search(r"        Log text 1 \(issue 321\).", cl))
    self.assertTrue(re.search(r"1999\-04\-05: Version 3\.22\.4", cl))

    # Note: The version file is on build number 5 again in the end of this test
    # since the git command that merges to master is mocked out.

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    # Check for correct content of the WATCHLISTS file

    watchlists_content = FileToText(os.path.join(TEST_CONFIG["DEFAULT_CWD"],
                                          WATCHLISTS_FILE))
    expected_watchlists_content = """
    'merges': [
      # Only enabled on branches created with tools/release/create_release.py
      'v8-merges@googlegroups.com',
    ],
"""
    self.assertEqual(watchlists_content, expected_watchlists_content)

1010 1011 1012 1013
  C_V8_22624_LOG = """V8 CL.

git-svn-id: https://v8.googlecode.com/svn/branches/bleeding_edge@22624 123

1014 1015 1016 1017 1018 1019
"""

  C_V8_123455_LOG = """V8 CL.

git-svn-id: https://v8.googlecode.com/svn/branches/bleeding_edge@123455 123

1020 1021 1022 1023 1024 1025 1026 1027
"""

  C_V8_123456_LOG = """V8 CL.

git-svn-id: https://v8.googlecode.com/svn/branches/bleeding_edge@123456 123

"""

1028
  ROLL_COMMIT_MSG = """Update V8 to version 3.22.4.
1029 1030

Summary of changes available at:
1031
https://chromium.googlesource.com/v8/v8/+log/last_rol..roll_hsh
1032 1033

Please follow these instructions for assigning/CC'ing issues:
1034
https://github.com/v8/v8/wiki/Triaging%20issues
1035

1036 1037
Please close rolling in case of a roll revert:
https://v8-roll.appspot.com/
1038
This only works with a Google account.
1039

1040
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
1041

1042
TBR=reviewer@chromium.org"""
1043

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
  # Snippet from the original DEPS file.
  FAKE_DEPS = """
vars = {
  "v8_revision": "last_roll_hsh",
}
deps = {
  "src/v8":
    (Var("googlecode_url") % "v8") + "/" + Var("v8_branch") + "@" +
    Var("v8_revision"),
}
"""

  def testChromiumRollUpToDate(self):
    TEST_CONFIG["CHROMIUM"] = self.MakeEmptyTempDirectory()
1058
    json_output_file = os.path.join(TEST_CONFIG["CHROMIUM"], "out.json")
1059 1060 1061 1062 1063 1064
    TextToFile(self.FAKE_DEPS, os.path.join(TEST_CONFIG["CHROMIUM"], "DEPS"))
    self.Expect([
      Cmd("git fetch origin", ""),
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
      Cmd("git describe --tags last_roll_hsh", "3.22.4"),
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
1065
      Cmd("git rev-list --max-age=395200 --tags",
1066 1067 1068 1069 1070 1071 1072 1073 1074
          "bad_tag\nroll_hsh\nhash_123"),
      Cmd("git describe --tags bad_tag", ""),
      Cmd("git describe --tags roll_hsh", "3.22.4"),
      Cmd("git describe --tags hash_123", "3.22.3"),
      Cmd("git describe --tags roll_hsh", "3.22.4"),
      Cmd("git describe --tags hash_123", "3.22.3"),
    ])

    result = auto_roll.AutoRoll(TEST_CONFIG, self).Run(
1075 1076 1077
        AUTO_PUSH_ARGS + [
          "-c", TEST_CONFIG["CHROMIUM"],
          "--json-output", json_output_file])
1078
    self.assertEquals(0, result)
1079 1080 1081
    json_output = json.loads(FileToText(json_output_file))
    self.assertEquals("up_to_date", json_output["monitoring_state"])

1082

1083
  def testChromiumRoll(self):
1084
    # Setup fake directory structures.
1085
    TEST_CONFIG["CHROMIUM"] = self.MakeEmptyTempDirectory()
1086
    json_output_file = os.path.join(TEST_CONFIG["CHROMIUM"], "out.json")
1087
    TextToFile(self.FAKE_DEPS, os.path.join(TEST_CONFIG["CHROMIUM"], "DEPS"))
1088 1089
    TextToFile("", os.path.join(TEST_CONFIG["CHROMIUM"], ".git"))
    chrome_dir = TEST_CONFIG["CHROMIUM"]
1090 1091
    os.makedirs(os.path.join(chrome_dir, "v8"))

1092
    def WriteDeps():
1093
      TextToFile("Some line\n   \"v8_revision\": \"22624\",\n  some line",
1094
                 os.path.join(chrome_dir, "DEPS"))
1095

1096
    expectations = [
1097
      Cmd("git fetch origin", ""),
1098
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
1099 1100
      Cmd("git describe --tags last_roll_hsh", "3.22.3.1"),
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
1101
      Cmd("git rev-list --max-age=395200 --tags",
1102 1103 1104 1105 1106 1107
          "bad_tag\nroll_hsh\nhash_123"),
      Cmd("git describe --tags bad_tag", ""),
      Cmd("git describe --tags roll_hsh", "3.22.4"),
      Cmd("git describe --tags hash_123", "3.22.3"),
      Cmd("git describe --tags roll_hsh", "3.22.4"),
      Cmd("git log -1 --format=%s roll_hsh", "Version 3.22.4\n"),
1108
      Cmd("git describe --tags roll_hsh", "3.22.4"),
1109
      Cmd("git describe --tags last_roll_hsh", "3.22.2.1"),
1110 1111
      Cmd("git status -s -uno", "", cwd=chrome_dir),
      Cmd("git checkout -f master", "", cwd=chrome_dir),
1112
      Cmd("git branch", "", cwd=chrome_dir),
1113
      Cmd("git pull", "", cwd=chrome_dir),
1114
      Cmd("git fetch origin", ""),
1115
      Cmd("git new-branch work-branch", "", cwd=chrome_dir),
1116
      Cmd("roll-dep-svn v8 roll_hsh", "rolled", cb=WriteDeps, cwd=chrome_dir),
1117 1118 1119
      Cmd(("git commit -am \"%s\" "
           "--author \"author@chromium.org <author@chromium.org>\"" %
           self.ROLL_COMMIT_MSG),
1120
          "", cwd=chrome_dir),
1121
      Cmd("git cl upload --send-mail --email \"author@chromium.org\" -f "
1122
          "--use-commit-queue --bypass-hooks", "", cwd=chrome_dir),
1123 1124
      Cmd("git checkout -f master", "", cwd=chrome_dir),
      Cmd("git branch -D work-branch", "", cwd=chrome_dir),
1125 1126
    ]
    self.Expect(expectations)
1127

1128
    args = ["-a", "author@chromium.org", "-c", chrome_dir,
1129
            "-r", "reviewer@chromium.org", "--json-output", json_output_file]
1130
    auto_roll.AutoRoll(TEST_CONFIG, self).Run(args)
1131

1132
    deps = FileToText(os.path.join(chrome_dir, "DEPS"))
1133
    self.assertTrue(re.search("\"v8_revision\": \"22624\"", deps))
1134

1135 1136 1137
    json_output = json.loads(FileToText(json_output_file))
    self.assertEquals("success", json_output["monitoring_state"])

1138
  def testCheckLastPushRecently(self):
1139
    self.Expect([
1140 1141 1142 1143 1144 1145
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
      Cmd("git tag", self.TAGS),
      Cmd("git log -1 --format=%H 3.22.4", "release_hash\n"),
      Cmd("git log -1 --format=%s release_hash",
          "Version 3.22.4 (based on abc3)\n"),
      Cmd("git log --format=%H abc3..abc123", "\n"),
1146 1147
    ])

1148
    self._state["candidate"] = "abc123"
1149
    self.assertEquals(0, self.RunStep(
1150
        auto_push.AutoPush, LastReleaseBailout, AUTO_PUSH_ARGS))
1151

1152
  def testAutoPush(self):
1153
    self.Expect([
1154
      Cmd("git fetch", ""),
1155 1156
      Cmd("git fetch origin +refs/heads/lkgr:refs/heads/lkgr", ""),
      Cmd("git show-ref -s refs/heads/lkgr", "abc123\n"),
1157 1158 1159 1160 1161 1162
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
      Cmd("git tag", self.TAGS),
      Cmd("git log -1 --format=%H 3.22.4", "release_hash\n"),
      Cmd("git log -1 --format=%s release_hash",
          "Version 3.22.4 (based on abc3)\n"),
      Cmd("git log --format=%H abc3..abc123", "some_stuff\n"),
1163 1164
    ])

1165
    auto_push.AutoPush(TEST_CONFIG, self).Run(AUTO_PUSH_ARGS + ["--push"])
1166

1167
    state = json.loads(FileToText("%s-state.json"
1168
                                  % TEST_CONFIG["PERSISTFILE_BASENAME"]))
1169

1170
    self.assertEquals("abc123", state["candidate"])
1171

1172
  def testRollMerge(self):
1173
    TEST_CONFIG["ALREADY_MERGING_SENTINEL_FILE"] = self.MakeEmptyTempFile()
1174
    TextToFile("", os.path.join(TEST_CONFIG["DEFAULT_CWD"], ".git"))
1175
    self.WriteFakeVersionFile(build=5)
1176 1177 1178 1179 1180
    os.environ["EDITOR"] = "vi"
    extra_patch = self.MakeEmptyTempFile()

    def VerifyPatch(patch):
      return lambda: self.assertEquals(patch,
1181
          FileToText(TEST_CONFIG["TEMPORARY_PATCH_FILE"]))
1182

1183
    msg = """Version 3.22.5.1 (cherry-pick)
1184

1185 1186 1187 1188 1189
Merged ab12345
Merged ab23456
Merged ab34567
Merged ab45678
Merged ab56789
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204

Title4

Title2

Title3

Title1

Revert "Something"

BUG=123,234,345,456,567,v8:123
LOG=N
"""

machenbach's avatar
machenbach committed
1205
    def VerifyLand():
1206 1207 1208 1209
      commit = FileToText(TEST_CONFIG["COMMITMSG_FILE"])
      self.assertEquals(msg, commit)
      version = FileToText(
          os.path.join(TEST_CONFIG["DEFAULT_CWD"], VERSION_FILE))
machenbach's avatar
machenbach committed
1210 1211 1212 1213 1214
      self.assertTrue(re.search(r"#define V8_MINOR_VERSION\s+22", version))
      self.assertTrue(re.search(r"#define V8_BUILD_NUMBER\s+5", version))
      self.assertTrue(re.search(r"#define V8_PATCH_LEVEL\s+1", version))
      self.assertTrue(
          re.search(r"#define V8_IS_CANDIDATE_VERSION\s+0", version))
1215 1216 1217

    self.Expect([
      Cmd("git status -s -uno", ""),
1218
      Cmd("git checkout -f origin/master", ""),
1219 1220
      Cmd("git fetch", ""),
      Cmd("git branch", "  branch1\n* branch2\n"),
1221
      Cmd("git new-branch %s --upstream refs/remotes/origin/candidates" %
1222
          TEST_CONFIG["BRANCHNAME"], ""),
1223
      Cmd(("git log --format=%H --grep=\"Port ab12345\" "
1224
           "--reverse origin/master"),
1225 1226 1227 1228
          "ab45678\nab23456"),
      Cmd("git log -1 --format=%s ab45678", "Title1"),
      Cmd("git log -1 --format=%s ab23456", "Title2"),
      Cmd(("git log --format=%H --grep=\"Port ab23456\" "
1229 1230
           "--reverse origin/master"),
          ""),
1231
      Cmd(("git log --format=%H --grep=\"Port ab34567\" "
1232
           "--reverse origin/master"),
1233 1234 1235 1236 1237
          "ab56789"),
      Cmd("git log -1 --format=%s ab56789", "Title3"),
      RL("Y"),  # Automatically add corresponding ports (ab34567, ab56789)?
      # Simulate git being down which stops the script.
      Cmd("git log -1 --format=%s ab12345", None),
1238
      # Restart script in the failing step.
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
      Cmd("git log -1 --format=%s ab12345", "Title4"),
      Cmd("git log -1 --format=%s ab23456", "Title2"),
      Cmd("git log -1 --format=%s ab34567", "Title3"),
      Cmd("git log -1 --format=%s ab45678", "Title1"),
      Cmd("git log -1 --format=%s ab56789", "Revert \"Something\""),
      Cmd("git log -1 ab12345", "Title4\nBUG=123\nBUG=234"),
      Cmd("git log -1 ab23456", "Title2\n BUG = v8:123,345"),
      Cmd("git log -1 ab34567", "Title3\nLOG=n\nBUG=567, 456"),
      Cmd("git log -1 ab45678", "Title1\nBUG="),
      Cmd("git log -1 ab56789", "Revert \"Something\"\nBUG=none"),
      Cmd("git log -1 -p ab12345", "patch4"),
1250 1251 1252
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch4")),
1253
      Cmd("git log -1 -p ab23456", "patch2"),
1254 1255 1256
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch2")),
1257
      Cmd("git log -1 -p ab34567", "patch3"),
1258 1259 1260
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch3")),
1261
      Cmd("git log -1 -p ab45678", "patch1"),
1262 1263 1264
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch1")),
1265
      Cmd("git log -1 -p ab56789", "patch5\n"),
1266 1267 1268 1269 1270 1271 1272 1273
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch5\n")),
      Cmd("git apply --index --reject \"%s\"" % extra_patch, ""),
      RL("Y"),  # Automatically increment patch level?
      Cmd("git commit -aF \"%s\"" % TEST_CONFIG["COMMITMSG_FILE"], ""),
      RL("reviewer@chromium.org"),  # V8 reviewer.
      Cmd("git cl upload --send-mail -r \"reviewer@chromium.org\" "
1274
          "--bypass-hooks --cc \"ulan@chromium.org\"", ""),
1275 1276 1277
      Cmd("git checkout -f %s" % TEST_CONFIG["BRANCHNAME"], ""),
      RL("LGTM"),  # Enter LGTM for V8 CL.
      Cmd("git cl presubmit", "Presubmit successfull\n"),
1278
      Cmd("git cl land -f --bypass-hooks", "Closing issue\n",
machenbach's avatar
machenbach committed
1279
          cb=VerifyLand),
1280 1281
      Cmd("git fetch", ""),
      Cmd("git log -1 --format=%H --grep=\""
1282
          "Version 3.22.5.1 (cherry-pick)"
1283
          "\" refs/remotes/origin/candidates",
1284 1285 1286
          ""),
      Cmd("git fetch", ""),
      Cmd("git log -1 --format=%H --grep=\""
1287
          "Version 3.22.5.1 (cherry-pick)"
1288
          "\" refs/remotes/origin/candidates",
1289 1290 1291
          "hsh_to_tag"),
      Cmd("git tag 3.22.5.1 hsh_to_tag", ""),
      Cmd("git push origin 3.22.5.1", ""),
1292
      Cmd("git checkout -f origin/master", ""),
1293 1294 1295
      Cmd("git branch -D %s" % TEST_CONFIG["BRANCHNAME"], ""),
    ])

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    # ab12345 and ab34567 are patches. ab23456 (included) and ab45678 are the
    # MIPS ports of ab12345. ab56789 is the MIPS port of ab34567.
    args = ["-f", "-p", extra_patch, "--branch", "candidates",
            "ab12345", "ab23456", "ab34567"]

    # The first run of the script stops because of git being down.
    self.assertRaises(GitFailedException,
        lambda: RollMerge(TEST_CONFIG, self).Run(args))

    # Test that state recovery after restarting the script works.
    args += ["-s", "4"]
    RollMerge(TEST_CONFIG, self).Run(args)

  def testReleases(self):
    c_hash1_commit_log = """Update V8 to Version 4.2.71.

Cr-Commit-Position: refs/heads/master@{#5678}
"""
    c_hash2_commit_log = """Revert something.

BUG=12345

Reason:
> Some reason.
> Cr-Commit-Position: refs/heads/master@{#12345}
> git-svn-id: svn://svn.chromium.org/chrome/trunk/src@12345 003-1c4

Review URL: https://codereview.chromium.org/12345

Cr-Commit-Position: refs/heads/master@{#4567}
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@4567 0039-1c4b

"""
    c_hash3_commit_log = """Simple.

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@3456 0039-1c4b

"""
    c_hash_234_commit_log = """Version 3.3.1.1 (cherry-pick).

Merged abc12.

Review URL: fake.com

Cr-Commit-Position: refs/heads/candidates@{#234}
"""
    c_hash_123_commit_log = """Version 3.3.1.0

git-svn-id: googlecode@123 0039-1c4b
"""
    c_hash_345_commit_log = """Version 3.4.0.

Cr-Commit-Position: refs/heads/candidates@{#345}
"""
    c_hash_456_commit_log = """Version 4.2.71.

Cr-Commit-Position: refs/heads/4.2.71@{#1}
"""
    c_deps = "Line\n   \"v8_revision\": \"%s\",\n  line\n"

    json_output = self.MakeEmptyTempFile()
    csv_output = self.MakeEmptyTempFile()
    self.WriteFakeVersionFile()

    TEST_CONFIG["CHROMIUM"] = self.MakeEmptyTempDirectory()
    chrome_dir = TEST_CONFIG["CHROMIUM"]
    chrome_v8_dir = os.path.join(chrome_dir, "v8")
    os.makedirs(chrome_v8_dir)

    def ResetVersion(major, minor, build, patch=0):
      return lambda: self.WriteFakeVersionFile(major=major,
                                               minor=minor,
                                               build=build,
                                               patch=patch)

    self.Expect([
      Cmd("git status -s -uno", ""),
      Cmd("git checkout -f origin/master", ""),
      Cmd("git fetch", ""),
      Cmd("git branch", "  branch1\n* branch2\n"),
      Cmd("git new-branch %s" % TEST_CONFIG["BRANCHNAME"], ""),
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
      Cmd("git rev-list --max-age=395200 --tags",
          "bad_tag\nhash_234\nhash_123\nhash_345\nhash_456\n"),
      Cmd("git describe --tags bad_tag", "3.23.42-1-deadbeef"),
      Cmd("git describe --tags hash_234", "3.3.1.1"),
      Cmd("git describe --tags hash_123", "3.21.2"),
      Cmd("git describe --tags hash_345", "3.22.3"),
      Cmd("git describe --tags hash_456", "4.2.71"),
      Cmd("git diff --name-only hash_234 hash_234^", VERSION_FILE),
      Cmd("git checkout -f hash_234 -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 3, 1, 1)),
      Cmd("git branch -r --contains hash_234", "  branch-heads/3.3\n"),
      Cmd("git log -1 --format=%B hash_234", c_hash_234_commit_log),
      Cmd("git log -1 --format=%s hash_234", ""),
      Cmd("git log -1 --format=%B hash_234", c_hash_234_commit_log),
      Cmd("git log -1 --format=%ci hash_234", "18:15"),
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 22, 5)),
      Cmd("git diff --name-only hash_123 hash_123^", VERSION_FILE),
      Cmd("git checkout -f hash_123 -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 21, 2)),
      Cmd("git branch -r --contains hash_123", "  branch-heads/3.21\n"),
      Cmd("git log -1 --format=%B hash_123", c_hash_123_commit_log),
      Cmd("git log -1 --format=%s hash_123", ""),
      Cmd("git log -1 --format=%B hash_123", c_hash_123_commit_log),
      Cmd("git log -1 --format=%ci hash_123", "03:15"),
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 22, 5)),
      Cmd("git diff --name-only hash_345 hash_345^", VERSION_FILE),
      Cmd("git checkout -f hash_345 -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 22, 3)),
      Cmd("git branch -r --contains hash_345", "  origin/candidates\n"),
      Cmd("git log -1 --format=%B hash_345", c_hash_345_commit_log),
      Cmd("git log -1 --format=%s hash_345", ""),
      Cmd("git log -1 --format=%B hash_345", c_hash_345_commit_log),
      Cmd("git log -1 --format=%ci hash_345", ""),
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 22, 5)),
      Cmd("git diff --name-only hash_456 hash_456^", VERSION_FILE),
      Cmd("git checkout -f hash_456 -- %s" % VERSION_FILE, "",
          cb=ResetVersion(4, 2, 71)),
      Cmd("git branch -r --contains hash_456", "  origin/4.2.71\n"),
      Cmd("git log -1 --format=%B hash_456", c_hash_456_commit_log),
      Cmd("git log -1 --format=%H 4.2.71", "hash_456"),
      Cmd("git log -1 --format=%s hash_456", "Version 4.2.71"),
      Cmd("git log -1 --format=%H hash_456^", "master_456"),
      Cmd("git log -1 --format=%B master_456",
          "Cr-Commit-Position: refs/heads/master@{#456}"),
      Cmd("git log -1 --format=%B hash_456", c_hash_456_commit_log),
      Cmd("git log -1 --format=%ci hash_456", "02:15"),
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 22, 5)),
      Cmd("git fetch origin +refs/heads/*:refs/remotes/origin/* "
          "+refs/branch-heads/*:refs/remotes/branch-heads/*", "",
          cwd=chrome_dir),
      Cmd("git fetch origin", "", cwd=chrome_v8_dir),
      Cmd("git log --format=%H --grep=\"V8\" origin/master -- DEPS",
          "c_hash1\nc_hash2\nc_hash3\n",
          cwd=chrome_dir),
      Cmd("git show c_hash1:DEPS", c_deps % "hash_456", cwd=chrome_dir),
      Cmd("git log -1 --format=%B c_hash1", c_hash1_commit_log,
          cwd=chrome_dir),
      Cmd("git show c_hash2:DEPS", c_deps % "hash_345", cwd=chrome_dir),
      Cmd("git log -1 --format=%B c_hash2", c_hash2_commit_log,
          cwd=chrome_dir),
      Cmd("git show c_hash3:DEPS", c_deps % "deadbeef", cwd=chrome_dir),
      Cmd("git log -1 --format=%B c_hash3", c_hash3_commit_log,
          cwd=chrome_dir),
      Cmd("git branch -r", " weird/123\n  branch-heads/7\n", cwd=chrome_dir),
      Cmd("git show refs/branch-heads/7:DEPS", c_deps % "hash_345",
          cwd=chrome_dir),
      URL("http://omahaproxy.appspot.com/all.json", """[{
        "os": "win",
        "versions": [{
          "version": "2.2.2.2",
          "v8_version": "22.2.2.2",
          "current_reldate": "04/09/15",
          "os": "win",
          "channel": "canary",
          "previous_version": "1.1.1.0"
          }]
        }]"""),
      URL("http://omahaproxy.appspot.com/v8.json?version=1.1.1.0", """{
        "chromium_version": "1.1.1.0",
        "v8_version": "11.1.1.0"
        }"""),
      Cmd("git rev-list -1 11.1.1", "v8_previous_version_hash"),
      Cmd("git rev-list -1 22.2.2.2", "v8_version_hash"),
      Cmd("git checkout -f origin/master", ""),
      Cmd("git branch -D %s" % TEST_CONFIG["BRANCHNAME"], "")
    ])

    args = ["-c", TEST_CONFIG["CHROMIUM"],
            "--json", json_output,
            "--csv", csv_output,
            "--max-releases", "1"]
    Releases(TEST_CONFIG, self).Run(args)

    # Check expected output.
    csv = ("4.2.71,4.2.71,1,5678,\r\n"
           "3.22.3,candidates,345,4567:5677,\r\n"
           "3.21.2,3.21,123,,\r\n"
           "3.3.1.1,3.3,234,,abc12\r\n")
    self.assertEquals(csv, FileToText(csv_output))

    expected_json = {"chrome_releases":{
                                        "canaries": [
                                                     {
                           "chrome_version": "2.2.2.2",
                           "os": "win",
                           "release_date": "04/09/15",
                           "v8_version": "22.2.2.2",
                           "v8_version_hash": "v8_version_hash",
                           "v8_previous_version": "11.1.1.0",
                           "v8_previous_version_hash": "v8_previous_version_hash"
                           }]},
                     "releases":[
      {
        "revision": "1",
        "revision_git": "hash_456",
        "master_position": "456",
        "master_hash": "master_456",
        "patches_merged": "",
        "version": "4.2.71",
        "chromium_revision": "5678",
        "branch": "4.2.71",
        "review_link": "",
        "date": "02:15",
        "chromium_branch": "",
        # FIXME(machenbach): Fix revisions link for git.
        "revision_link": "https://code.google.com/p/v8/source/detail?r=1",
      },
      {
        "revision": "345",
        "revision_git": "hash_345",
        "master_position": "",
        "master_hash": "",
        "patches_merged": "",
        "version": "3.22.3",
        "chromium_revision": "4567:5677",
        "branch": "candidates",
        "review_link": "",
        "date": "",
        "chromium_branch": "7",
        "revision_link": "https://code.google.com/p/v8/source/detail?r=345",
      },
      {
        "revision": "123",
        "revision_git": "hash_123",
        "patches_merged": "",
        "master_position": "",
        "master_hash": "",
        "version": "3.21.2",
        "chromium_revision": "",
        "branch": "3.21",
        "review_link": "",
        "date": "03:15",
        "chromium_branch": "",
        "revision_link": "https://code.google.com/p/v8/source/detail?r=123",
      },
      {
        "revision": "234",
        "revision_git": "hash_234",
        "patches_merged": "abc12",
        "master_position": "",
        "master_hash": "",
        "version": "3.3.1.1",
        "chromium_revision": "",
        "branch": "3.3",
        "review_link": "fake.com",
        "date": "18:15",
        "chromium_branch": "",
        "revision_link": "https://code.google.com/p/v8/source/detail?r=234",
      },],
    }
    self.assertEquals(expected_json, json.loads(FileToText(json_output)))

  def testMergeToBranch(self):
    TEST_CONFIG["ALREADY_MERGING_SENTINEL_FILE"] = self.MakeEmptyTempFile()
    TextToFile("", os.path.join(TEST_CONFIG["DEFAULT_CWD"], ".git"))
    self.WriteFakeVersionFile(build=5)
    os.environ["EDITOR"] = "vi"
    extra_patch = self.MakeEmptyTempFile()


    def VerifyPatch(patch):
      return lambda: self.assertEquals(patch,
          FileToText(TEST_CONFIG["TEMPORARY_PATCH_FILE"]))

    info_msg = ("NOTE: This script will no longer automatically "
     "update include/v8-version.h "
     "and create a tag. This is done automatically by the autotag bot. "
     "Please call the merge_to_branch.py with --help for more information.")

    msg = """Merged: Squashed multiple commits.

Merged: Title4
Revision: ab12345

Merged: Title2
Revision: ab23456

Merged: Title3
Revision: ab34567

Merged: Title1
Revision: ab45678

Merged: Revert \"Something\"
Revision: ab56789

BUG=123,234,345,456,567,v8:123
LOG=N
NOTRY=true
NOPRESUBMIT=true
NOTREECHECKS=true
"""

    def VerifyLand():
      commit = FileToText(TEST_CONFIG["COMMITMSG_FILE"])
      self.assertEquals(msg, commit)

    self.Expect([
      Cmd("git status -s -uno", ""),
      Cmd("git checkout -f origin/master", ""),
      Cmd("git fetch", ""),
      Cmd("git branch", "  branch1\n* branch2\n"),
      Cmd("git new-branch %s --upstream refs/remotes/origin/candidates" %
          TEST_CONFIG["BRANCHNAME"], ""),
      Cmd(("git log --format=%H --grep=\"^[Pp]ort ab12345\" "
           "--reverse origin/master"),
          "ab45678\nab23456"),
      Cmd("git log -1 --format=%s ab45678", "Title1"),
      Cmd("git log -1 --format=%s ab23456", "Title2"),
      Cmd(("git log --format=%H --grep=\"^[Pp]ort ab23456\" "
           "--reverse origin/master"),
          ""),
      Cmd(("git log --format=%H --grep=\"^[Pp]ort ab34567\" "
           "--reverse origin/master"),
          "ab56789"),
      Cmd("git log -1 --format=%s ab56789", "Title3"),
      RL("Y"),  # Automatically add corresponding ports (ab34567, ab56789)?
      # Simulate git being down which stops the script.
      Cmd("git log -1 --format=%s ab12345", None),
      # Restart script in the failing step.
      Cmd("git log -1 --format=%s ab12345", "Title4"),
      Cmd("git log -1 --format=%s ab23456", "Title2"),
      Cmd("git log -1 --format=%s ab34567", "Title3"),
      Cmd("git log -1 --format=%s ab45678", "Title1"),
      Cmd("git log -1 --format=%s ab56789", "Revert \"Something\""),
      Cmd("git log -1 ab12345", "Title4\nBUG=123\nBUG=234"),
      Cmd("git log -1 ab23456", "Title2\n BUG = v8:123,345"),
      Cmd("git log -1 ab34567", "Title3\nLOG=n\nBUG=567, 456"),
      Cmd("git log -1 ab45678", "Title1\nBUG="),
      Cmd("git log -1 ab56789", "Revert \"Something\"\nBUG=none"),
      Cmd("git log -1 -p ab12345", "patch4"),
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch4")),
      Cmd("git log -1 -p ab23456", "patch2"),
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch2")),
      Cmd("git log -1 -p ab34567", "patch3"),
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch3")),
      Cmd("git log -1 -p ab45678", "patch1"),
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch1")),
      Cmd("git log -1 -p ab56789", "patch5\n"),
      Cmd(("git apply --index --reject \"%s\"" %
           TEST_CONFIG["TEMPORARY_PATCH_FILE"]),
          "", cb=VerifyPatch("patch5\n")),
      Cmd("git apply --index --reject \"%s\"" % extra_patch, ""),
      Cmd("git commit -aF \"%s\"" % TEST_CONFIG["COMMITMSG_FILE"], ""),
      RL("reviewer@chromium.org"),  # V8 reviewer.
      Cmd("git cl upload --send-mail -r \"reviewer@chromium.org\" "
          "--bypass-hooks --cc \"ulan@chromium.org\"", ""),
      Cmd("git cl comments -a \"%s\"" % info_msg, ""),
      Cmd("git checkout -f %s" % TEST_CONFIG["BRANCHNAME"], ""),
      RL("LGTM"),  # Enter LGTM for V8 CL.
      Cmd("git cl presubmit", "Presubmit successfull\n"),
      Cmd("git cl land -f --bypass-hooks", "Closing issue\n",
          cb=VerifyLand),
      Cmd("git checkout -f origin/master", ""),
      Cmd("git branch -D %s" % TEST_CONFIG["BRANCHNAME"], ""),
    ])

1667 1668
    # ab12345 and ab34567 are patches. ab23456 (included) and ab45678 are the
    # MIPS ports of ab12345. ab56789 is the MIPS port of ab34567.
1669
    args = ["-f", "-p", extra_patch, "--branch", "candidates",
1670
            "ab12345", "ab23456", "ab34567"]
1671

1672
    # The first run of the script stops because of git being down.
1673
    self.assertRaises(GitFailedException,
1674
        lambda: MergeToBranch(TEST_CONFIG, self).Run(args))
1675 1676

    # Test that state recovery after restarting the script works.
1677
    args += ["-s", "4"]
1678
    MergeToBranch(TEST_CONFIG, self).Run(args)
1679

1680
  def testReleases(self):
1681 1682 1683 1684
    c_hash1_commit_log = """Update V8 to Version 4.2.71.

Cr-Commit-Position: refs/heads/master@{#5678}
"""
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
    c_hash2_commit_log = """Revert something.

BUG=12345

Reason:
> Some reason.
> Cr-Commit-Position: refs/heads/master@{#12345}
> git-svn-id: svn://svn.chromium.org/chrome/trunk/src@12345 003-1c4

Review URL: https://codereview.chromium.org/12345

Cr-Commit-Position: refs/heads/master@{#4567}
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@4567 0039-1c4b

"""
    c_hash3_commit_log = """Simple.

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@3456 0039-1c4b

1704
"""
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    c_hash_234_commit_log = """Version 3.3.1.1 (cherry-pick).

Merged abc12.

Review URL: fake.com

Cr-Commit-Position: refs/heads/candidates@{#234}
"""
    c_hash_123_commit_log = """Version 3.3.1.0

git-svn-id: googlecode@123 0039-1c4b
"""
    c_hash_345_commit_log = """Version 3.4.0.

Cr-Commit-Position: refs/heads/candidates@{#345}
1720 1721 1722 1723
"""
    c_hash_456_commit_log = """Version 4.2.71.

Cr-Commit-Position: refs/heads/4.2.71@{#1}
1724
"""
1725
    c_deps = "Line\n   \"v8_revision\": \"%s\",\n  line\n"
1726

1727 1728 1729 1730
    json_output = self.MakeEmptyTempFile()
    csv_output = self.MakeEmptyTempFile()
    self.WriteFakeVersionFile()

1731 1732
    TEST_CONFIG["CHROMIUM"] = self.MakeEmptyTempDirectory()
    chrome_dir = TEST_CONFIG["CHROMIUM"]
1733 1734
    chrome_v8_dir = os.path.join(chrome_dir, "v8")
    os.makedirs(chrome_v8_dir)
1735

1736 1737 1738
    def ResetVersion(major, minor, build, patch=0):
      return lambda: self.WriteFakeVersionFile(major=major,
                                               minor=minor,
1739 1740 1741
                                               build=build,
                                               patch=patch)

1742
    self.Expect([
1743
      Cmd("git status -s -uno", ""),
1744
      Cmd("git checkout -f origin/master", ""),
1745
      Cmd("git fetch", ""),
1746
      Cmd("git branch", "  branch1\n* branch2\n"),
1747
      Cmd("git new-branch %s" % TEST_CONFIG["BRANCHNAME"], ""),
1748 1749
      Cmd("git fetch origin +refs/tags/*:refs/tags/*", ""),
      Cmd("git rev-list --max-age=395200 --tags",
1750
          "bad_tag\nhash_234\nhash_123\nhash_345\nhash_456\n"),
1751 1752 1753 1754
      Cmd("git describe --tags bad_tag", "3.23.42-1-deadbeef"),
      Cmd("git describe --tags hash_234", "3.3.1.1"),
      Cmd("git describe --tags hash_123", "3.21.2"),
      Cmd("git describe --tags hash_345", "3.22.3"),
1755
      Cmd("git describe --tags hash_456", "4.2.71"),
1756 1757
      Cmd("git diff --name-only hash_234 hash_234^", VERSION_FILE),
      Cmd("git checkout -f hash_234 -- %s" % VERSION_FILE, "",
1758
          cb=ResetVersion(3, 3, 1, 1)),
1759
      Cmd("git branch -r --contains hash_234", "  branch-heads/3.3\n"),
1760
      Cmd("git log -1 --format=%B hash_234", c_hash_234_commit_log),
1761
      Cmd("git log -1 --format=%s hash_234", ""),
1762
      Cmd("git log -1 --format=%B hash_234", c_hash_234_commit_log),
1763
      Cmd("git log -1 --format=%ci hash_234", "18:15"),
1764
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
1765
          cb=ResetVersion(3, 22, 5)),
1766 1767
      Cmd("git diff --name-only hash_123 hash_123^", VERSION_FILE),
      Cmd("git checkout -f hash_123 -- %s" % VERSION_FILE, "",
1768
          cb=ResetVersion(3, 21, 2)),
1769
      Cmd("git branch -r --contains hash_123", "  branch-heads/3.21\n"),
1770
      Cmd("git log -1 --format=%B hash_123", c_hash_123_commit_log),
1771
      Cmd("git log -1 --format=%s hash_123", ""),
1772
      Cmd("git log -1 --format=%B hash_123", c_hash_123_commit_log),
1773
      Cmd("git log -1 --format=%ci hash_123", "03:15"),
1774
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
1775
          cb=ResetVersion(3, 22, 5)),
1776 1777
      Cmd("git diff --name-only hash_345 hash_345^", VERSION_FILE),
      Cmd("git checkout -f hash_345 -- %s" % VERSION_FILE, "",
1778
          cb=ResetVersion(3, 22, 3)),
1779
      Cmd("git branch -r --contains hash_345", "  origin/candidates\n"),
1780
      Cmd("git log -1 --format=%B hash_345", c_hash_345_commit_log),
1781
      Cmd("git log -1 --format=%s hash_345", ""),
1782
      Cmd("git log -1 --format=%B hash_345", c_hash_345_commit_log),
1783
      Cmd("git log -1 --format=%ci hash_345", ""),
1784
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
          cb=ResetVersion(3, 22, 5)),
      Cmd("git diff --name-only hash_456 hash_456^", VERSION_FILE),
      Cmd("git checkout -f hash_456 -- %s" % VERSION_FILE, "",
          cb=ResetVersion(4, 2, 71)),
      Cmd("git branch -r --contains hash_456", "  origin/4.2.71\n"),
      Cmd("git log -1 --format=%B hash_456", c_hash_456_commit_log),
      Cmd("git log -1 --format=%H 4.2.71", "hash_456"),
      Cmd("git log -1 --format=%s hash_456", "Version 4.2.71"),
      Cmd("git log -1 --format=%H hash_456^", "master_456"),
      Cmd("git log -1 --format=%B master_456",
          "Cr-Commit-Position: refs/heads/master@{#456}"),
      Cmd("git log -1 --format=%B hash_456", c_hash_456_commit_log),
      Cmd("git log -1 --format=%ci hash_456", "02:15"),
      Cmd("git checkout -f HEAD -- %s" % VERSION_FILE, "",
          cb=ResetVersion(3, 22, 5)),
1800 1801
      Cmd("git fetch origin +refs/heads/*:refs/remotes/origin/* "
          "+refs/branch-heads/*:refs/remotes/branch-heads/*", "",
1802
          cwd=chrome_dir),
1803
      Cmd("git fetch origin", "", cwd=chrome_v8_dir),
1804 1805
      Cmd("git log --format=%H --grep=\"V8\" origin/master -- DEPS",
          "c_hash1\nc_hash2\nc_hash3\n",
1806
          cwd=chrome_dir),
1807
      Cmd("git show c_hash1:DEPS", c_deps % "hash_456", cwd=chrome_dir),
1808
      Cmd("git log -1 --format=%B c_hash1", c_hash1_commit_log,
1809
          cwd=chrome_dir),
1810
      Cmd("git show c_hash2:DEPS", c_deps % "hash_345", cwd=chrome_dir),
1811 1812
      Cmd("git log -1 --format=%B c_hash2", c_hash2_commit_log,
          cwd=chrome_dir),
1813
      Cmd("git show c_hash3:DEPS", c_deps % "deadbeef", cwd=chrome_dir),
1814 1815 1816
      Cmd("git log -1 --format=%B c_hash3", c_hash3_commit_log,
          cwd=chrome_dir),
      Cmd("git branch -r", " weird/123\n  branch-heads/7\n", cwd=chrome_dir),
1817
      Cmd("git show refs/branch-heads/7:DEPS", c_deps % "hash_345",
1818
          cwd=chrome_dir),
1819 1820 1821
      URL("http://omahaproxy.appspot.com/all.json", """[{
        "os": "win",
        "versions": [{
1822 1823
          "version": "2.2.2.2",
          "v8_version": "22.2.2.2",
1824 1825
          "current_reldate": "04/09/15",
          "os": "win",
1826 1827
          "channel": "canary",
          "previous_version": "1.1.1.0"
1828 1829
          }]
        }]"""),
1830 1831 1832 1833 1834 1835
      URL("http://omahaproxy.appspot.com/v8.json?version=1.1.1.0", """{
        "chromium_version": "1.1.1.0",
        "v8_version": "11.1.1.0"
        }"""),
      Cmd("git rev-list -1 11.1.1", "v8_previous_version_hash"),
      Cmd("git rev-list -1 22.2.2.2", "v8_version_hash"),
1836
      Cmd("git checkout -f origin/master", ""),
1837
      Cmd("git branch -D %s" % TEST_CONFIG["BRANCHNAME"], "")
1838 1839
    ])

1840
    args = ["-c", TEST_CONFIG["CHROMIUM"],
1841 1842 1843 1844 1845 1846
            "--json", json_output,
            "--csv", csv_output,
            "--max-releases", "1"]
    Releases(TEST_CONFIG, self).Run(args)

    # Check expected output.
1847 1848
    csv = ("4.2.71,4.2.71,1,5678,\r\n"
           "3.22.3,candidates,345,4567:5677,\r\n"
1849
           "3.21.2,3.21,123,,\r\n"
1850
           "3.3.1.1,3.3,234,,abc12\r\n")
1851 1852
    self.assertEquals(csv, FileToText(csv_output))

1853 1854 1855
    expected_json = {"chrome_releases":{
                                        "canaries": [
                                                     {
1856
                           "chrome_version": "2.2.2.2",
1857 1858
                           "os": "win",
                           "release_date": "04/09/15",
1859 1860 1861 1862
                           "v8_version": "22.2.2.2",
                           "v8_version_hash": "v8_version_hash",
                           "v8_previous_version": "11.1.1.0",
                           "v8_previous_version_hash": "v8_previous_version_hash"
1863 1864
                           }]},
                     "releases":[
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
      {
        "revision": "1",
        "revision_git": "hash_456",
        "master_position": "456",
        "master_hash": "master_456",
        "patches_merged": "",
        "version": "4.2.71",
        "chromium_revision": "5678",
        "branch": "4.2.71",
        "review_link": "",
        "date": "02:15",
        "chromium_branch": "",
        # FIXME(machenbach): Fix revisions link for git.
        "revision_link": "https://code.google.com/p/v8/source/detail?r=1",
      },
1880 1881 1882
      {
        "revision": "345",
        "revision_git": "hash_345",
1883 1884
        "master_position": "",
        "master_hash": "",
1885 1886
        "patches_merged": "",
        "version": "3.22.3",
1887
        "chromium_revision": "4567:5677",
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
        "branch": "candidates",
        "review_link": "",
        "date": "",
        "chromium_branch": "7",
        "revision_link": "https://code.google.com/p/v8/source/detail?r=345",
      },
      {
        "revision": "123",
        "revision_git": "hash_123",
        "patches_merged": "",
1898 1899
        "master_position": "",
        "master_hash": "",
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
        "version": "3.21.2",
        "chromium_revision": "",
        "branch": "3.21",
        "review_link": "",
        "date": "03:15",
        "chromium_branch": "",
        "revision_link": "https://code.google.com/p/v8/source/detail?r=123",
      },
      {
        "revision": "234",
        "revision_git": "hash_234",
1911
        "patches_merged": "abc12",
1912 1913
        "master_position": "",
        "master_hash": "",
1914 1915 1916 1917 1918 1919 1920
        "version": "3.3.1.1",
        "chromium_revision": "",
        "branch": "3.3",
        "review_link": "fake.com",
        "date": "18:15",
        "chromium_branch": "",
        "revision_link": "https://code.google.com/p/v8/source/detail?r=234",
1921 1922
      },],
    }
1923 1924
    self.assertEquals(expected_json, json.loads(FileToText(json_output)))

1925

1926 1927


1928 1929
class SystemTest(unittest.TestCase):
  def testReload(self):
1930 1931
    options = ScriptsBase(
        TEST_CONFIG, DEFAULT_SIDE_EFFECT_HANDLER, {}).MakeOptions([])
1932
    step = MakeStep(step_class=PrepareChangeLog, number=0, state={}, config={},
1933
                    options=options,
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
                    side_effect_handler=DEFAULT_SIDE_EFFECT_HANDLER)
    body = step.Reload(
"""------------------------------------------------------------------------
r17997 | machenbach@chromium.org | 2013-11-22 11:04:04 +0100 (...) | 6 lines

Prepare push to trunk.  Now working on version 3.23.11.

R=danno@chromium.org

Review URL: https://codereview.chromium.org/83173002

------------------------------------------------------------------------""")
    self.assertEquals(
"""Prepare push to trunk.  Now working on version 3.23.11.

R=danno@chromium.org

Committed: https://code.google.com/p/v8/source/detail?r=17997""", body)