Path: blob/main_old/scripts/roll_chromium_deps.py
1693 views
#!/usr/bin/env python1# Copyright 2019 The ANGLE project authors. All Rights Reserved.2#3# Use of this source code is governed by a BSD-style license4# that can be found in the LICENSE file in the root of the source5# tree. An additional intellectual property rights grant can be found6# in the file PATENTS. All contributing project authors may7# be found in the AUTHORS file in the root of the source tree.89# This is a modified copy of the script in10# https://webrtc.googlesource.com/src/+/master/tools_webrtc/autoroller/roll_deps.py11# customized for ANGLE.12"""Script to automatically roll Chromium dependencies in the ANGLE DEPS file."""1314import argparse15import base6416import collections17import logging18import os19import platform20import re21import subprocess22import sys23import urllib2242526def FindSrcDirPath():27"""Returns the abs path to the root dir of the project."""28# Special cased for ANGLE.29return os.path.dirname(os.path.abspath(os.path.join(__file__, '..')))303132ANGLE_CHROMIUM_DEPS = [33'build',34'buildtools',35'buildtools/clang_format/script',36'buildtools/linux64',37'buildtools/mac',38'buildtools/third_party/libc++/trunk',39'buildtools/third_party/libc++abi/trunk',40'buildtools/win',41'testing',42'third_party/abseil-cpp',43'third_party/android_build_tools',44'third_party/android_build_tools/aapt2',45'third_party/android_build_tools/art',46'third_party/android_build_tools/bundletool',47'third_party/android_deps',48'third_party/android_ndk',49'third_party/android_platform',50'third_party/android_sdk',51'third_party/android_sdk/androidx_browser/src',52'third_party/android_sdk/public',53'third_party/android_system_sdk',54'third_party/bazel',55'third_party/catapult',56'third_party/colorama/src',57'third_party/depot_tools',58'third_party/ijar',59'third_party/jdk',60'third_party/jdk/extras',61'third_party/jinja2',62'third_party/libjpeg_turbo',63'third_party/markupsafe',64'third_party/nasm',65'third_party/proguard',66'third_party/protobuf',67'third_party/Python-Markdown',68'third_party/qemu-linux-x64',69'third_party/qemu-mac-x64',70'third_party/r8',71'third_party/requests/src',72'third_party/six',73'third_party/turbine',74'third_party/zlib',75'tools/android/errorprone_plugin',76'tools/clang',77'tools/clang/dsymutil',78'tools/luci-go',79'tools/mb',80'tools/md_browser',81'tools/memory',82'tools/perf',83'tools/protoc_wrapper',84'tools/python',85'tools/skia_goldctl/linux',86'tools/skia_goldctl/mac',87'tools/skia_goldctl/win',88]8990ANGLE_URL = 'https://chromium.googlesource.com/angle/angle'91CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src'92CHROMIUM_COMMIT_TEMPLATE = CHROMIUM_SRC_URL + '/+/%s'93CHROMIUM_LOG_TEMPLATE = CHROMIUM_SRC_URL + '/+log/%s'94CHROMIUM_FILE_TEMPLATE = CHROMIUM_SRC_URL + '/+/%s/%s'9596COMMIT_POSITION_RE = re.compile('^Cr-Commit-Position: .*#([0-9]+).*$')97CLANG_REVISION_RE = re.compile(r'^CLANG_REVISION = \'([-0-9a-z]+)\'')98ROLL_BRANCH_NAME = 'roll_chromium_revision'99100SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))101CHECKOUT_SRC_DIR = FindSrcDirPath()102CHECKOUT_ROOT_DIR = CHECKOUT_SRC_DIR103104# Copied from tools/android/roll/android_deps/.../BuildConfigGenerator.groovy.105ANDROID_DEPS_START = r'=== ANDROID_DEPS Generated Code Start ==='106ANDROID_DEPS_END = r'=== ANDROID_DEPS Generated Code End ==='107# Location of automically gathered android deps.108ANDROID_DEPS_PATH = 'src/third_party/android_deps/'109110NOTIFY_EMAIL = '[email protected]'111112CLANG_TOOLS_URL = 'https://chromium.googlesource.com/chromium/src/tools/clang'113CLANG_FILE_TEMPLATE = CLANG_TOOLS_URL + '/+/%s/%s'114115CLANG_TOOLS_PATH = 'tools/clang'116CLANG_UPDATE_SCRIPT_URL_PATH = 'scripts/update.py'117CLANG_UPDATE_SCRIPT_LOCAL_PATH = os.path.join(CHECKOUT_SRC_DIR, 'tools', 'clang', 'scripts',118'update.py')119120DepsEntry = collections.namedtuple('DepsEntry', 'path url revision')121ChangedDep = collections.namedtuple('ChangedDep', 'path url current_rev new_rev')122ClangChange = collections.namedtuple('ClangChange', 'mirror_change clang_change')123CipdDepsEntry = collections.namedtuple('CipdDepsEntry', 'path packages')124ChangedCipdPackage = collections.namedtuple('ChangedCipdPackage',125'path package current_version new_version')126127ChromiumRevisionUpdate = collections.namedtuple('ChromiumRevisionUpdate', ('current_chromium_rev '128'new_chromium_rev '))129130131def AddDepotToolsToPath():132sys.path.append(os.path.join(CHECKOUT_SRC_DIR, 'build'))133import find_depot_tools134find_depot_tools.add_depot_tools_to_path()135136137class RollError(Exception):138pass139140141def StrExpansion():142return lambda str_value: str_value143144145def VarLookup(local_scope):146return lambda var_name: local_scope['vars'][var_name]147148149def ParseDepsDict(deps_content):150local_scope = {}151global_scope = {152'Str': StrExpansion(),153'Var': VarLookup(local_scope),154'deps_os': {},155}156exec (deps_content, global_scope, local_scope)157return local_scope158159160def ParseLocalDepsFile(filename):161with open(filename, 'rb') as f:162deps_content = f.read()163return ParseDepsDict(deps_content)164165166def ParseCommitPosition(commit_message):167for line in reversed(commit_message.splitlines()):168m = COMMIT_POSITION_RE.match(line.strip())169if m:170return int(m.group(1))171logging.error('Failed to parse commit position id from:\n%s\n', commit_message)172sys.exit(-1)173174175def _RunCommand(command, working_dir=None, ignore_exit_code=False, extra_env=None,176input_data=None):177"""Runs a command and returns the output from that command.178179If the command fails (exit code != 0), the function will exit the process.180181Returns:182A tuple containing the stdout and stderr outputs as strings.183"""184working_dir = working_dir or CHECKOUT_SRC_DIR185logging.debug('CMD: %s CWD: %s', ' '.join(command), working_dir)186env = os.environ.copy()187if extra_env:188assert all(isinstance(value, str) for value in extra_env.values())189logging.debug('extra env: %s', extra_env)190env.update(extra_env)191p = subprocess.Popen(192command,193stdin=subprocess.PIPE,194stdout=subprocess.PIPE,195stderr=subprocess.PIPE,196env=env,197cwd=working_dir,198universal_newlines=True)199std_output, err_output = p.communicate(input_data)200p.stdout.close()201p.stderr.close()202if not ignore_exit_code and p.returncode != 0:203logging.error('Command failed: %s\n'204'stdout:\n%s\n'205'stderr:\n%s\n', ' '.join(command), std_output, err_output)206sys.exit(p.returncode)207return std_output, err_output208209210def _GetBranches():211"""Returns a tuple of active,branches.212213The 'active' is the name of the currently active branch and 'branches' is a214list of all branches.215"""216lines = _RunCommand(['git', 'branch'])[0].split('\n')217branches = []218active = ''219for line in lines:220if '*' in line:221# The assumption is that the first char will always be the '*'.222active = line[1:].strip()223branches.append(active)224else:225branch = line.strip()226if branch:227branches.append(branch)228return active, branches229230231def _ReadGitilesContent(url):232# Download and decode BASE64 content until233# https://code.google.com/p/gitiles/issues/detail?id=7 is fixed.234logging.debug('Reading gitiles URL %s' % url)235base64_content = ReadUrlContent(url + '?format=TEXT')236return base64.b64decode(base64_content[0])237238239def ReadRemoteCrFile(path_below_src, revision):240"""Reads a remote Chromium file of a specific revision. Returns a string."""241return _ReadGitilesContent(CHROMIUM_FILE_TEMPLATE % (revision, path_below_src))242243244def ReadRemoteCrCommit(revision):245"""Reads a remote Chromium commit message. Returns a string."""246return _ReadGitilesContent(CHROMIUM_COMMIT_TEMPLATE % revision)247248249def ReadRemoteClangFile(path_below_src, revision):250"""Reads a remote Clang file of a specific revision. Returns a string."""251return _ReadGitilesContent(CLANG_FILE_TEMPLATE % (revision, path_below_src))252253254def ReadUrlContent(url):255"""Connect to a remote host and read the contents. Returns a list of lines."""256conn = urllib2.urlopen(url)257try:258return conn.readlines()259except IOError as e:260logging.exception('Error connecting to %s. Error: %s', url, e)261raise262finally:263conn.close()264265266def GetMatchingDepsEntries(depsentry_dict, dir_path):267"""Gets all deps entries matching the provided path.268269This list may contain more than one DepsEntry object.270Example: dir_path='src/testing' would give results containing both271'src/testing/gtest' and 'src/testing/gmock' deps entries for Chromium's DEPS.272Example 2: dir_path='src/build' should return 'src/build' but not273'src/buildtools'.274275Returns:276A list of DepsEntry objects.277"""278result = []279for path, depsentry in depsentry_dict.iteritems():280if path == dir_path:281result.append(depsentry)282else:283parts = path.split('/')284if all(part == parts[i] for i, part in enumerate(dir_path.split('/'))):285result.append(depsentry)286return result287288289def BuildDepsentryDict(deps_dict):290"""Builds a dict of paths to DepsEntry objects from a raw parsed deps dict."""291result = {}292293def AddDepsEntries(deps_subdict):294for path, dep in deps_subdict.iteritems():295if path in result:296continue297if not isinstance(dep, dict):298dep = {'url': dep}299if dep.get('dep_type') == 'cipd':300result[path] = CipdDepsEntry(path, dep['packages'])301else:302if '@' not in dep['url']:303continue304url, revision = dep['url'].split('@')305result[path] = DepsEntry(path, url, revision)306307AddDepsEntries(deps_dict['deps'])308for deps_os in ['win', 'mac', 'unix', 'android', 'ios', 'unix']:309AddDepsEntries(deps_dict.get('deps_os', {}).get(deps_os, {}))310return result311312313def _FindChangedCipdPackages(path, old_pkgs, new_pkgs):314pkgs_equal = ({p['package'] for p in old_pkgs} == {p['package'] for p in new_pkgs})315assert pkgs_equal, ('Old: %s\n New: %s.\nYou need to do a manual roll '316'and remove/add entries in DEPS so the old and new '317'list match.' % (old_pkgs, new_pkgs))318for old_pkg in old_pkgs:319for new_pkg in new_pkgs:320old_version = old_pkg['version']321new_version = new_pkg['version']322if (old_pkg['package'] == new_pkg['package'] and old_version != new_version):323logging.debug('Roll dependency %s to %s', path, new_version)324yield ChangedCipdPackage(path, old_pkg['package'], old_version, new_version)325326327def _FindNewDeps(old, new):328""" Gather dependencies only in |new| and return corresponding paths. """329old_entries = set(BuildDepsentryDict(old))330new_entries = set(BuildDepsentryDict(new))331return [path for path in new_entries - old_entries if path in ANGLE_CHROMIUM_DEPS]332333334def CalculateChangedDeps(angle_deps, new_cr_deps):335"""336Calculate changed deps entries based on entries defined in the ANGLE DEPS337file:338- If a shared dependency with the Chromium DEPS file: roll it to the same339revision as Chromium (i.e. entry in the new_cr_deps dict)340- If it's a Chromium sub-directory, roll it to the HEAD revision (notice341this means it may be ahead of the chromium_revision, but generally these342should be close).343- If it's another DEPS entry (not shared with Chromium), roll it to HEAD344unless it's configured to be skipped.345346Returns:347A list of ChangedDep objects representing the changed deps.348"""349350def ChromeURL(angle_deps_entry):351# Perform variable substitutions.352# This is a hack to get around the unsupported way this script parses DEPS.353# A better fix would be to use the gclient APIs to query and update DEPS.354# However this is complicated by how this script downloads DEPS remotely.355return angle_deps_entry.url.replace('{chromium_git}', 'https://chromium.googlesource.com')356357result = []358angle_entries = BuildDepsentryDict(angle_deps)359new_cr_entries = BuildDepsentryDict(new_cr_deps)360for path, angle_deps_entry in angle_entries.iteritems():361if path not in ANGLE_CHROMIUM_DEPS:362continue363364# All ANGLE Chromium dependencies are located in src/.365chrome_path = 'src/%s' % path366cr_deps_entry = new_cr_entries.get(chrome_path)367368if cr_deps_entry:369assert type(cr_deps_entry) is type(angle_deps_entry)370371if isinstance(cr_deps_entry, CipdDepsEntry):372result.extend(373_FindChangedCipdPackages(path, angle_deps_entry.packages,374cr_deps_entry.packages))375continue376377# Use the revision from Chromium's DEPS file.378new_rev = cr_deps_entry.revision379assert ChromeURL(angle_deps_entry) == cr_deps_entry.url, (380'ANGLE DEPS entry %s has a different URL (%s) than Chromium (%s).' %381(path, ChromeURL(angle_deps_entry), cr_deps_entry.url))382else:383if isinstance(angle_deps_entry, DepsEntry):384# Use the HEAD of the deps repo.385stdout, _ = _RunCommand(['git', 'ls-remote', ChromeURL(angle_deps_entry), 'HEAD'])386new_rev = stdout.strip().split('\t')[0]387else:388# The dependency has been removed from chromium.389# This is handled by FindRemovedDeps.390continue391392# Check if an update is necessary.393if angle_deps_entry.revision != new_rev:394logging.debug('Roll dependency %s to %s', path, new_rev)395result.append(396ChangedDep(path, ChromeURL(angle_deps_entry), angle_deps_entry.revision, new_rev))397return sorted(result)398399400def CalculateChangedClang(changed_deps, autoroll):401mirror_change = [change for change in changed_deps if change.path == CLANG_TOOLS_PATH]402if not mirror_change:403return None404405mirror_change = mirror_change[0]406407def GetClangRev(lines):408for line in lines:409match = CLANG_REVISION_RE.match(line)410if match:411return match.group(1)412raise RollError('Could not parse Clang revision!')413414old_clang_update_py = ReadRemoteClangFile(CLANG_UPDATE_SCRIPT_URL_PATH,415mirror_change.current_rev).splitlines()416old_clang_rev = GetClangRev(old_clang_update_py)417logging.debug('Found old clang rev: %s' % old_clang_rev)418419new_clang_update_py = ReadRemoteClangFile(CLANG_UPDATE_SCRIPT_URL_PATH,420mirror_change.new_rev).splitlines()421new_clang_rev = GetClangRev(new_clang_update_py)422logging.debug('Found new clang rev: %s' % new_clang_rev)423clang_change = ChangedDep(CLANG_UPDATE_SCRIPT_LOCAL_PATH, None, old_clang_rev, new_clang_rev)424return ClangChange(mirror_change, clang_change)425426427def GenerateCommitMessage(428rev_update,429current_commit_pos,430new_commit_pos,431changed_deps_list,432autoroll,433clang_change,434):435current_cr_rev = rev_update.current_chromium_rev[0:10]436new_cr_rev = rev_update.new_chromium_rev[0:10]437rev_interval = '%s..%s' % (current_cr_rev, new_cr_rev)438git_number_interval = '%s:%s' % (current_commit_pos, new_commit_pos)439440commit_msg = []441# Autoroll already adds chromium_revision changes to commit message442if not autoroll:443commit_msg.extend([444'Roll chromium_revision %s (%s)\n' % (rev_interval, git_number_interval),445'Change log: %s' % (CHROMIUM_LOG_TEMPLATE % rev_interval),446'Full diff: %s\n' % (CHROMIUM_COMMIT_TEMPLATE % rev_interval)447])448449def Section(adjective, deps):450noun = 'dependency' if len(deps) == 1 else 'dependencies'451commit_msg.append('%s %s' % (adjective, noun))452453tbr_authors = ''454if changed_deps_list:455Section('Changed', changed_deps_list)456457for c in changed_deps_list:458if isinstance(c, ChangedCipdPackage):459commit_msg.append('* %s: %s..%s' % (c.path, c.current_version, c.new_version))460else:461commit_msg.append('* %s: %s/+log/%s..%s' %462(c.path, c.url, c.current_rev[0:10], c.new_rev[0:10]))463464if changed_deps_list:465# rev_interval is empty for autoroll, since we are starting from a state466# in which chromium_revision is already modified in DEPS467if not autoroll:468change_url = CHROMIUM_FILE_TEMPLATE % (rev_interval, 'DEPS')469commit_msg.append('DEPS diff: %s\n' % change_url)470else:471commit_msg.append('No dependencies changed.')472473c = clang_change474if (c and (c.clang_change.current_rev != c.clang_change.new_rev)):475commit_msg.append('Clang version changed %s:%s' %476(c.clang_change.current_rev, c.clang_change.new_rev))477478rev_clang = rev_interval = '%s..%s' % (c.mirror_change.current_rev,479c.mirror_change.new_rev)480change_url = CLANG_FILE_TEMPLATE % (rev_clang, CLANG_UPDATE_SCRIPT_URL_PATH)481commit_msg.append('Details: %s\n' % change_url)482else:483commit_msg.append('No update to Clang.\n')484485# Autoroll takes care of BUG and TBR in commit message486if not autoroll:487# TBR needs to be non-empty for Gerrit to process it.488git_author = _RunCommand(['git', 'config', 'user.email'],489working_dir=CHECKOUT_SRC_DIR)[0].splitlines()[0]490tbr_authors = git_author + ',' + tbr_authors491492commit_msg.append('TBR=%s' % tbr_authors)493commit_msg.append('BUG=None')494495return '\n'.join(commit_msg)496497498def UpdateDepsFile(deps_filename, rev_update, changed_deps, new_cr_content, autoroll):499"""Update the DEPS file with the new revision."""500501with open(deps_filename, 'rb') as deps_file:502deps_content = deps_file.read()503# Autoroll takes care of updating 'chromium_revision', thus we don't need to.504if not autoroll:505# Update the chromium_revision variable.506deps_content = deps_content.replace(rev_update.current_chromium_rev,507rev_update.new_chromium_rev)508509# Add and remove dependencies. For now: only generated android deps.510# Since gclient cannot add or remove deps, we rely on the fact that511# these android deps are located in one place to copy/paste.512deps_re = re.compile(ANDROID_DEPS_START + '.*' + ANDROID_DEPS_END, re.DOTALL)513new_deps = deps_re.search(new_cr_content)514old_deps = deps_re.search(deps_content)515if not new_deps or not old_deps:516faulty = 'Chromium' if not new_deps else 'ANGLE'517raise RollError('Was expecting to find "%s" and "%s"\n'518'in %s DEPS' % (ANDROID_DEPS_START, ANDROID_DEPS_END, faulty))519520replacement = new_deps.group(0).replace('src/third_party/android_deps',521'third_party/android_deps')522replacement = replacement.replace('checkout_android',523'checkout_android and not build_with_chromium')524525deps_content = deps_re.sub(replacement, deps_content)526527with open(deps_filename, 'wb') as deps_file:528deps_file.write(deps_content)529530# Update each individual DEPS entry.531for dep in changed_deps:532# We don't sync deps on autoroller, so ignore missing local deps533if not autoroll:534local_dep_dir = os.path.join(CHECKOUT_ROOT_DIR, dep.path)535if not os.path.isdir(local_dep_dir):536raise RollError('Cannot find local directory %s. Either run\n'537'gclient sync --deps=all\n'538'or make sure the .gclient file for your solution contains all '539'platforms in the target_os list, i.e.\n'540'target_os = ["android", "unix", "mac", "ios", "win"];\n'541'Then run "gclient sync" again.' % local_dep_dir)542if isinstance(dep, ChangedCipdPackage):543package = dep.package.format() # Eliminate double curly brackets544update = '%s:%s@%s' % (dep.path, package, dep.new_version)545else:546update = '%s@%s' % (dep.path, dep.new_rev)547gclient_cmd = 'gclient'548if platform.system() == 'Windows':549gclient_cmd += '.bat'550_RunCommand([gclient_cmd, 'setdep', '--revision', update], working_dir=CHECKOUT_SRC_DIR)551552553def _IsTreeClean():554stdout, _ = _RunCommand(['git', 'status', '--porcelain'])555if len(stdout) == 0:556return True557558logging.error('Dirty/unversioned files:\n%s', stdout)559return False560561562def _EnsureUpdatedMasterBranch(dry_run):563current_branch = _RunCommand(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])[0].splitlines()[0]564if current_branch != 'master':565logging.error('Please checkout the master branch and re-run this script.')566if not dry_run:567sys.exit(-1)568569logging.info('Updating master branch...')570_RunCommand(['git', 'pull'])571572573def _CreateRollBranch(dry_run):574logging.info('Creating roll branch: %s', ROLL_BRANCH_NAME)575if not dry_run:576_RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])577578579def _RemovePreviousRollBranch(dry_run):580active_branch, branches = _GetBranches()581if active_branch == ROLL_BRANCH_NAME:582active_branch = 'master'583if ROLL_BRANCH_NAME in branches:584logging.info('Removing previous roll branch (%s)', ROLL_BRANCH_NAME)585if not dry_run:586_RunCommand(['git', 'checkout', active_branch])587_RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])588589590def _LocalCommit(commit_msg, dry_run):591logging.info('Committing changes locally.')592if not dry_run:593_RunCommand(['git', 'add', '--update', '.'])594_RunCommand(['git', 'commit', '-m', commit_msg])595596597def _LocalCommitAmend(commit_msg, dry_run):598logging.info('Amending changes to local commit.')599if not dry_run:600old_commit_msg = _RunCommand(['git', 'log', '-1', '--pretty=%B'])[0].strip()601logging.debug('Existing commit message:\n%s\n', old_commit_msg)602603bug_index = old_commit_msg.rfind('Bug:')604if bug_index == -1:605logging.error('"Bug:" not found in commit message.')606if not dry_run:607sys.exit(-1)608new_commit_msg = old_commit_msg[:bug_index] + commit_msg + '\n' + old_commit_msg[bug_index:]609610_RunCommand(['git', 'commit', '-a', '--amend', '-m', new_commit_msg])611612613def ChooseCQMode(skip_cq, cq_over, current_commit_pos, new_commit_pos):614if skip_cq:615return 0616if (new_commit_pos - current_commit_pos) < cq_over:617return 1618return 2619620621def _UploadCL(commit_queue_mode):622"""Upload the committed changes as a changelist to Gerrit.623624commit_queue_mode:625- 2: Submit to commit queue.626- 1: Run trybots but do not submit to CQ.627- 0: Skip CQ, upload only.628"""629cmd = ['git', 'cl', 'upload', '--force', '--bypass-hooks', '--send-mail']630cmd.extend(['--cc', NOTIFY_EMAIL])631if commit_queue_mode >= 2:632logging.info('Sending the CL to the CQ...')633cmd.extend(['--use-commit-queue'])634elif commit_queue_mode >= 1:635logging.info('Starting CQ dry run...')636cmd.extend(['--cq-dry-run'])637extra_env = {638'EDITOR': 'true',639'SKIP_GCE_AUTH_FOR_GIT': '1',640}641stdout, stderr = _RunCommand(cmd, extra_env=extra_env)642logging.debug('Output from "git cl upload":\nstdout:\n%s\n\nstderr:\n%s', stdout, stderr)643644645def GetRollRevisionRanges(opts, angle_deps):646current_cr_rev = angle_deps['vars']['chromium_revision']647new_cr_rev = opts.revision648if not new_cr_rev:649stdout, _ = _RunCommand(['git', 'ls-remote', CHROMIUM_SRC_URL, 'HEAD'])650head_rev = stdout.strip().split('\t')[0]651logging.info('No revision specified. Using HEAD: %s', head_rev)652new_cr_rev = head_rev653654return ChromiumRevisionUpdate(current_cr_rev, new_cr_rev)655656657def main():658p = argparse.ArgumentParser()659p.add_argument(660'--clean',661action='store_true',662default=False,663help='Removes any previous local roll branch.')664p.add_argument(665'-r',666'--revision',667help=('Chromium Git revision to roll to. Defaults to the '668'Chromium HEAD revision if omitted.'))669p.add_argument(670'--dry-run',671action='store_true',672default=False,673help=('Calculate changes and modify DEPS, but don\'t create '674'any local branch, commit, upload CL or send any '675'tryjobs.'))676p.add_argument(677'-i',678'--ignore-unclean-workdir',679action='store_true',680default=False,681help=('Ignore if the current branch is not master or if there '682'are uncommitted changes (default: %(default)s).'))683grp = p.add_mutually_exclusive_group()684grp.add_argument(685'--skip-cq',686action='store_true',687default=False,688help='Skip sending the CL to the CQ (default: %(default)s)')689grp.add_argument(690'--cq-over',691type=int,692default=1,693help=('Commit queue dry run if the revision difference '694'is below this number (default: %(default)s)'))695grp.add_argument(696'--autoroll',697action='store_true',698default=False,699help='Autoroller mode - amend existing commit, '700'do not create nor upload a CL (default: %(default)s)')701p.add_argument(702'-v',703'--verbose',704action='store_true',705default=False,706help='Be extra verbose in printing of log messages.')707opts = p.parse_args()708709if opts.verbose:710logging.basicConfig(level=logging.DEBUG)711else:712logging.basicConfig(level=logging.INFO)713714# We don't have locally sync'ed deps on autoroller,715# so trust it to have depot_tools in path716if not opts.autoroll:717AddDepotToolsToPath()718719if not opts.ignore_unclean_workdir and not _IsTreeClean():720logging.error('Please clean your local checkout first.')721return 1722723if opts.clean:724_RemovePreviousRollBranch(opts.dry_run)725726if not opts.ignore_unclean_workdir:727_EnsureUpdatedMasterBranch(opts.dry_run)728729deps_filename = os.path.join(CHECKOUT_SRC_DIR, 'DEPS')730angle_deps = ParseLocalDepsFile(deps_filename)731732rev_update = GetRollRevisionRanges(opts, angle_deps)733734current_commit_pos = ParseCommitPosition(ReadRemoteCrCommit(rev_update.current_chromium_rev))735new_commit_pos = ParseCommitPosition(ReadRemoteCrCommit(rev_update.new_chromium_rev))736737new_cr_content = ReadRemoteCrFile('DEPS', rev_update.new_chromium_rev)738new_cr_deps = ParseDepsDict(new_cr_content)739changed_deps = CalculateChangedDeps(angle_deps, new_cr_deps)740clang_change = CalculateChangedClang(changed_deps, opts.autoroll)741commit_msg = GenerateCommitMessage(rev_update, current_commit_pos, new_commit_pos,742changed_deps, opts.autoroll, clang_change)743logging.debug('Commit message:\n%s', commit_msg)744745# We are updating a commit that autoroll has created, using existing branch746if not opts.autoroll:747_CreateRollBranch(opts.dry_run)748749if not opts.dry_run:750UpdateDepsFile(deps_filename, rev_update, changed_deps, new_cr_content, opts.autoroll)751752if opts.autoroll:753_LocalCommitAmend(commit_msg, opts.dry_run)754else:755if _IsTreeClean():756logging.info("No DEPS changes detected, skipping CL creation.")757else:758_LocalCommit(commit_msg, opts.dry_run)759commit_queue_mode = ChooseCQMode(opts.skip_cq, opts.cq_over, current_commit_pos,760new_commit_pos)761logging.info('Uploading CL...')762if not opts.dry_run:763_UploadCL(commit_queue_mode)764return 0765766767if __name__ == '__main__':768sys.exit(main())769770771