blob: 6432cc4a093760086393a1049c335444478d6119 [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
geofflang896099f62016-02-12 15:53:2815extra_cq_trybots = [
kbr44b05f82016-01-07 23:37:0116 {
17 "mastername": "tryserver.chromium.win",
geofflang896099f62016-02-12 15:53:2818 "buildernames": ["win_optional_gpu_tests_rel"]
19 },
20 {
21 "mastername": "tryserver.chromium.mac",
22 "buildernames": ["mac_optional_gpu_tests_rel"]
geofflange45a836a2016-02-16 22:43:2323 },
geofflang896099f62016-02-12 15:53:2824 {
25 "mastername": "tryserver.chromium.linux",
26 "buildernames": ["linux_optional_gpu_tests_rel"]
27 }
28]
29extra_fyi_trybots = [
30 {
31 "mastername": "tryserver.chromium.win",
32 "buildernames": ["win_clang_dbg"]
kbr44b05f82016-01-07 23:37:0133 }
geofflang527982f92015-09-15 20:39:2434]
kbr9fe00f62015-05-21 21:09:5035
36SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
37SRC_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir))
mcgrathrb729cfa2015-10-26 22:07:5138sys.path.insert(0, os.path.join(SRC_DIR, 'build'))
kbr9fe00f62015-05-21 21:09:5039import find_depot_tools
40find_depot_tools.add_depot_tools_to_path()
jmadill241d77b2015-05-25 19:21:5441import roll_dep_svn
kbr9fe00f62015-05-21 21:09:5042from gclient import GClientKeywords
43from third_party import upload
44
45# Avoid depot_tools/third_party/upload.py print verbose messages.
46upload.verbosity = 0 # Errors only.
47
48CHROMIUM_GIT_URL = 'https://chromium.googlesource.com/chromium/src.git'
49CL_ISSUE_RE = re.compile('^Issue number: ([0-9]+) \((.*)\)$')
50RIETVELD_URL_RE = re.compile('^https?://(.*)/(.*)')
51ROLL_BRANCH_NAME = 'special_angle_roll_branch'
52TRYJOB_STATUS_SLEEP_SECONDS = 30
53
54# Use a shell for subcommands on Windows to get a PATH search.
kbrebf7b742015-06-25 02:31:4155IS_WIN = sys.platform.startswith('win')
geofflang44a4fb3e2015-06-09 21:45:3756ANGLE_PATH = os.path.join('third_party', 'angle')
kbr9fe00f62015-05-21 21:09:5057
58CommitInfo = collections.namedtuple('CommitInfo', ['git_commit',
59 'git_repo_url'])
60CLInfo = collections.namedtuple('CLInfo', ['issue', 'url', 'rietveld_server'])
61
geofflang44a4fb3e2015-06-09 21:45:3762def _PosixPath(path):
63 """Convert a possibly-Windows path to a posix-style path."""
64 (_, path) = os.path.splitdrive(path)
65 return path.replace(os.sep, '/')
kbr9fe00f62015-05-21 21:09:5066
67def _ParseGitCommitHash(description):
68 for line in description.splitlines():
69 if line.startswith('commit '):
70 return line.split()[1]
71 logging.error('Failed to parse git commit id from:\n%s\n', description)
72 sys.exit(-1)
73 return None
74
75
76def _ParseDepsFile(filename):
77 with open(filename, 'rb') as f:
78 deps_content = f.read()
79 return _ParseDepsDict(deps_content)
80
81
82def _ParseDepsDict(deps_content):
83 local_scope = {}
84 var = GClientKeywords.VarImpl({}, local_scope)
85 global_scope = {
86 'File': GClientKeywords.FileImpl,
87 'From': GClientKeywords.FromImpl,
88 'Var': var.Lookup,
89 'deps_os': {},
90 }
91 exec(deps_content, global_scope, local_scope)
92 return local_scope
93
94
geofflang896099f62016-02-12 15:53:2895def _GenerateCLDescriptionCommand(angle_current, angle_new, bugs, tbr):
kbr9fe00f62015-05-21 21:09:5096 def GetChangeString(current_hash, new_hash):
97 return '%s..%s' % (current_hash[0:7], new_hash[0:7]);
98
99 def GetChangeLogURL(git_repo_url, change_string):
100 return '%s/+log/%s' % (git_repo_url, change_string)
101
geofflang44a4fb3e2015-06-09 21:45:37102 def GetBugString(bugs):
103 bug_str = 'BUG='
104 for bug in bugs:
105 bug_str += str(bug) + ','
106 return bug_str.rstrip(',')
107
kbr9fe00f62015-05-21 21:09:50108 if angle_current.git_commit != angle_new.git_commit:
109 change_str = GetChangeString(angle_current.git_commit,
110 angle_new.git_commit)
111 changelog_url = GetChangeLogURL(angle_current.git_repo_url,
112 change_str)
113
geofflang896099f62016-02-12 15:53:28114 def GetExtraCQTrybotString():
kbre85ee562016-02-09 04:37:35115 s = ''
geofflang896099f62016-02-12 15:53:28116 for t in extra_cq_trybots:
kbre85ee562016-02-09 04:37:35117 if s:
118 s += ';'
119 s += t['mastername'] + ':' + ','.join(t['buildernames'])
120 return s
121
geofflang896099f62016-02-12 15:53:28122 def GetTBRString(tbr):
123 if not tbr:
124 return ''
125 return 'TBR=' + tbr
126
kbre85ee562016-02-09 04:37:35127 extra_trybot_args = []
geofflang896099f62016-02-12 15:53:28128 if extra_cq_trybots:
129 extra_trybot_string = GetExtraCQTrybotString()
kbre85ee562016-02-09 04:37:35130 extra_trybot_args = ['-m', 'CQ_INCLUDE_TRYBOTS=' + extra_trybot_string]
131
geofflang44a4fb3e2015-06-09 21:45:37132 return [
133 '-m', 'Roll ANGLE ' + change_str,
134 '-m', '%s' % changelog_url,
135 '-m', GetBugString(bugs),
geofflang896099f62016-02-12 15:53:28136 '-m', GetTBRString(tbr),
geofflang44a4fb3e2015-06-09 21:45:37137 '-m', 'TEST=bots',
kbre85ee562016-02-09 04:37:35138 ] + extra_trybot_args
kbr9fe00f62015-05-21 21:09:50139
140
141class AutoRoller(object):
142 def __init__(self, chromium_src):
143 self._chromium_src = chromium_src
144
145 def _RunCommand(self, command, working_dir=None, ignore_exit_code=False,
146 extra_env=None):
147 """Runs a command and returns the stdout from that command.
148
149 If the command fails (exit code != 0), the function will exit the process.
150 """
151 working_dir = working_dir or self._chromium_src
152 logging.debug('cmd: %s cwd: %s', ' '.join(command), working_dir)
153 env = os.environ.copy()
154 if extra_env:
155 logging.debug('extra env: %s', extra_env)
156 env.update(extra_env)
157 p = subprocess.Popen(command, stdout=subprocess.PIPE,
kbrebf7b742015-06-25 02:31:41158 stderr=subprocess.PIPE, shell=IS_WIN, env=env,
kbr9fe00f62015-05-21 21:09:50159 cwd=working_dir, universal_newlines=True)
160 output = p.stdout.read()
161 p.wait()
162 p.stdout.close()
163 p.stderr.close()
164
165 if not ignore_exit_code and p.returncode != 0:
166 logging.error('Command failed: %s\n%s', str(command), output)
167 sys.exit(p.returncode)
168 return output
169
170 def _GetCommitInfo(self, path_below_src, git_hash=None, git_repo_url=None):
171 working_dir = os.path.join(self._chromium_src, path_below_src)
172 self._RunCommand(['git', 'fetch', 'origin'], working_dir=working_dir)
173 revision_range = git_hash or 'origin'
174 ret = self._RunCommand(
175 ['git', '--no-pager', 'log', revision_range, '--pretty=full', '-1'],
176 working_dir=working_dir)
177 return CommitInfo(_ParseGitCommitHash(ret), git_repo_url)
178
179 def _GetDepsCommitInfo(self, deps_dict, path_below_src):
geofflang44a4fb3e2015-06-09 21:45:37180 entry = deps_dict['deps'][_PosixPath('src/%s' % path_below_src)]
kbr9fe00f62015-05-21 21:09:50181 at_index = entry.find('@')
182 git_repo_url = entry[:at_index]
183 git_hash = entry[at_index + 1:]
184 return self._GetCommitInfo(path_below_src, git_hash, git_repo_url)
185
186 def _GetCLInfo(self):
187 cl_output = self._RunCommand(['git', 'cl', 'issue'])
188 m = CL_ISSUE_RE.match(cl_output.strip())
189 if not m:
190 logging.error('Cannot find any CL info. Output was:\n%s', cl_output)
191 sys.exit(-1)
192 issue_number = int(m.group(1))
193 url = m.group(2)
194
195 # Parse the Rietveld host from the URL.
196 m = RIETVELD_URL_RE.match(url)
197 if not m:
198 logging.error('Cannot parse Rietveld host from URL: %s', url)
199 sys.exit(-1)
200 rietveld_server = m.group(1)
201 return CLInfo(issue_number, url, rietveld_server)
202
203 def _GetCurrentBranchName(self):
204 return self._RunCommand(
205 ['git', 'rev-parse', '--abbrev-ref', 'HEAD']).splitlines()[0]
206
207 def _IsTreeClean(self):
208 lines = self._RunCommand(
209 ['git', 'status', '--porcelain', '-uno']).splitlines()
210 if len(lines) == 0:
211 return True
212
213 logging.debug('Dirty/unversioned files:\n%s', '\n'.join(lines))
214 return False
215
geofflang44a4fb3e2015-06-09 21:45:37216 def _GetBugList(self, path_below_src, angle_current, angle_new):
217 working_dir = os.path.join(self._chromium_src, path_below_src)
218 lines = self._RunCommand(
219 ['git','log',
220 '%s..%s' % (angle_current.git_commit, angle_new.git_commit)],
221 working_dir=working_dir).split('\n')
222 bugs = set()
223 for line in lines:
224 line = line.strip()
225 bug_prefix = 'BUG='
226 if line.startswith(bug_prefix):
227 bugs_strings = line[len(bug_prefix):].split(',')
228 for bug_string in bugs_strings:
229 try:
230 bugs.add(int(bug_string))
231 except:
232 # skip this, it may be a project specific bug such as
233 # "angleproject:X" or an ill-formed BUG= message
234 pass
235 return bugs
236
kbr9fe00f62015-05-21 21:09:50237 def _UpdateReadmeFile(self, readme_path, new_revision):
238 readme = open(os.path.join(self._chromium_src, readme_path), 'r+')
239 txt = readme.read()
240 m = re.sub(re.compile('.*^Revision\: ([0-9]*).*', re.MULTILINE),
241 ('Revision: %s' % new_revision), txt)
242 readme.seek(0)
243 readme.write(m)
244 readme.truncate()
245
geofflang896099f62016-02-12 15:53:28246 def _TriggerExtraTrybots(self, trybots):
247 for trybot in trybots:
248 for builder in trybot['buildernames']:
249 self._RunCommand([
250 'git', 'cl', 'try',
251 '-m', trybot['mastername'],
252 '-b', builder])
253
254 def PrepareRoll(self, ignore_checks, tbr, should_commit):
kbr9fe00f62015-05-21 21:09:50255 # TODO(kjellander): use os.path.normcase, os.path.join etc for all paths for
256 # cross platform compatibility.
257
258 if not ignore_checks:
259 if self._GetCurrentBranchName() != 'master':
260 logging.error('Please checkout the master branch.')
261 return -1
262 if not self._IsTreeClean():
263 logging.error('Please make sure you don\'t have any modified files.')
264 return -1
265
266 # Always clean up any previous roll.
267 self.Abort()
268
269 logging.debug('Pulling latest changes')
270 if not ignore_checks:
271 self._RunCommand(['git', 'pull'])
272
273 self._RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
274
275 # Modify Chromium's DEPS file.
276
277 # Parse current hashes.
278 deps_filename = os.path.join(self._chromium_src, 'DEPS')
279 deps = _ParseDepsFile(deps_filename)
280 angle_current = self._GetDepsCommitInfo(deps, ANGLE_PATH)
281
282 # Find ToT revisions.
283 angle_latest = self._GetCommitInfo(ANGLE_PATH)
284
kbrebf7b742015-06-25 02:31:41285 if IS_WIN:
286 # Make sure the roll script doesn't use windows line endings
287 self._RunCommand(['git', 'config', 'core.autocrlf', 'true'])
geofflang44a4fb3e2015-06-09 21:45:37288
kbr9fe00f62015-05-21 21:09:50289 self._UpdateDep(deps_filename, ANGLE_PATH, angle_latest)
290
291 if self._IsTreeClean():
292 logging.debug('Tree is clean - no changes detected.')
293 self._DeleteRollBranch()
294 else:
geofflang44a4fb3e2015-06-09 21:45:37295 bugs = self._GetBugList(ANGLE_PATH, angle_current, angle_latest)
296 description = _GenerateCLDescriptionCommand(
geofflang896099f62016-02-12 15:53:28297 angle_current, angle_latest, bugs, tbr)
kbr9fe00f62015-05-21 21:09:50298 logging.debug('Committing changes locally.')
299 self._RunCommand(['git', 'add', '--update', '.'])
geofflang44a4fb3e2015-06-09 21:45:37300 self._RunCommand(['git', 'commit'] + description)
kbr9fe00f62015-05-21 21:09:50301 logging.debug('Uploading changes...')
geofflang44a4fb3e2015-06-09 21:45:37302 self._RunCommand(['git', 'cl', 'upload'],
kbr9fe00f62015-05-21 21:09:50303 extra_env={'EDITOR': 'true'})
geofflang527982f92015-09-15 20:39:24304
kbre85ee562016-02-09 04:37:35305 # Kick off tryjobs.
geofflang527982f92015-09-15 20:39:24306 base_try_cmd = ['git', 'cl', 'try']
307 self._RunCommand(base_try_cmd)
308
geofflang896099f62016-02-12 15:53:28309 if extra_cq_trybots:
kbre85ee562016-02-09 04:37:35310 # Run additional tryjobs.
311 # TODO(kbr): this should not be necessary -- the
312 # CQ_INCLUDE_TRYBOTS directive above should handle it.
313 # http://crbug.com/585237
geofflang896099f62016-02-12 15:53:28314 self._TriggerExtraTrybots(extra_cq_trybots)
315
316 if extra_fyi_trybots:
317 self._TriggerExtraTrybots(extra_fyi_trybots)
318
319 # Mark the CL to be committed if requested
320 if should_commit:
321 self._RunCommand(['git', 'cl', 'set-commit'])
geofflang527982f92015-09-15 20:39:24322
kbr9fe00f62015-05-21 21:09:50323 cl_info = self._GetCLInfo()
324 print 'Issue: %d URL: %s' % (cl_info.issue, cl_info.url)
325
326 # Checkout master again.
327 self._RunCommand(['git', 'checkout', 'master'])
328 print 'Roll branch left as ' + ROLL_BRANCH_NAME
329 return 0
330
331 def _UpdateDep(self, deps_filename, dep_relative_to_src, commit_info):
geofflang44a4fb3e2015-06-09 21:45:37332 dep_name = _PosixPath(os.path.join('src', dep_relative_to_src))
kbr9fe00f62015-05-21 21:09:50333
jmadill241d77b2015-05-25 19:21:54334 # roll_dep_svn.py relies on cwd being the Chromium checkout, so let's
kbr9fe00f62015-05-21 21:09:50335 # temporarily change the working directory and then change back.
336 cwd = os.getcwd()
337 os.chdir(os.path.dirname(deps_filename))
jmadill241d77b2015-05-25 19:21:54338 roll_dep_svn.update_deps(deps_filename, dep_relative_to_src, dep_name,
339 commit_info.git_commit, '')
kbr9fe00f62015-05-21 21:09:50340 os.chdir(cwd)
341
342 def _DeleteRollBranch(self):
343 self._RunCommand(['git', 'checkout', 'master'])
344 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
345 logging.debug('Deleted the local roll branch (%s)', ROLL_BRANCH_NAME)
346
347
348 def _GetBranches(self):
349 """Returns a tuple of active,branches.
350
351 The 'active' is the name of the currently active branch and 'branches' is a
352 list of all branches.
353 """
354 lines = self._RunCommand(['git', 'branch']).split('\n')
355 branches = []
356 active = ''
357 for l in lines:
358 if '*' in l:
359 # The assumption is that the first char will always be the '*'.
360 active = l[1:].strip()
361 branches.append(active)
362 else:
363 b = l.strip()
364 if b:
365 branches.append(b)
366 return (active, branches)
367
368 def Abort(self):
369 active_branch, branches = self._GetBranches()
370 if active_branch == ROLL_BRANCH_NAME:
371 active_branch = 'master'
372 if ROLL_BRANCH_NAME in branches:
373 print 'Aborting pending roll.'
374 self._RunCommand(['git', 'checkout', ROLL_BRANCH_NAME])
375 # Ignore an error here in case an issue wasn't created for some reason.
376 self._RunCommand(['git', 'cl', 'set_close'], ignore_exit_code=True)
377 self._RunCommand(['git', 'checkout', active_branch])
378 self._RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
379 return 0
380
381
382def main():
kbr9fe00f62015-05-21 21:09:50383 parser = argparse.ArgumentParser(
384 description='Auto-generates a CL containing an ANGLE roll.')
385 parser.add_argument('--abort',
386 help=('Aborts a previously prepared roll. '
387 'Closes any associated issues and deletes the roll branches'),
388 action='store_true')
389 parser.add_argument('--ignore-checks', action='store_true', default=False,
390 help=('Skips checks for being on the master branch, dirty workspaces and '
391 'the updating of the checkout. Will still delete and create local '
392 'Git branches.'))
geofflang896099f62016-02-12 15:53:28393 parser.add_argument('--tbr', help='Add a TBR to the commit message.')
394 parser.add_argument('--commit', action='store_true', default=False,
395 help='Submit the roll to the CQ after uploading.')
kbr9fe00f62015-05-21 21:09:50396 parser.add_argument('-v', '--verbose', action='store_true', default=False,
397 help='Be extra verbose in printing of log messages.')
398 args = parser.parse_args()
399
400 if args.verbose:
401 logging.basicConfig(level=logging.DEBUG)
402 else:
403 logging.basicConfig(level=logging.ERROR)
404
405 autoroller = AutoRoller(SRC_DIR)
406 if args.abort:
407 return autoroller.Abort()
408 else:
geofflang896099f62016-02-12 15:53:28409 return autoroller.PrepareRoll(args.ignore_checks, args.tbr, args.commit)
kbr9fe00f62015-05-21 21:09:50410
411if __name__ == '__main__':
412 sys.exit(main())