2 # Copyright 2014 the V8 project authors. All rights reserved.
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
7 # * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 # * Redistributions in binary form must reproduce the above
10 # copyright notice, this list of conditions and the following
11 # disclaimer in the documentation and/or other materials provided
12 # with the distribution.
13 # * Neither the name of Google Inc. nor the names of its
14 # contributors may be used to endorse or promote products derived
15 # from this software without specific prior written permission.
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 SHA1_RE = re.compile('^[a-fA-F0-9]{40}$')
32 ROLL_DEPS_GIT_SVN_ID_RE = re.compile('^git-svn-id: .*@([0-9]+) .*$')
34 # Regular expression that matches a single commit footer line.
35 COMMIT_FOOTER_ENTRY_RE = re.compile(r'([^:]+):\s+(.+)')
37 # Footer metadata key for commit position.
38 COMMIT_POSITION_FOOTER_KEY = 'Cr-Commit-Position'
40 # Regular expression to parse a commit position
41 COMMIT_POSITION_RE = re.compile(r'(.+)@\{#(\d+)\}')
43 # Key for the 'git-svn' ID metadata commit footer entry.
44 GIT_SVN_ID_FOOTER_KEY = 'git-svn-id'
46 # e.g., git-svn-id: https://v8.googlecode.com/svn/trunk@23117
47 # ce2b1a6d-e550-0410-aec6-3dcde31c8c00
48 GIT_SVN_ID_RE = re.compile(r'((?:\w+)://[^@]+)@(\d+)\s+(?:[a-zA-Z0-9\-]+)')
51 # Copied from bot_update.py.
52 def GetCommitMessageFooterMap(message):
53 """Returns: (dict) A dictionary of commit message footer entries.
57 # Extract the lines in the footer block.
59 for line in message.strip().splitlines():
68 m = COMMIT_FOOTER_ENTRY_RE.match(line)
70 # If any single line isn't valid, the entire footer is invalid.
73 footers[m.group(1)] = m.group(2).strip()
77 class GitFailedException(Exception):
82 def new_f(*args, **kwargs):
83 result = f(*args, **kwargs)
92 """['-a', '', 'abc', ''] -> '-a abc'"""
93 return " ".join(filter(None, l))
100 class GitRecipesMixin(object):
101 def GitIsWorkdirClean(self, **kwargs):
102 return self.Git("status -s -uno", **kwargs).strip() == ""
105 def GitBranch(self, **kwargs):
106 return self.Git("branch", **kwargs)
108 def GitCreateBranch(self, name, remote="", **kwargs):
110 remote_args = ["--upstream", remote] if remote else []
111 self.Git(MakeArgs(["new-branch", name] + remote_args), **kwargs)
113 def GitDeleteBranch(self, name, **kwargs):
115 self.Git(MakeArgs(["branch -D", name]), **kwargs)
117 def GitReset(self, name, **kwargs):
119 self.Git(MakeArgs(["reset --hard", name]), **kwargs)
121 def GitStash(self, **kwargs):
122 self.Git(MakeArgs(["stash"]), **kwargs)
124 def GitRemotes(self, **kwargs):
125 return map(str.strip,
126 self.Git(MakeArgs(["branch -r"]), **kwargs).splitlines())
128 def GitCheckout(self, name, **kwargs):
130 self.Git(MakeArgs(["checkout -f", name]), **kwargs)
132 def GitCheckoutFile(self, name, branch_or_hash, **kwargs):
134 assert branch_or_hash
135 self.Git(MakeArgs(["checkout -f", branch_or_hash, "--", name]), **kwargs)
137 def GitCheckoutFileSafe(self, name, branch_or_hash, **kwargs):
139 self.GitCheckoutFile(name, branch_or_hash, **kwargs)
140 except GitFailedException: # pragma: no cover
141 # The file doesn't exist in that revision.
145 def GitChangedFiles(self, git_hash, **kwargs):
148 files = self.Git(MakeArgs(["diff --name-only",
150 "%s^" % git_hash]), **kwargs)
151 return map(str.strip, files.splitlines())
152 except GitFailedException: # pragma: no cover
153 # Git fails using "^" at branch roots.
158 def GitCurrentBranch(self, **kwargs):
159 for line in self.Git("status -s -b -uno", **kwargs).strip().splitlines():
160 match = re.match(r"^## (.+)", line)
161 if match: return match.group(1)
162 raise Exception("Couldn't find curent branch.") # pragma: no cover
165 def GitLog(self, n=0, format="", grep="", git_hash="", parent_hash="",
166 branch="", reverse=False, **kwargs):
167 assert not (git_hash and parent_hash)
170 args.append("-%d" % n)
172 args.append("--format=%s" % format)
174 args.append("--grep=\"%s\"" % grep.replace("\"", "\\\""))
176 args.append("--reverse")
178 args.append(git_hash)
180 args.append("%s^" % parent_hash)
182 return self.Git(MakeArgs(args), **kwargs)
184 def GitGetPatch(self, git_hash, **kwargs):
186 return self.Git(MakeArgs(["log", "-1", "-p", git_hash]), **kwargs)
188 # TODO(machenbach): Unused? Remove.
189 def GitAdd(self, name, **kwargs):
191 self.Git(MakeArgs(["add", Quoted(name)]), **kwargs)
193 def GitApplyPatch(self, patch_file, reverse=False, **kwargs):
195 args = ["apply --index --reject"]
197 args.append("--reverse")
198 args.append(Quoted(patch_file))
199 self.Git(MakeArgs(args), **kwargs)
201 def GitUpload(self, reviewer="", author="", force=False, cq=False,
202 bypass_hooks=False, cc="", **kwargs):
203 args = ["cl upload --send-mail"]
205 args += ["--email", Quoted(author)]
207 args += ["-r", Quoted(reviewer)]
211 args.append("--use-commit-queue")
213 args.append("--bypass-hooks")
215 args += ["--cc", Quoted(cc)]
216 # TODO(machenbach): Check output in forced mode. Verify that all required
217 # base files were uploaded, if not retry.
218 self.Git(MakeArgs(args), pipe=False, **kwargs)
220 def GitCommit(self, message="", file_name="", author=None, **kwargs):
221 assert message or file_name
224 args += ["-aF", Quoted(file_name)]
226 args += ["-am", Quoted(message)]
228 args += ["--author", "\"%s <%s>\"" % (author, author)]
229 self.Git(MakeArgs(args), **kwargs)
231 def GitPresubmit(self, **kwargs):
232 self.Git("cl presubmit", "PRESUBMIT_TREE_CHECK=\"skip\"", **kwargs)
234 def GitDCommit(self, **kwargs):
236 "cl dcommit -f --bypass-hooks", retry_on=lambda x: x is None, **kwargs)
238 def GitCLLand(self, **kwargs):
240 "cl land -f --bypass-hooks", retry_on=lambda x: x is None, **kwargs)
242 def GitDiff(self, loc1, loc2, **kwargs):
243 return self.Git(MakeArgs(["diff", loc1, loc2]), **kwargs)
245 def GitPull(self, **kwargs):
246 self.Git("pull", **kwargs)
248 def GitFetchOrigin(self, **kwargs):
249 self.Git("fetch origin", **kwargs)
251 def GitConvertToSVNRevision(self, git_hash, **kwargs):
252 result = self.Git(MakeArgs(["rev-list", "-n", "1", git_hash]), **kwargs)
253 if not result or not SHA1_RE.match(result):
254 raise GitFailedException("Git hash %s is unknown." % git_hash)
255 log = self.GitLog(n=1, format="%B", git_hash=git_hash, **kwargs)
256 for line in reversed(log.splitlines()):
257 match = ROLL_DEPS_GIT_SVN_ID_RE.match(line.strip())
259 return match.group(1)
260 raise GitFailedException("Couldn't convert %s to SVN." % git_hash)
263 # Copied from bot_update.py and modified for svn-like numbers only.
264 def GetCommitPositionNumber(self, git_hash, **kwargs):
265 """Dumps the 'git' log for a specific revision and parses out the commit
268 If a commit position metadata key is found, its number will be returned.
270 Otherwise, we will search for a 'git-svn' metadata entry. If one is found,
271 its SVN revision value is returned.
273 git_log = self.GitLog(format='%B', n=1, git_hash=git_hash, **kwargs)
274 footer_map = GetCommitMessageFooterMap(git_log)
276 # Search for commit position metadata
277 value = footer_map.get(COMMIT_POSITION_FOOTER_KEY)
279 match = COMMIT_POSITION_RE.match(value)
281 return match.group(2)
283 # Extract the svn revision from 'git-svn' metadata
284 value = footer_map.get(GIT_SVN_ID_FOOTER_KEY)
286 match = GIT_SVN_ID_RE.match(value)
288 return match.group(2)
293 def GitSVNFetch(self, **kwargs):
294 self.Git("svn fetch", **kwargs)
296 def GitSVNRebase(self, **kwargs):
297 self.Git("svn rebase", **kwargs)
299 # TODO(machenbach): Unused? Remove.
301 def GitSVNLog(self, **kwargs):
302 return self.Git("svn log -1 --oneline", **kwargs)
305 def GitSVNFindGitHash(self, revision, branch="", **kwargs):
307 args = MakeArgs(["svn find-rev", "r%s" % revision, branch])
309 # Pick the last line if multiple lines are available. The first lines might
310 # print information about rebuilding the svn-git mapping.
311 return self.Git(args, **kwargs).splitlines()[-1]
314 def GitSVNFindSVNRev(self, git_hash, branch="", **kwargs):
315 return self.Git(MakeArgs(["svn find-rev", git_hash, branch]), **kwargs)
317 def GitSVNDCommit(self, **kwargs):
318 return self.Git("svn dcommit 2>&1", retry_on=lambda x: x is None, **kwargs)
320 def GitSVNTag(self, version, **kwargs):
321 self.Git(("svn tag %s -m \"Tagging version %s\"" % (version, version)),
322 retry_on=lambda x: x is None,