blob: 751d4ac72eff3ae37276eee309ef8ce78ecd27b8 [file] [log] [blame]
kbr9fe00f62015-05-21 21:09:501#!/usr/bin/env python
2# Copyright 2015 The Chromium 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
6import argparse
7import collections
8import logging
9import os
10import re
11import subprocess
12import sys
13import time
14
geofflang527982f92015-09-15 20:39:2415extra_trybots = [
kbr44b05f82016-01-07 23:37:0116 {
17 "mastername": "tryserver.chromium.win",
18 "buildername": "win_clang_dbg",
19 }
geofflang527982f92015-09-15 20:39:2420]
kbr9fe00f62015-05-21 21:09:5021
22SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
23SRC_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir))
mcgrathrb729cfa2015-10-26 22:07:5124sys.path.insert(0, os.path.join(SRC_DIR, 'build'))
kbr9fe00f62015-05-21 21:09:5025import find_depot_tools
26find_depot_tools.add_depot_tools_to_path()
jmadill241d77b2015-05-25 19:21:5427import roll_dep_svn
kbr9fe00f62015-05-21 21:09:5028from gclient import GClientKeywords
29from third_party import upload
30
31# Avoid depot_tools/third_party/upload.py print verbose messages.
32upload.verbosity = 0 # Errors only.
33
34CHROMIUM_GIT_URL = 'https://chromium.googlesource.com/chromium/src.git'
35CL_ISSUE_RE = re.compile('^Issue number: ([0-9]+) \((.*)\)$')
36RIETVELD_URL_RE = re.compile('^https?://(.*)/(.*)')
37ROLL_BRANCH_NAME = 'special_angle_roll_branch'
38TRYJOB_STATUS_SLEEP_SECONDS = 30
39
40# Use a shell for subcommands on Windows to get a PATH search.
kbrebf7b742015-06-25 02:31:4141IS_WIN = sys.platform.startswith('win')
geofflang44a4fb3e2015-06-09 21:45:3742ANGLE_PATH = os.path.join('third_party', 'angle')
kbr9fe00f62015-05-21 21:09:5043
44CommitInfo = collections.namedtuple('CommitInfo', ['git_commit',
45 'git_repo_url'])
46CLInfo = collections.namedtuple('CLInfo', ['issue', 'url', 'rietveld_server'])
47
geofflang44a4fb3e2015-06-09 21:45:3748def _PosixPath(path):
49 """Convert a possibly-Windows path to a posix-style path."""
50 (_, path) = os.path.splitdrive(path)
51 return path.replace(os.sep, '/')
kbr9fe00f62015-05-21 21:09:5052
53def _ParseGitCommitHash(description):
54 for line in description.splitlines():
55 if line.startswith('commit '):
56 return line.split()[1]
57 logging.error('Failed to parse git commit id from:\n%s\n', description)
58 sys.exit(-1)
59 return None
60
61
62def _ParseDepsFile(filename):
63 with open(filename, 'rb') as f:
64 deps_content = f.read()
65 return _ParseDepsDict(deps_content)
66
67
68def _ParseDepsDict(deps_content):
69 local_scope = {}
70 var = GClientKeywords.VarImpl({}, local_scope)
71 global_scope = {
72 'File': GClientKeywords.FileImpl,
73 'From': GClientKeywords.FromImpl,
74 'Var': var.Lookup,
75 'deps_os': {},
76 }
77 exec(deps_content, global_scope, local_scope)
78 return local_scope
79
80
geofflang44a4fb3e2015-06-09 21:45:3781def _GenerateCLDescriptionCommand(angle_current, angle_new, bugs):
kbr9fe00f62015-05-21 21:09:5082 def GetChangeString(current_hash, new_hash):
83 return '%s..%s' % (current_hash[0:7], new_hash[0:7]);
84
85 def GetChangeLogURL(git_repo_url, change_string):
86 return '%s/+log/%s' % (git_repo_url, change_string)
87
geofflang44a4fb3e2015-06-09 21:45:3788 def GetBugString(bugs):
89 bug_str = 'BUG='
90 for bug in bugs:
91 bug_str += str(bug) + ','
92 return bug_str.rstrip(',')
93
kbr9fe00f62015-05-21 21:09:5094 if angle_current.git_commit != angle_new.git_commit:
95 change_str = GetChangeString(angle_current.git_commit,
96 angle_new.git_commit)
97 changelog_url = GetChangeLogURL(angle_current.git_repo_url,
98 change_str)
99
geofflang44a4fb3e2015-06-09 21:45:37100 return [
101 '-m', 'Roll ANGLE ' + change_str,
102 '-m', '%s' % changelog_url,
103 '-m', GetBugString(bugs),
104 '-m', 'TEST=bots',
105 ]
kbr9fe00f62015-05-21 21:09:50106
107
108class AutoRoller(object):
109 def __init__(self, chromium_src):
110 self._chromium_src = chromium_src
111
112 def _RunCommand(self, command, working_dir=None, ignore_exit_code=False,
113 extra_env=None):
114 """Runs a command and returns the stdout from that command.
115
116 If the command fails (exit code != 0), the function will exit the process.
117 """
118 working_dir = working_dir or self._chromium_src
119 logging.debug('cmd: %s cwd: %s', ' '.join(command), working_dir)
120 env = os.environ.copy()
121 if extra_env:
122 logging.debug('extra env: %s', extra_env)
123 env.update(extra_env)
124 p = subprocess.Popen(command, stdout=subprocess.PIPE,
kbrebf7b742015-06-25 02:31:41125 stderr=subprocess.PIPE, shell=IS_WIN, env=env,
kbr9fe00f62015-05-21 21:09:50126 cwd=working_dir, universal_newlines=True)
127 output = p.stdout.read()
128 p.wait()
129 p.stdout.close()
130 p.stderr.close()
131
132 if not ignore_exit_code and p.returncode != 0:
133 logging.error('Command failed: %s\n%s', str(command), output)
134 sys.exit(p.returncode)
135 return output
136
137 def _GetCommitInfo(self, path_below_src, git_hash=None, git_repo_url=None):
138 working_dir = os.path.join(self._chromium_src, path_below_src)
139 self._RunCommand(['git', 'fetch', 'origin'], working_dir=working_dir)
140 revision_range = git_hash or 'origin'
141 ret = self._RunCommand(
142 ['git', '--no-pager', 'log', revision_range, '--pretty=full', '-1'],
143 working_dir=working_dir)
144 return CommitInfo(_ParseGitCommitHash(ret), git_repo_url)
145
146 def _GetDepsCommitInfo(self, deps_dict, path_below_src):
geofflang44a4fb3e2015-06-09 21:45:37147 entry = deps_dict['deps'][_PosixPath('src/%s' % path_below_src)]
kbr9fe00f62015-05-21 21:09:50148 at_index = entry.find('@')
149 git_repo_url = entry[:at_index]
150 git_hash = entry[at_index + 1:]
151 return self._GetCommitInfo(path_below_src, git_hash, git_repo_url)
152
153 def _GetCLInfo(self):
154 cl_output = self._RunCommand(['git', 'cl', 'issue'])
155 m = CL_ISSUE_RE.match(cl_output.strip())
156 if not m:
157 logging.error('Cannot find any CL info. Output was:\n%s', cl_output)
158 sys.exit(-1)
159 issue_number = int(m.group(1))
160 url = m.group(2)
161
162 # Parse the Rietveld host from the URL.
163 m = RIETVELD_URL_RE.match(url)
164 if not m:
165 logging.error('Cannot parse Rietveld host from URL: %s', url)
166 sys.exit(-1)
167 rietveld_server = m.group(1)
168 return CLInfo(issue_number, url, rietveld_server)
169
170 def _GetCurrentBranchName(self):
171 return self._RunCommand(
172 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).splitlines()[0]
173
174 def _IsTreeClean(self):
175 lines = self._RunCommand(
176 ['git', 'status', '--porcelain', '-uno']).splitlines()
177 if len(lines) == 0:
178 return True
179
180 logging.debug('Dirty/unversioned files:\n%s', '\n'.join(lines))
181 return False
182
geofflang44a4fb3e2015-06-09 21:45:37183 def _GetBugList(self, path_below_src, angle_current, angle_new):
184 working_dir = os.path.join(self._chromium_src, path_below_src)
185 lines = self._RunCommand(
186 ['git','log',
187 '%s..%s' % (angle_current.git_commit, angle_new.git_commit)],
188 working_dir=working_dir).split('\n')
189 bugs = set()
190 for line in lines:
191 line = line.strip()
192 bug_prefix = 'BUG='
193 if line.startswith(bug_prefix):
194 bugs_strings = line[len(bug_prefix):].split(',')
195 for bug_string in bugs_strings:
196 try:
197 bugs.add(int(bug_string))
198 except:
199 # skip this, it may be a project specific bug such as
200 # "angleproject:X" or an ill-formed BUG= message
201 pass
202 return bugs
203
kbr9fe00f62015-05-21 21:09:50204 def _UpdateReadmeFile(self, readme_path, new_revision):
205 readme = open(os.path.join(self._chromium_src, readme_path), 'r+')
206 txt = readme.read()
207 m = re.sub(re.compile('.*^Revision\: ([0-9]*).*', re.MULTILINE),
208 ('Revision: %s' % new_revision), txt)
209 readme.seek(0)
210 readme.write(m)
211 readme.truncate()
212
213 def PrepareRoll(self, ignore_checks):
214 # TODO(kjellander): use os.path.normcase, os.path.join etc for all paths for
215 # cross platform compatibility.
216
217 if not ignore_checks:
218 if self._GetCurrentBranchName() != 'master':
219 logging.error('Please checkout the master branch.')
220 return -1
221 if not self._IsTreeClean():
222 logging.error('Please make sure you don\'t have any modified files.')
223 return -1
224
225 # Always clean up any previous roll.
226 self.Abort()
227
228 logging.debug('Pulling latest changes')
229 if not ignore_checks:
230 self._RunCommand(['git', 'pull'])
231
232 self._RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
233
234 # Modify Chromium's DEPS file.
235
236 # Parse current hashes.
237 deps_filename = os.path.join(self._chromium_src, 'DEPS')
238 deps = _ParseDepsFile(deps_filename)
239 angle_current = self._GetDepsCommitInfo(deps, ANGLE_PATH)
240
241 # Find ToT revisions.
242 angle_latest = self._GetCommitInfo(ANGLE_PATH)
243
kbrebf7b742015-06-25 02:31:41244 if IS_WIN:
245 # Make sure the roll script doesn't use windows line endings
246 self._RunCommand(['git', 'config', 'core.autocrlf', 'true'])
geofflang44a4fb3e2015-06-09 21:45:37247
kbr9fe00f62015-05-21 21:09:50248 self._UpdateDep(deps_filename, ANGLE_PATH, angle_latest)
249
250 if self._IsTreeClean():
251 logging.debug('Tree is clean - no changes detected.')
252 self._DeleteRollBranch()
253 else:
geofflang44a4fb3e2015-06-09 21:45:37254 bugs = self._GetBugList(ANGLE_PATH, angle_current, angle_latest)
255 description = _GenerateCLDescriptionCommand(
256 angle_current, angle_latest, bugs)
kbr9fe00f62015-05-21 21:09:50257 logging.debug('Committing changes locally.')
258 self._RunCommand(['git', 'add', '--update', '.'])
geofflang44a4fb3e2015-06-09 21:45:37259 self._RunCommand(['git', 'commit'] + description)
kbr9fe00f62015-05-21 21:09:50260 logging.debug('Uploading changes...')
geofflang44a4fb3e2015-06-09 21:45:37261 self._RunCommand(['git', 'cl', 'upload'],
kbr9fe00f62015-05-21 21:09:50262 extra_env={'EDITOR': 'true'})
geofflang527982f92015-09-15 20:39:24263
264 # Run the default trybots
265 base_try_cmd = ['git', 'cl', 'try']
266 self._RunCommand(base_try_cmd)
267
268 if extra_trybots:
269 # Run additional tryjobs
270 extra_try_args = []
271 for extra_trybot in extra_trybots:
kbr44b05f82016-01-07 23:37:01272 extra_try_args += ['-m', extra_trybot["mastername"],
273 '-b', extra_trybot["buildername"]]
geofflang527982f92015-09-15 20:39:24274 self._RunCommand(base_try_cmd + extra_try_args)
275
kbr9fe00f62015-05-21 21:09:50276 cl_info = self._GetCLInfo()
277 print 'Issue: %d URL: %s' % (cl_info.issue, cl_info.url)
278
279 # Checkout master again.
280 self._RunCommand(['git', 'checkout', 'master'])
281 print 'Roll branch left as ' + ROLL_BRANCH_NAME
282 return 0
283
284 def _UpdateDep(self, deps_filename, dep_relative_to_src, commit_info):
geofflang44a4fb3e2015-06-09 21:45:37285 dep_name = _PosixPath(os.path.join('src', dep_relative_to_src))
kbr9fe00f62015-05-21 21:09:50286
jmadill241d77b2015-05-25 19:21:54287 # roll_dep_svn.py relies on cwd being the Chromium checkout, so let's
kbr9fe00f62015-05-21 21:09:50288 # temporarily change the working directory and then change back.
289 cwd = os.getcwd()
290 os.chdir(os.path.dirname(deps_filename))
jmadill241d77b2015-05-25 19:21:54291 roll_dep_svn.update_deps(deps_filename, dep_relative_to_src, dep_name,
292 commit_info.git_commit, '')
kbr9fe00f62015-05-21 21:09:50293 os.chdir(cwd)
294
295 def _DeleteRollBranch(self):
296 self._RunCommand(['git', 'checkout', 'master'])
297 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
298 logging.debug('Deleted the local roll branch (%s)', ROLL_BRANCH_NAME)
299
300
301 def _GetBranches(self):
302 """Returns a tuple of active,branches.
303
304 The 'active' is the name of the currently active branch and 'branches' is a
305 list of all branches.
306 """
307 lines = self._RunCommand(['git', 'branch']).split('\n')
308 branches = []
309 active = ''
310 for l in lines:
311 if '*' in l:
312 # The assumption is that the first char will always be the '*'.
313 active = l[1:].strip()
314 branches.append(active)
315 else:
316 b = l.strip()
317 if b:
318 branches.append(b)
319 return (active, branches)
320
321 def Abort(self):
322 active_branch, branches = self._GetBranches()
323 if active_branch == ROLL_BRANCH_NAME:
324 active_branch = 'master'
325 if ROLL_BRANCH_NAME in branches:
326 print 'Aborting pending roll.'
327 self._RunCommand(['git', 'checkout', ROLL_BRANCH_NAME])
328 # Ignore an error here in case an issue wasn't created for some reason.
329 self._RunCommand(['git', 'cl', 'set_close'], ignore_exit_code=True)
330 self._RunCommand(['git', 'checkout', active_branch])
331 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
332 return 0
333
334
335def main():
kbr9fe00f62015-05-21 21:09:50336 parser = argparse.ArgumentParser(
337 description='Auto-generates a CL containing an ANGLE roll.')
338 parser.add_argument('--abort',
339 help=('Aborts a previously prepared roll. '
340 'Closes any associated issues and deletes the roll branches'),
341 action='store_true')
342 parser.add_argument('--ignore-checks', action='store_true', default=False,
343 help=('Skips checks for being on the master branch, dirty workspaces and '
344 'the updating of the checkout. Will still delete and create local '
345 'Git branches.'))
346 parser.add_argument('-v', '--verbose', action='store_true', default=False,
347 help='Be extra verbose in printing of log messages.')
348 args = parser.parse_args()
349
350 if args.verbose:
351 logging.basicConfig(level=logging.DEBUG)
352 else:
353 logging.basicConfig(level=logging.ERROR)
354
355 autoroller = AutoRoller(SRC_DIR)
356 if args.abort:
357 return autoroller.Abort()
358 else:
359 return autoroller.PrepareRoll(args.ignore_checks)
360
361if __name__ == '__main__':
362 sys.exit(main())