• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
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.
5
6# This script retrieves the history of all V8 branches and trunk revisions and
7# their corresponding Chromium revisions.
8
9# Requires a chromium checkout with branch heads:
10# gclient sync --with_branch_heads
11# gclient fetch
12
13import argparse
14import csv
15import itertools
16import json
17import os
18import re
19import sys
20
21from common_includes import *
22
23DEPS_FILE = "DEPS_FILE"
24CHROMIUM = "CHROMIUM"
25
26CONFIG = {
27  BRANCHNAME: "retrieve-v8-releases",
28  PERSISTFILE_BASENAME: "/tmp/v8-releases-tempfile",
29  DOT_GIT_LOCATION: ".git",
30  VERSION_FILE: "src/version.cc",
31  DEPS_FILE: "DEPS",
32}
33
34# Expression for retrieving the bleeding edge revision from a commit message.
35PUSH_MESSAGE_RE = re.compile(r".* \(based on bleeding_edge revision r(\d+)\)$")
36
37# Expression for retrieving the merged patches from a merge commit message
38# (old and new format).
39MERGE_MESSAGE_RE = re.compile(r"^.*[M|m]erged (.+)(\)| into).*$", re.M)
40
41# Expression for retrieving reverted patches from a commit message (old and
42# new format).
43ROLLBACK_MESSAGE_RE = re.compile(r"^.*[R|r]ollback of (.+)(\)| in).*$", re.M)
44
45# Expression for retrieving the code review link.
46REVIEW_LINK_RE = re.compile(r"^Review URL: (.+)$", re.M)
47
48# Expression with three versions (historical) for extracting the v8 revision
49# from the chromium DEPS file.
50DEPS_RE = re.compile(r'^\s*(?:"v8_revision": "'
51                      '|\(Var\("googlecode_url"\) % "v8"\) \+ "\/trunk@'
52                      '|"http\:\/\/v8\.googlecode\.com\/svn\/trunk@)'
53                      '([0-9]+)".*$', re.M)
54
55
56def SortingKey(version):
57  """Key for sorting version number strings: '3.11' > '3.2.1.1'"""
58  version_keys = map(int, version.split("."))
59  # Fill up to full version numbers to normalize comparison.
60  while len(version_keys) < 4:
61    version_keys.append(0)
62  # Fill digits.
63  return ".".join(map("{0:03d}".format, version_keys))
64
65
66def SortBranches(branches):
67  """Sort branches with version number names."""
68  return sorted(branches, key=SortingKey, reverse=True)
69
70
71def FilterDuplicatesAndReverse(cr_releases):
72  """Returns the chromium releases in reverse order filtered by v8 revision
73  duplicates.
74
75  cr_releases is a list of [cr_rev, v8_rev] reverse-sorted by cr_rev.
76  """
77  last = ""
78  result = []
79  for release in reversed(cr_releases):
80    if last == release[1]:
81      continue
82    last = release[1]
83    result.append(release)
84  return result
85
86
87def BuildRevisionRanges(cr_releases):
88  """Returns a mapping of v8 revision -> chromium ranges.
89  The ranges are comma-separated, each range has the form R1:R2. The newest
90  entry is the only one of the form R1, as there is no end range.
91
92  cr_releases is a list of [cr_rev, v8_rev] reverse-sorted by cr_rev.
93  cr_rev either refers to a chromium svn revision or a chromium branch number.
94  """
95  range_lists = {}
96  cr_releases = FilterDuplicatesAndReverse(cr_releases)
97
98  # Visit pairs of cr releases from oldest to newest.
99  for cr_from, cr_to in itertools.izip(
100      cr_releases, itertools.islice(cr_releases, 1, None)):
101
102    # Assume the chromium revisions are all different.
103    assert cr_from[0] != cr_to[0]
104
105    # TODO(machenbach): Subtraction is not git friendly.
106    ran = "%s:%d" % (cr_from[0], int(cr_to[0]) - 1)
107
108    # Collect the ranges in lists per revision.
109    range_lists.setdefault(cr_from[1], []).append(ran)
110
111  # Add the newest revision.
112  if cr_releases:
113    range_lists.setdefault(cr_releases[-1][1], []).append(cr_releases[-1][0])
114
115  # Stringify and comma-separate the range lists.
116  return dict((rev, ", ".join(ran)) for rev, ran in range_lists.iteritems())
117
118
119def MatchSafe(match):
120  if match:
121    return match.group(1)
122  else:
123    return ""
124
125
126class Preparation(Step):
127  MESSAGE = "Preparation."
128
129  def RunStep(self):
130    self.CommonPrepare()
131    self.PrepareBranch()
132
133
134class RetrieveV8Releases(Step):
135  MESSAGE = "Retrieve all V8 releases."
136
137  def ExceedsMax(self, releases):
138    return (self._options.max_releases > 0
139            and len(releases) > self._options.max_releases)
140
141  def GetBleedingEdgeFromPush(self, title):
142    return MatchSafe(PUSH_MESSAGE_RE.match(title))
143
144  def GetMergedPatches(self, body):
145    patches = MatchSafe(MERGE_MESSAGE_RE.search(body))
146    if not patches:
147      patches = MatchSafe(ROLLBACK_MESSAGE_RE.search(body))
148      if patches:
149        # Indicate reverted patches with a "-".
150        patches = "-%s" % patches
151    return patches
152
153  def GetRelease(self, git_hash, branch):
154    self.ReadAndPersistVersion()
155    base_version = [self["major"], self["minor"], self["build"]]
156    version = ".".join(base_version)
157    body = self.GitLog(n=1, format="%B", git_hash=git_hash)
158
159    patches = ""
160    if self["patch"] != "0":
161      version += ".%s" % self["patch"]
162      patches = self.GetMergedPatches(body)
163
164    title = self.GitLog(n=1, format="%s", git_hash=git_hash)
165    revision = self.GitSVNFindSVNRev(git_hash)
166    return {
167      # The SVN revision on the branch.
168      "revision": revision,
169      # The SVN revision on bleeding edge (only for newer trunk pushes).
170      "bleeding_edge": self.GetBleedingEdgeFromPush(title),
171      # The branch name.
172      "branch": branch,
173      # The version for displaying in the form 3.26.3 or 3.26.3.12.
174      "version": version,
175      # The date of the commit.
176      "date": self.GitLog(n=1, format="%ci", git_hash=git_hash),
177      # Merged patches if available in the form 'r1234, r2345'.
178      "patches_merged": patches,
179      # Default for easier output formatting.
180      "chromium_revision": "",
181      # Default for easier output formatting.
182      "chromium_branch": "",
183      # Link to the CL on code review. Trunk pushes are not uploaded, so this
184      # field will be populated below with the recent roll CL link.
185      "review_link": MatchSafe(REVIEW_LINK_RE.search(body)),
186      # Link to the commit message on google code.
187      "revision_link": ("https://code.google.com/p/v8/source/detail?r=%s"
188                        % revision),
189    }, self["patch"]
190
191  def GetReleasesFromBranch(self, branch):
192    self.GitReset("svn/%s" % branch)
193    releases = []
194    try:
195      for git_hash in self.GitLog(format="%H").splitlines():
196        if self._config[VERSION_FILE] not in self.GitChangedFiles(git_hash):
197          continue
198        if self.ExceedsMax(releases):
199          break  # pragma: no cover
200        if not self.GitCheckoutFileSafe(self._config[VERSION_FILE], git_hash):
201          break  # pragma: no cover
202
203        release, patch_level = self.GetRelease(git_hash, branch)
204        releases.append(release)
205
206        # Follow branches only until their creation point.
207        # TODO(machenbach): This omits patches if the version file wasn't
208        # manipulated correctly. Find a better way to detect the point where
209        # the parent of the branch head leads to the trunk branch.
210        if branch != "trunk" and patch_level == "0":
211          break
212
213    # Allow Ctrl-C interrupt.
214    except (KeyboardInterrupt, SystemExit):  # pragma: no cover
215      pass
216
217    # Clean up checked-out version file.
218    self.GitCheckoutFileSafe(self._config[VERSION_FILE], "HEAD")
219    return releases
220
221  def RunStep(self):
222    self.GitCreateBranch(self._config[BRANCHNAME])
223    # Get relevant remote branches, e.g. "svn/3.25".
224    branches = filter(lambda s: re.match(r"^svn/\d+\.\d+$", s),
225                      self.GitRemotes())
226    # Remove 'svn/' prefix.
227    branches = map(lambda s: s[4:], branches)
228
229    releases = []
230    if self._options.branch == 'recent':
231      # Get only recent development on trunk, beta and stable.
232      if self._options.max_releases == 0:  # pragma: no cover
233        self._options.max_releases = 10
234      beta, stable = SortBranches(branches)[0:2]
235      releases += self.GetReleasesFromBranch(stable)
236      releases += self.GetReleasesFromBranch(beta)
237      releases += self.GetReleasesFromBranch("trunk")
238    elif self._options.branch == 'all':  # pragma: no cover
239      # Retrieve the full release history.
240      for branch in branches:
241        releases += self.GetReleasesFromBranch(branch)
242      releases += self.GetReleasesFromBranch("trunk")
243    else:  # pragma: no cover
244      # Retrieve history for a specified branch.
245      assert self._options.branch in branches + ["trunk"]
246      releases += self.GetReleasesFromBranch(self._options.branch)
247
248    self["releases"] = sorted(releases,
249                              key=lambda r: SortingKey(r["version"]),
250                              reverse=True)
251
252
253# TODO(machenbach): Parts of the Chromium setup are c/p from the chromium_roll
254# script -> unify.
255class CheckChromium(Step):
256  MESSAGE = "Check the chromium checkout."
257
258  def Run(self):
259    self["chrome_path"] = self._options.chromium
260
261
262class SwitchChromium(Step):
263  MESSAGE = "Switch to Chromium checkout."
264  REQUIRES = "chrome_path"
265
266  def RunStep(self):
267    self["v8_path"] = os.getcwd()
268    os.chdir(self["chrome_path"])
269    # Check for a clean workdir.
270    if not self.GitIsWorkdirClean():  # pragma: no cover
271      self.Die("Workspace is not clean. Please commit or undo your changes.")
272    # Assert that the DEPS file is there.
273    if not os.path.exists(self.Config(DEPS_FILE)):  # pragma: no cover
274      self.Die("DEPS file not present.")
275
276
277class UpdateChromiumCheckout(Step):
278  MESSAGE = "Update the checkout and create a new branch."
279  REQUIRES = "chrome_path"
280
281  def RunStep(self):
282    os.chdir(self["chrome_path"])
283    self.GitCheckout("master")
284    self.GitPull()
285    self.GitCreateBranch(self.Config(BRANCHNAME))
286
287
288class RetrieveChromiumV8Releases(Step):
289  MESSAGE = "Retrieve V8 releases from Chromium DEPS."
290  REQUIRES = "chrome_path"
291
292  def RunStep(self):
293    os.chdir(self["chrome_path"])
294
295    trunk_releases = filter(lambda r: r["branch"] == "trunk", self["releases"])
296    if not trunk_releases:  # pragma: no cover
297      print "No trunk releases detected. Skipping chromium history."
298      return True
299
300    oldest_v8_rev = int(trunk_releases[-1]["revision"])
301
302    cr_releases = []
303    try:
304      for git_hash in self.GitLog(format="%H", grep="V8").splitlines():
305        if self._config[DEPS_FILE] not in self.GitChangedFiles(git_hash):
306          continue
307        if not self.GitCheckoutFileSafe(self._config[DEPS_FILE], git_hash):
308          break  # pragma: no cover
309        deps = FileToText(self.Config(DEPS_FILE))
310        match = DEPS_RE.search(deps)
311        if match:
312          svn_rev = self.GitSVNFindSVNRev(git_hash)
313          v8_rev = match.group(1)
314          cr_releases.append([svn_rev, v8_rev])
315
316          # Stop after reaching beyond the last v8 revision we want to update.
317          # We need a small buffer for possible revert/reland frenzies.
318          # TODO(machenbach): Subtraction is not git friendly.
319          if int(v8_rev) < oldest_v8_rev - 100:
320            break  # pragma: no cover
321
322    # Allow Ctrl-C interrupt.
323    except (KeyboardInterrupt, SystemExit):  # pragma: no cover
324      pass
325
326    # Clean up.
327    self.GitCheckoutFileSafe(self._config[DEPS_FILE], "HEAD")
328
329    # Add the chromium ranges to the v8 trunk releases.
330    all_ranges = BuildRevisionRanges(cr_releases)
331    trunk_dict = dict((r["revision"], r) for r in trunk_releases)
332    for revision, ranges in all_ranges.iteritems():
333      trunk_dict.get(revision, {})["chromium_revision"] = ranges
334
335
336# TODO(machenbach): Unify common code with method above.
337class RietrieveChromiumBranches(Step):
338  MESSAGE = "Retrieve Chromium branch information."
339  REQUIRES = "chrome_path"
340
341  def RunStep(self):
342    os.chdir(self["chrome_path"])
343
344    trunk_releases = filter(lambda r: r["branch"] == "trunk", self["releases"])
345    if not trunk_releases:  # pragma: no cover
346      print "No trunk releases detected. Skipping chromium history."
347      return True
348
349    oldest_v8_rev = int(trunk_releases[-1]["revision"])
350
351    # Filter out irrelevant branches.
352    branches = filter(lambda r: re.match(r"branch-heads/\d+", r),
353                      self.GitRemotes())
354
355    # Transform into pure branch numbers.
356    branches = map(lambda r: int(re.match(r"branch-heads/(\d+)", r).group(1)),
357                   branches)
358
359    branches = sorted(branches, reverse=True)
360
361    cr_branches = []
362    try:
363      for branch in branches:
364        if not self.GitCheckoutFileSafe(self._config[DEPS_FILE],
365                                        "branch-heads/%d" % branch):
366          break  # pragma: no cover
367        deps = FileToText(self.Config(DEPS_FILE))
368        match = DEPS_RE.search(deps)
369        if match:
370          v8_rev = match.group(1)
371          cr_branches.append([str(branch), v8_rev])
372
373          # Stop after reaching beyond the last v8 revision we want to update.
374          # We need a small buffer for possible revert/reland frenzies.
375          # TODO(machenbach): Subtraction is not git friendly.
376          if int(v8_rev) < oldest_v8_rev - 100:
377            break  # pragma: no cover
378
379    # Allow Ctrl-C interrupt.
380    except (KeyboardInterrupt, SystemExit):  # pragma: no cover
381      pass
382
383    # Clean up.
384    self.GitCheckoutFileSafe(self._config[DEPS_FILE], "HEAD")
385
386    # Add the chromium branches to the v8 trunk releases.
387    all_ranges = BuildRevisionRanges(cr_branches)
388    trunk_dict = dict((r["revision"], r) for r in trunk_releases)
389    for revision, ranges in all_ranges.iteritems():
390      trunk_dict.get(revision, {})["chromium_branch"] = ranges
391
392
393class SwitchV8(Step):
394  MESSAGE = "Returning to V8 checkout."
395  REQUIRES = "chrome_path"
396
397  def RunStep(self):
398    self.GitCheckout("master")
399    self.GitDeleteBranch(self.Config(BRANCHNAME))
400    os.chdir(self["v8_path"])
401
402
403class CleanUp(Step):
404  MESSAGE = "Clean up."
405
406  def RunStep(self):
407    self.CommonCleanup()
408
409
410class WriteOutput(Step):
411  MESSAGE = "Print output."
412
413  def Run(self):
414    if self._options.csv:
415      with open(self._options.csv, "w") as f:
416        writer = csv.DictWriter(f,
417                                ["version", "branch", "revision",
418                                 "chromium_revision", "patches_merged"],
419                                restval="",
420                                extrasaction="ignore")
421        for release in self["releases"]:
422          writer.writerow(release)
423    if self._options.json:
424      with open(self._options.json, "w") as f:
425        f.write(json.dumps(self["releases"]))
426    if not self._options.csv and not self._options.json:
427      print self["releases"]  # pragma: no cover
428
429
430class Releases(ScriptsBase):
431  def _PrepareOptions(self, parser):
432    parser.add_argument("-b", "--branch", default="recent",
433                        help=("The branch to analyze. If 'all' is specified, "
434                              "analyze all branches. If 'recent' (default) "
435                              "is specified, track beta, stable and trunk."))
436    parser.add_argument("-c", "--chromium",
437                        help=("The path to your Chromium src/ "
438                              "directory to automate the V8 roll."))
439    parser.add_argument("--csv", help="Path to a CSV file for export.")
440    parser.add_argument("-m", "--max-releases", type=int, default=0,
441                        help="The maximum number of releases to track.")
442    parser.add_argument("--json", help="Path to a JSON file for export.")
443
444  def _ProcessOptions(self, options):  # pragma: no cover
445    return True
446
447  def _Steps(self):
448    return [
449      Preparation,
450      RetrieveV8Releases,
451      CheckChromium,
452      SwitchChromium,
453      UpdateChromiumCheckout,
454      RetrieveChromiumV8Releases,
455      RietrieveChromiumBranches,
456      SwitchV8,
457      CleanUp,
458      WriteOutput,
459    ]
460
461
462if __name__ == "__main__":  # pragma: no cover
463  sys.exit(Releases(CONFIG).Run())
464