2 # Copyright 2014 the V8 project authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 # This script retrieves the history of all V8 branches and
7 # their corresponding Chromium revisions.
9 # Requires a chromium checkout with branch heads:
10 # gclient sync --with_branch_heads
21 from common_includes import *
24 "BRANCHNAME": "retrieve-v8-releases",
25 "PERSISTFILE_BASENAME": "/tmp/v8-releases-tempfile",
28 # Expression for retrieving the bleeding edge revision from a commit message.
29 PUSH_MSG_SVN_RE = re.compile(r".* \(based on bleeding_edge revision r(\d+)\)$")
30 PUSH_MSG_GIT_RE = re.compile(r".* \(based on ([a-fA-F0-9]+)\)$")
32 # Expression for retrieving the merged patches from a merge commit message
33 # (old and new format).
34 MERGE_MESSAGE_RE = re.compile(r"^.*[M|m]erged (.+)(\)| into).*$", re.M)
36 CHERRY_PICK_TITLE_GIT_RE = re.compile(r"^.* \(cherry\-pick\)\.?$")
38 # New git message for cherry-picked CLs. One message per line.
39 MERGE_MESSAGE_GIT_RE = re.compile(r"^Merged ([a-fA-F0-9]+)\.?$")
41 # Expression for retrieving reverted patches from a commit message (old and
43 ROLLBACK_MESSAGE_RE = re.compile(r"^.*[R|r]ollback of (.+)(\)| in).*$", re.M)
45 # New git message for reverted CLs. One message per line.
46 ROLLBACK_MESSAGE_GIT_RE = re.compile(r"^Rollback of ([a-fA-F0-9]+)\.?$")
48 # Expression for retrieving the code review link.
49 REVIEW_LINK_RE = re.compile(r"^Review URL: (.+)$", re.M)
51 # Expression with three versions (historical) for extracting the v8 revision
52 # from the chromium DEPS file.
53 DEPS_RE = re.compile(r"""^\s*(?:["']v8_revision["']: ["']"""
54 """|\(Var\("googlecode_url"\) % "v8"\) \+ "\/trunk@"""
55 """|"http\:\/\/v8\.googlecode\.com\/svn\/trunk@)"""
56 """([^"']+)["'].*$""", re.M)
58 # Expression to pick tag and revision for bleeding edge tags. To be used with
59 # output of 'svn log'.
60 BLEEDING_EDGE_TAGS_RE = re.compile(
61 r"A \/tags\/([^\s]+) \(from \/branches\/bleeding_edge\:(\d+)\)")
64 def SortBranches(branches):
65 """Sort branches with version number names."""
66 return sorted(branches, key=SortingKey, reverse=True)
69 def FilterDuplicatesAndReverse(cr_releases):
70 """Returns the chromium releases in reverse order filtered by v8 revision
73 cr_releases is a list of [cr_rev, v8_hsh] reverse-sorted by cr_rev.
77 for release in reversed(cr_releases):
78 if last == release[1]:
81 result.append(release)
85 def BuildRevisionRanges(cr_releases):
86 """Returns a mapping of v8 revision -> chromium ranges.
87 The ranges are comma-separated, each range has the form R1:R2. The newest
88 entry is the only one of the form R1, as there is no end range.
90 cr_releases is a list of [cr_rev, v8_hsh] reverse-sorted by cr_rev.
91 cr_rev either refers to a chromium commit position or a chromium branch
95 cr_releases = FilterDuplicatesAndReverse(cr_releases)
97 # Visit pairs of cr releases from oldest to newest.
98 for cr_from, cr_to in itertools.izip(
99 cr_releases, itertools.islice(cr_releases, 1, None)):
101 # Assume the chromium revisions are all different.
102 assert cr_from[0] != cr_to[0]
104 ran = "%s:%d" % (cr_from[0], int(cr_to[0]) - 1)
106 # Collect the ranges in lists per revision.
107 range_lists.setdefault(cr_from[1], []).append(ran)
109 # Add the newest revision.
111 range_lists.setdefault(cr_releases[-1][1], []).append(cr_releases[-1][0])
113 # Stringify and comma-separate the range lists.
114 return dict((hsh, ", ".join(ran)) for hsh, ran in range_lists.iteritems())
117 def MatchSafe(match):
119 return match.group(1)
124 class Preparation(Step):
125 MESSAGE = "Preparation."
132 class RetrieveV8Releases(Step):
133 MESSAGE = "Retrieve all V8 releases."
135 def ExceedsMax(self, releases):
136 return (self._options.max_releases > 0
137 and len(releases) > self._options.max_releases)
139 def GetMasterHashFromPush(self, title):
140 return MatchSafe(PUSH_MSG_GIT_RE.match(title))
142 def GetMergedPatches(self, body):
143 patches = MatchSafe(MERGE_MESSAGE_RE.search(body))
145 patches = MatchSafe(ROLLBACK_MESSAGE_RE.search(body))
147 # Indicate reverted patches with a "-".
148 patches = "-%s" % patches
151 def GetMergedPatchesGit(self, body):
153 for line in body.splitlines():
154 patch = MatchSafe(MERGE_MESSAGE_GIT_RE.match(line))
156 patches.append(patch)
157 patch = MatchSafe(ROLLBACK_MESSAGE_GIT_RE.match(line))
159 patches.append("-%s" % patch)
160 return ", ".join(patches)
164 self, git_hash, master_position, master_hash, branch, version,
166 revision = self.GetCommitPositionNumber(git_hash)
168 # The cr commit position number on the branch.
169 "revision": revision,
170 # The git revision on the branch.
171 "revision_git": git_hash,
172 # The cr commit position number on master.
173 "master_position": master_position,
175 "master_hash": master_hash,
178 # The version for displaying in the form 3.26.3 or 3.26.3.12.
180 # The date of the commit.
181 "date": self.GitLog(n=1, format="%ci", git_hash=git_hash),
182 # Merged patches if available in the form 'r1234, r2345'.
183 "patches_merged": patches,
184 # Default for easier output formatting.
185 "chromium_revision": "",
186 # Default for easier output formatting.
187 "chromium_branch": "",
188 # Link to the CL on code review. Candiates pushes are not uploaded,
189 # so this field will be populated below with the recent roll CL link.
190 "review_link": MatchSafe(REVIEW_LINK_RE.search(cl_body)),
191 # Link to the commit message on google code.
192 "revision_link": ("https://code.google.com/p/v8/source/detail?r=%s"
196 def GetRelease(self, git_hash, branch):
197 self.ReadAndPersistVersion()
198 base_version = [self["major"], self["minor"], self["build"]]
199 version = ".".join(base_version)
200 body = self.GitLog(n=1, format="%B", git_hash=git_hash)
203 if self["patch"] != "0":
204 version += ".%s" % self["patch"]
205 if CHERRY_PICK_TITLE_GIT_RE.match(body.splitlines()[0]):
206 patches = self.GetMergedPatchesGit(body)
208 patches = self.GetMergedPatches(body)
210 if SortingKey("4.2.69") <= SortingKey(version):
211 master_hash = self.GetLatestReleaseBase(version=version)
213 # Legacy: Before version 4.2.69, the master revision was determined
215 title = self.GitLog(n=1, format="%s", git_hash=git_hash)
216 master_hash = self.GetMasterHashFromPush(title)
219 master_position = self.GetCommitPositionNumber(master_hash)
220 return self.GetReleaseDict(
221 git_hash, master_position, master_hash, branch, version,
222 patches, body), self["patch"]
224 def GetReleasesFromBranch(self, branch):
225 self.GitReset(self.vc.RemoteBranch(branch))
226 if branch == self.vc.MasterBranch():
227 return self.GetReleasesFromMaster()
231 for git_hash in self.GitLog(format="%H").splitlines():
232 if VERSION_FILE not in self.GitChangedFiles(git_hash):
234 if self.ExceedsMax(releases):
235 break # pragma: no cover
236 if not self.GitCheckoutFileSafe(VERSION_FILE, git_hash):
237 break # pragma: no cover
239 release, patch_level = self.GetRelease(git_hash, branch)
240 releases.append(release)
242 # Follow branches only until their creation point.
243 # TODO(machenbach): This omits patches if the version file wasn't
244 # manipulated correctly. Find a better way to detect the point where
245 # the parent of the branch head leads to the trunk branch.
246 if branch != self.vc.CandidateBranch() and patch_level == "0":
249 # Allow Ctrl-C interrupt.
250 except (KeyboardInterrupt, SystemExit): # pragma: no cover
253 # Clean up checked-out version file.
254 self.GitCheckoutFileSafe(VERSION_FILE, "HEAD")
257 def GetReleaseFromRevision(self, revision):
260 if (VERSION_FILE not in self.GitChangedFiles(revision) or
261 not self.GitCheckoutFileSafe(VERSION_FILE, revision)):
262 print "Skipping revision %s" % revision
263 return [] # pragma: no cover
267 self.Git("branch -r --contains %s" % revision).strip().splitlines(),
271 if b.startswith("origin/"):
272 branch = b.split("origin/")[1]
274 if b.startswith("branch-heads/"):
275 branch = b.split("branch-heads/")[1]
278 print "Could not determine branch for %s" % revision
280 release, _ = self.GetRelease(revision, branch)
281 releases.append(release)
283 # Allow Ctrl-C interrupt.
284 except (KeyboardInterrupt, SystemExit): # pragma: no cover
287 # Clean up checked-out version file.
288 self.GitCheckoutFileSafe(VERSION_FILE, "HEAD")
293 self.GitCreateBranch(self._config["BRANCHNAME"])
295 if self._options.branch == 'recent':
296 # List every release from the last 7 days.
297 revisions = self.GetRecentReleases(max_age=7 * DAY_IN_SECONDS)
298 for revision in revisions:
299 releases += self.GetReleaseFromRevision(revision)
300 elif self._options.branch == 'all': # pragma: no cover
301 # Retrieve the full release history.
302 for branch in self.vc.GetBranches():
303 releases += self.GetReleasesFromBranch(branch)
304 releases += self.GetReleasesFromBranch(self.vc.CandidateBranch())
305 releases += self.GetReleasesFromBranch(self.vc.MasterBranch())
306 else: # pragma: no cover
307 # Retrieve history for a specified branch.
308 assert self._options.branch in (self.vc.GetBranches() +
309 [self.vc.CandidateBranch(), self.vc.MasterBranch()])
310 releases += self.GetReleasesFromBranch(self._options.branch)
312 self["releases"] = sorted(releases,
313 key=lambda r: SortingKey(r["version"]),
317 class SwitchChromium(Step):
318 MESSAGE = "Switch to Chromium checkout."
321 cwd = self._options.chromium
322 # Check for a clean workdir.
323 if not self.GitIsWorkdirClean(cwd=cwd): # pragma: no cover
324 self.Die("Workspace is not clean. Please commit or undo your changes.")
325 # Assert that the DEPS file is there.
326 if not os.path.exists(os.path.join(cwd, "DEPS")): # pragma: no cover
327 self.Die("DEPS file not present.")
330 class UpdateChromiumCheckout(Step):
331 MESSAGE = "Update the checkout and create a new branch."
334 cwd = self._options.chromium
335 self.GitCheckout("master", cwd=cwd)
336 self.GitPull(cwd=cwd)
337 self.DeleteBranch(self.Config("BRANCHNAME"), cwd=cwd)
338 self.GitCreateBranch(self.Config("BRANCHNAME"), cwd=cwd)
341 def ConvertToCommitNumber(step, revision):
342 # Simple check for git hashes.
343 if revision.isdigit() and len(revision) < 8:
345 return step.GetCommitPositionNumber(
346 revision, cwd=os.path.join(step._options.chromium, "v8"))
349 class RetrieveChromiumV8Releases(Step):
350 MESSAGE = "Retrieve V8 releases from Chromium DEPS."
353 cwd = self._options.chromium
355 # Update v8 checkout in chromium.
356 self.GitFetchOrigin(cwd=os.path.join(cwd, "v8"))
358 # All v8 revisions we are interested in.
359 releases_dict = dict((r["revision_git"], r) for r in self["releases"])
363 for git_hash in self.GitLog(
364 format="%H", grep="V8", cwd=cwd).splitlines():
365 if "DEPS" not in self.GitChangedFiles(git_hash, cwd=cwd):
367 if not self.GitCheckoutFileSafe("DEPS", git_hash, cwd=cwd):
368 break # pragma: no cover
369 deps = FileToText(os.path.join(cwd, "DEPS"))
370 match = DEPS_RE.search(deps)
372 cr_rev = self.GetCommitPositionNumber(git_hash, cwd=cwd)
374 v8_hsh = match.group(1)
375 cr_releases.append([cr_rev, v8_hsh])
377 # Stop as soon as we find a v8 revision that we didn't fetch in the
378 # v8-revision-retrieval part above (i.e. a revision that's too old).
379 if v8_hsh not in releases_dict:
380 break # pragma: no cover
382 # Allow Ctrl-C interrupt.
383 except (KeyboardInterrupt, SystemExit): # pragma: no cover
387 self.GitCheckoutFileSafe("DEPS", "HEAD", cwd=cwd)
389 # Add the chromium ranges to the v8 candidates and master releases.
390 all_ranges = BuildRevisionRanges(cr_releases)
392 for hsh, ranges in all_ranges.iteritems():
393 releases_dict.get(hsh, {})["chromium_revision"] = ranges
396 # TODO(machenbach): Unify common code with method above.
397 class RietrieveChromiumBranches(Step):
398 MESSAGE = "Retrieve Chromium branch information."
401 cwd = self._options.chromium
403 # All v8 revisions we are interested in.
404 releases_dict = dict((r["revision_git"], r) for r in self["releases"])
406 # Filter out irrelevant branches.
407 branches = filter(lambda r: re.match(r"branch-heads/\d+", r),
408 self.GitRemotes(cwd=cwd))
410 # Transform into pure branch numbers.
411 branches = map(lambda r: int(re.match(r"branch-heads/(\d+)", r).group(1)),
414 branches = sorted(branches, reverse=True)
418 for branch in branches:
419 if not self.GitCheckoutFileSafe("DEPS",
420 "branch-heads/%d" % branch,
422 break # pragma: no cover
423 deps = FileToText(os.path.join(cwd, "DEPS"))
424 match = DEPS_RE.search(deps)
426 v8_hsh = match.group(1)
427 cr_branches.append([str(branch), v8_hsh])
429 # Stop as soon as we find a v8 revision that we didn't fetch in the
430 # v8-revision-retrieval part above (i.e. a revision that's too old).
431 if v8_hsh not in releases_dict:
432 break # pragma: no cover
434 # Allow Ctrl-C interrupt.
435 except (KeyboardInterrupt, SystemExit): # pragma: no cover
439 self.GitCheckoutFileSafe("DEPS", "HEAD", cwd=cwd)
441 # Add the chromium branches to the v8 candidate releases.
442 all_ranges = BuildRevisionRanges(cr_branches)
443 for revision, ranges in all_ranges.iteritems():
444 releases_dict.get(revision, {})["chromium_branch"] = ranges
448 MESSAGE = "Clean up."
451 self.GitCheckout("master", cwd=self._options.chromium)
452 self.GitDeleteBranch(self.Config("BRANCHNAME"), cwd=self._options.chromium)
456 class WriteOutput(Step):
457 MESSAGE = "Print output."
460 if self._options.csv:
461 with open(self._options.csv, "w") as f:
462 writer = csv.DictWriter(f,
463 ["version", "branch", "revision",
464 "chromium_revision", "patches_merged"],
466 extrasaction="ignore")
467 for release in self["releases"]:
468 writer.writerow(release)
469 if self._options.json:
470 with open(self._options.json, "w") as f:
471 f.write(json.dumps(self["releases"]))
472 if not self._options.csv and not self._options.json:
473 print self["releases"] # pragma: no cover
476 class Releases(ScriptsBase):
477 def _PrepareOptions(self, parser):
478 parser.add_argument("-b", "--branch", default="recent",
479 help=("The branch to analyze. If 'all' is specified, "
480 "analyze all branches. If 'recent' (default) "
481 "is specified, track beta, stable and "
483 parser.add_argument("-c", "--chromium",
484 help=("The path to your Chromium src/ "
485 "directory to automate the V8 roll."))
486 parser.add_argument("--csv", help="Path to a CSV file for export.")
487 parser.add_argument("-m", "--max-releases", type=int, default=0,
488 help="The maximum number of releases to track.")
489 parser.add_argument("--json", help="Path to a JSON file for export.")
491 def _ProcessOptions(self, options): # pragma: no cover
492 options.force_readline_defaults = True
497 "BRANCHNAME": "retrieve-v8-releases",
498 "PERSISTFILE_BASENAME": "/tmp/v8-releases-tempfile",
506 UpdateChromiumCheckout,
507 RetrieveChromiumV8Releases,
508 RietrieveChromiumBranches,
514 if __name__ == "__main__": # pragma: no cover
515 sys.exit(Releases().Run())