44c10d9b304367f6053a48ff9b2118afbe5701e2
[platform/upstream/nodejs.git] / deps / v8 / tools / release / create_release.py
1 #!/usr/bin/env python
2 # Copyright 2015 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 import argparse
7 import os
8 import sys
9 import tempfile
10 import urllib2
11
12 from common_includes import *
13
14
15 class Preparation(Step):
16   MESSAGE = "Preparation."
17
18   def RunStep(self):
19     fetchspecs = [
20       "+refs/heads/*:refs/heads/*",
21       "+refs/pending/*:refs/pending/*",
22       "+refs/pending-tags/*:refs/pending-tags/*",
23     ]
24     self.Git("fetch origin %s" % " ".join(fetchspecs))
25     self.GitCheckout("origin/master")
26     self.DeleteBranch("work-branch")
27
28
29 class PrepareBranchRevision(Step):
30   MESSAGE = "Check from which revision to branch off."
31
32   def RunStep(self):
33     if self._options.revision:
34       self["push_hash"], tree_object = self.GitLog(
35           n=1, format="\"%H %T\"", git_hash=self._options.revision).split(" ")
36     else:
37       self["push_hash"], tree_object = self.GitLog(
38           n=1, format="\"%H %T\"", branch="origin/master").split(" ")
39     print "Release revision %s" % self["push_hash"]
40     assert self["push_hash"]
41
42     pending_tuples = self.GitLog(
43         n=200, format="\"%H %T\"", branch="refs/pending/heads/master")
44     for hsh, tree in map(lambda s: s.split(" "), pending_tuples.splitlines()):
45       if tree == tree_object:
46         self["pending_hash"] = hsh
47         break
48     print "Pending release revision %s" % self["pending_hash"]
49     assert self["pending_hash"]
50
51
52 class IncrementVersion(Step):
53   MESSAGE = "Increment version number."
54
55   def RunStep(self):
56     latest_version = self.GetLatestVersion()
57
58     # The version file on master can be used to bump up major/minor at
59     # branch time.
60     self.GitCheckoutFile(VERSION_FILE, self.vc.RemoteMasterBranch())
61     self.ReadAndPersistVersion("master_")
62     master_version = self.ArrayToVersion("master_")
63
64     # Use the highest version from master or from tags to determine the new
65     # version.
66     authoritative_version = sorted(
67         [master_version, latest_version], key=SortingKey)[1]
68     self.StoreVersion(authoritative_version, "authoritative_")
69
70     # Variables prefixed with 'new_' contain the new version numbers for the
71     # ongoing candidates push.
72     self["new_major"] = self["authoritative_major"]
73     self["new_minor"] = self["authoritative_minor"]
74     self["new_build"] = str(int(self["authoritative_build"]) + 1)
75
76     # Make sure patch level is 0 in a new push.
77     self["new_patch"] = "0"
78
79     # The new version is not a candidate.
80     self["new_candidate"] = "0"
81
82     self["version"] = "%s.%s.%s" % (self["new_major"],
83                                     self["new_minor"],
84                                     self["new_build"])
85
86     print ("Incremented version to %s" % self["version"])
87
88
89 class DetectLastRelease(Step):
90   MESSAGE = "Detect commit ID of last release base."
91
92   def RunStep(self):
93     self["last_push_master"] = self.GetLatestReleaseBase()
94
95
96 class PrepareChangeLog(Step):
97   MESSAGE = "Prepare raw ChangeLog entry."
98
99   def Reload(self, body):
100     """Attempts to reload the commit message from rietveld in order to allow
101     late changes to the LOG flag. Note: This is brittle to future changes of
102     the web page name or structure.
103     """
104     match = re.search(r"^Review URL: https://codereview\.chromium\.org/(\d+)$",
105                       body, flags=re.M)
106     if match:
107       cl_url = ("https://codereview.chromium.org/%s/description"
108                 % match.group(1))
109       try:
110         # Fetch from Rietveld but only retry once with one second delay since
111         # there might be many revisions.
112         body = self.ReadURL(cl_url, wait_plan=[1])
113       except urllib2.URLError:  # pragma: no cover
114         pass
115     return body
116
117   def RunStep(self):
118     self["date"] = self.GetDate()
119     output = "%s: Version %s\n\n" % (self["date"], self["version"])
120     TextToFile(output, self.Config("CHANGELOG_ENTRY_FILE"))
121     commits = self.GitLog(format="%H",
122         git_hash="%s..%s" % (self["last_push_master"],
123                              self["push_hash"]))
124
125     # Cache raw commit messages.
126     commit_messages = [
127       [
128         self.GitLog(n=1, format="%s", git_hash=commit),
129         self.Reload(self.GitLog(n=1, format="%B", git_hash=commit)),
130         self.GitLog(n=1, format="%an", git_hash=commit),
131       ] for commit in commits.splitlines()
132     ]
133
134     # Auto-format commit messages.
135     body = MakeChangeLogBody(commit_messages, auto_format=True)
136     AppendToFile(body, self.Config("CHANGELOG_ENTRY_FILE"))
137
138     msg = ("        Performance and stability improvements on all platforms."
139            "\n#\n# The change log above is auto-generated. Please review if "
140            "all relevant\n# commit messages from the list below are included."
141            "\n# All lines starting with # will be stripped.\n#\n")
142     AppendToFile(msg, self.Config("CHANGELOG_ENTRY_FILE"))
143
144     # Include unformatted commit messages as a reference in a comment.
145     comment_body = MakeComment(MakeChangeLogBody(commit_messages))
146     AppendToFile(comment_body, self.Config("CHANGELOG_ENTRY_FILE"))
147
148
149 class EditChangeLog(Step):
150   MESSAGE = "Edit ChangeLog entry."
151
152   def RunStep(self):
153     print ("Please press <Return> to have your EDITOR open the ChangeLog "
154            "entry, then edit its contents to your liking. When you're done, "
155            "save the file and exit your EDITOR. ")
156     self.ReadLine(default="")
157     self.Editor(self.Config("CHANGELOG_ENTRY_FILE"))
158
159     # Strip comments and reformat with correct indentation.
160     changelog_entry = FileToText(self.Config("CHANGELOG_ENTRY_FILE")).rstrip()
161     changelog_entry = StripComments(changelog_entry)
162     changelog_entry = "\n".join(map(Fill80, changelog_entry.splitlines()))
163     changelog_entry = changelog_entry.lstrip()
164
165     if changelog_entry == "":  # pragma: no cover
166       self.Die("Empty ChangeLog entry.")
167
168     # Safe new change log for adding it later to the candidates patch.
169     TextToFile(changelog_entry, self.Config("CHANGELOG_ENTRY_FILE"))
170
171
172 class MakeBranch(Step):
173   MESSAGE = "Create the branch."
174
175   def RunStep(self):
176     self.Git("reset --hard origin/master")
177     self.Git("checkout -b work-branch %s" % self["pending_hash"])
178     self.GitCheckoutFile(CHANGELOG_FILE, self["latest_version"])
179     self.GitCheckoutFile(VERSION_FILE, self["latest_version"])
180
181
182 class AddChangeLog(Step):
183   MESSAGE = "Add ChangeLog changes to release branch."
184
185   def RunStep(self):
186     changelog_entry = FileToText(self.Config("CHANGELOG_ENTRY_FILE"))
187     old_change_log = FileToText(os.path.join(self.default_cwd, CHANGELOG_FILE))
188     new_change_log = "%s\n\n\n%s" % (changelog_entry, old_change_log)
189     TextToFile(new_change_log, os.path.join(self.default_cwd, CHANGELOG_FILE))
190
191
192 class SetVersion(Step):
193   MESSAGE = "Set correct version for candidates."
194
195   def RunStep(self):
196     self.SetVersion(os.path.join(self.default_cwd, VERSION_FILE), "new_")
197
198
199 class CommitBranch(Step):
200   MESSAGE = "Commit version and changelog to new branch."
201
202   def RunStep(self):
203     # Convert the ChangeLog entry to commit message format.
204     text = FileToText(self.Config("CHANGELOG_ENTRY_FILE"))
205
206     # Remove date and trailing white space.
207     text = re.sub(r"^%s: " % self["date"], "", text.rstrip())
208
209     # Remove indentation and merge paragraphs into single long lines, keeping
210     # empty lines between them.
211     def SplitMapJoin(split_text, fun, join_text):
212       return lambda text: join_text.join(map(fun, text.split(split_text)))
213     text = SplitMapJoin(
214         "\n\n", SplitMapJoin("\n", str.strip, " "), "\n\n")(text)
215
216     if not text:  # pragma: no cover
217       self.Die("Commit message editing failed.")
218     self["commit_title"] = text.splitlines()[0]
219     TextToFile(text, self.Config("COMMITMSG_FILE"))
220
221     self.GitCommit(file_name = self.Config("COMMITMSG_FILE"))
222     os.remove(self.Config("COMMITMSG_FILE"))
223     os.remove(self.Config("CHANGELOG_ENTRY_FILE"))
224
225
226 class PushBranch(Step):
227   MESSAGE = "Push changes."
228
229   def RunStep(self):
230     pushspecs = [
231       "refs/heads/work-branch:refs/pending/heads/%s" % self["version"],
232       "%s:refs/pending-tags/heads/%s" %
233       (self["pending_hash"], self["version"]),
234       "%s:refs/heads/%s" % (self["push_hash"], self["version"]),
235     ]
236     cmd = "push origin %s" % " ".join(pushspecs)
237     if self._options.dry_run:
238       print "Dry run. Command:\ngit %s" % cmd
239     else:
240       self.Git(cmd)
241
242
243 class TagRevision(Step):
244   MESSAGE = "Tag the new revision."
245
246   def RunStep(self):
247     if self._options.dry_run:
248       print ("Dry run. Tagging \"%s\" with %s" %
249              (self["commit_title"], self["version"]))
250     else:
251       self.vc.Tag(self["version"],
252                   "origin/%s" % self["version"],
253                   self["commit_title"])
254
255
256 class CleanUp(Step):
257   MESSAGE = "Done!"
258
259   def RunStep(self):
260     print("Congratulations, you have successfully created version %s."
261           % self["version"])
262
263     self.GitCheckout("origin/master")
264     self.DeleteBranch("work-branch")
265     self.Git("gc")
266
267
268 class CreateRelease(ScriptsBase):
269   def _PrepareOptions(self, parser):
270     group = parser.add_mutually_exclusive_group()
271     group.add_argument("-f", "--force",
272                       help="Don't prompt the user.",
273                       default=True, action="store_true")
274     group.add_argument("-m", "--manual",
275                       help="Prompt the user at every important step.",
276                       default=False, action="store_true")
277     parser.add_argument("-R", "--revision",
278                         help="The git commit ID to push (defaults to HEAD).")
279
280   def _ProcessOptions(self, options):  # pragma: no cover
281     if not options.author or not options.reviewer:
282       print "Reviewer (-r) and author (-a) are required."
283       return False
284     return True
285
286   def _Config(self):
287     return {
288       "PERSISTFILE_BASENAME": "/tmp/create-releases-tempfile",
289       "CHANGELOG_ENTRY_FILE":
290           "/tmp/v8-create-releases-tempfile-changelog-entry",
291       "COMMITMSG_FILE": "/tmp/v8-create-releases-tempfile-commitmsg",
292     }
293
294   def _Steps(self):
295     return [
296       Preparation,
297       PrepareBranchRevision,
298       IncrementVersion,
299       DetectLastRelease,
300       PrepareChangeLog,
301       EditChangeLog,
302       MakeBranch,
303       AddChangeLog,
304       SetVersion,
305       CommitBranch,
306       PushBranch,
307       TagRevision,
308       CleanUp,
309     ]
310
311
312 if __name__ == "__main__":  # pragma: no cover
313   sys.exit(CreateRelease().Run())