roll_deps.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #!/usr/bin/env python
  2. # Copyright 2017 The LibYuv Project Authors. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style license
  5. # that can be found in the LICENSE file in the root of the source
  6. # tree. An additional intellectual property rights grant can be found
  7. # in the file PATENTS. All contributing project authors may
  8. # be found in the AUTHORS file in the root of the source tree.
  9. # This is a modified copy of the script in
  10. # https://webrtc.googlesource.com/src/+/master/tools_webrtc/autoroller/roll_deps.py
  11. # customized for libyuv.
  12. """Script to automatically roll dependencies in the libyuv DEPS file."""
  13. import argparse
  14. import base64
  15. import collections
  16. import logging
  17. import os
  18. import re
  19. import subprocess
  20. import sys
  21. import urllib2
  22. # Skip these dependencies (list without solution name prefix).
  23. DONT_AUTOROLL_THESE = [
  24. 'src/third_party/gflags/src',
  25. ]
  26. LIBYUV_URL = 'https://chromium.googlesource.com/libyuv/libyuv'
  27. CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src'
  28. CHROMIUM_COMMIT_TEMPLATE = CHROMIUM_SRC_URL + '/+/%s'
  29. CHROMIUM_LOG_TEMPLATE = CHROMIUM_SRC_URL + '/+log/%s'
  30. CHROMIUM_FILE_TEMPLATE = CHROMIUM_SRC_URL + '/+/%s/%s'
  31. COMMIT_POSITION_RE = re.compile('^Cr-Commit-Position: .*#([0-9]+).*$')
  32. CLANG_REVISION_RE = re.compile(r'^CLANG_REVISION = \'([0-9a-z]+)\'$')
  33. ROLL_BRANCH_NAME = 'roll_chromium_revision'
  34. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  35. CHECKOUT_SRC_DIR = os.path.realpath(os.path.join(SCRIPT_DIR, os.pardir,
  36. os.pardir))
  37. CHECKOUT_ROOT_DIR = os.path.realpath(os.path.join(CHECKOUT_SRC_DIR, os.pardir))
  38. sys.path.append(os.path.join(CHECKOUT_SRC_DIR, 'build'))
  39. import find_depot_tools
  40. find_depot_tools.add_depot_tools_to_path()
  41. CLANG_UPDATE_SCRIPT_URL_PATH = 'tools/clang/scripts/update.py'
  42. CLANG_UPDATE_SCRIPT_LOCAL_PATH = os.path.join(CHECKOUT_SRC_DIR, 'tools',
  43. 'clang', 'scripts', 'update.py')
  44. DepsEntry = collections.namedtuple('DepsEntry', 'path url revision')
  45. ChangedDep = collections.namedtuple('ChangedDep',
  46. 'path url current_rev new_rev')
  47. class RollError(Exception):
  48. pass
  49. def VarLookup(local_scope):
  50. return lambda var_name: local_scope['vars'][var_name]
  51. def ParseDepsDict(deps_content):
  52. local_scope = {}
  53. global_scope = {
  54. 'Var': VarLookup(local_scope),
  55. 'deps_os': {},
  56. }
  57. exec(deps_content, global_scope, local_scope)
  58. return local_scope
  59. def ParseLocalDepsFile(filename):
  60. with open(filename, 'rb') as f:
  61. deps_content = f.read()
  62. return ParseDepsDict(deps_content)
  63. def ParseRemoteCrDepsFile(revision):
  64. deps_content = ReadRemoteCrFile('DEPS', revision)
  65. return ParseDepsDict(deps_content)
  66. def ParseCommitPosition(commit_message):
  67. for line in reversed(commit_message.splitlines()):
  68. m = COMMIT_POSITION_RE.match(line.strip())
  69. if m:
  70. return int(m.group(1))
  71. logging.error('Failed to parse commit position id from:\n%s\n',
  72. commit_message)
  73. sys.exit(-1)
  74. def _RunCommand(command, working_dir=None, ignore_exit_code=False,
  75. extra_env=None):
  76. """Runs a command and returns the output from that command.
  77. If the command fails (exit code != 0), the function will exit the process.
  78. Returns:
  79. A tuple containing the stdout and stderr outputs as strings.
  80. """
  81. working_dir = working_dir or CHECKOUT_SRC_DIR
  82. logging.debug('CMD: %s CWD: %s', ' '.join(command), working_dir)
  83. env = os.environ.copy()
  84. if extra_env:
  85. assert all(isinstance(value, str) for value in extra_env.values())
  86. logging.debug('extra env: %s', extra_env)
  87. env.update(extra_env)
  88. p = subprocess.Popen(command, stdout=subprocess.PIPE,
  89. stderr=subprocess.PIPE, env=env,
  90. cwd=working_dir, universal_newlines=True)
  91. std_output = p.stdout.read()
  92. err_output = p.stderr.read()
  93. p.wait()
  94. p.stdout.close()
  95. p.stderr.close()
  96. if not ignore_exit_code and p.returncode != 0:
  97. logging.error('Command failed: %s\n'
  98. 'stdout:\n%s\n'
  99. 'stderr:\n%s\n', ' '.join(command), std_output, err_output)
  100. sys.exit(p.returncode)
  101. return std_output, err_output
  102. def _GetBranches():
  103. """Returns a tuple of active,branches.
  104. The 'active' is the name of the currently active branch and 'branches' is a
  105. list of all branches.
  106. """
  107. lines = _RunCommand(['git', 'branch'])[0].split('\n')
  108. branches = []
  109. active = ''
  110. for line in lines:
  111. if '*' in line:
  112. # The assumption is that the first char will always be the '*'.
  113. active = line[1:].strip()
  114. branches.append(active)
  115. else:
  116. branch = line.strip()
  117. if branch:
  118. branches.append(branch)
  119. return active, branches
  120. def _ReadGitilesContent(url):
  121. # Download and decode BASE64 content until
  122. # https://code.google.com/p/gitiles/issues/detail?id=7 is fixed.
  123. base64_content = ReadUrlContent(url + '?format=TEXT')
  124. return base64.b64decode(base64_content[0])
  125. def ReadRemoteCrFile(path_below_src, revision):
  126. """Reads a remote Chromium file of a specific revision. Returns a string."""
  127. return _ReadGitilesContent(CHROMIUM_FILE_TEMPLATE % (revision,
  128. path_below_src))
  129. def ReadRemoteCrCommit(revision):
  130. """Reads a remote Chromium commit message. Returns a string."""
  131. return _ReadGitilesContent(CHROMIUM_COMMIT_TEMPLATE % revision)
  132. def ReadUrlContent(url):
  133. """Connect to a remote host and read the contents. Returns a list of lines."""
  134. conn = urllib2.urlopen(url)
  135. try:
  136. return conn.readlines()
  137. except IOError as e:
  138. logging.exception('Error connecting to %s. Error: %s', url, e)
  139. raise
  140. finally:
  141. conn.close()
  142. def GetMatchingDepsEntries(depsentry_dict, dir_path):
  143. """Gets all deps entries matching the provided path.
  144. This list may contain more than one DepsEntry object.
  145. Example: dir_path='src/testing' would give results containing both
  146. 'src/testing/gtest' and 'src/testing/gmock' deps entries for Chromium's DEPS.
  147. Example 2: dir_path='src/build' should return 'src/build' but not
  148. 'src/buildtools'.
  149. Returns:
  150. A list of DepsEntry objects.
  151. """
  152. result = []
  153. for path, depsentry in depsentry_dict.iteritems():
  154. if path == dir_path:
  155. result.append(depsentry)
  156. else:
  157. parts = path.split('/')
  158. if all(part == parts[i]
  159. for i, part in enumerate(dir_path.split('/'))):
  160. result.append(depsentry)
  161. return result
  162. def BuildDepsentryDict(deps_dict):
  163. """Builds a dict of paths to DepsEntry objects from a raw parsed deps dict."""
  164. result = {}
  165. def AddDepsEntries(deps_subdict):
  166. for path, deps_url_spec in deps_subdict.iteritems():
  167. # The deps url is either an URL and a condition, or just the URL.
  168. if isinstance(deps_url_spec, dict):
  169. if deps_url_spec.get('dep_type') == 'cipd':
  170. continue
  171. deps_url = deps_url_spec['url']
  172. else:
  173. deps_url = deps_url_spec
  174. if not result.has_key(path):
  175. url, revision = deps_url.split('@') if deps_url else (None, None)
  176. result[path] = DepsEntry(path, url, revision)
  177. AddDepsEntries(deps_dict['deps'])
  178. for deps_os in ['win', 'mac', 'unix', 'android', 'ios', 'unix']:
  179. AddDepsEntries(deps_dict.get('deps_os', {}).get(deps_os, {}))
  180. return result
  181. def CalculateChangedDeps(libyuv_deps, new_cr_deps):
  182. """
  183. Calculate changed deps entries based on entries defined in the libyuv DEPS
  184. file:
  185. - If a shared dependency with the Chromium DEPS file: roll it to the same
  186. revision as Chromium (i.e. entry in the new_cr_deps dict)
  187. - If it's a Chromium sub-directory, roll it to the HEAD revision (notice
  188. this means it may be ahead of the chromium_revision, but generally these
  189. should be close).
  190. - If it's another DEPS entry (not shared with Chromium), roll it to HEAD
  191. unless it's configured to be skipped.
  192. Returns:
  193. A list of ChangedDep objects representing the changed deps.
  194. """
  195. result = []
  196. libyuv_entries = BuildDepsentryDict(libyuv_deps)
  197. new_cr_entries = BuildDepsentryDict(new_cr_deps)
  198. for path, libyuv_deps_entry in libyuv_entries.iteritems():
  199. if path in DONT_AUTOROLL_THESE:
  200. continue
  201. cr_deps_entry = new_cr_entries.get(path)
  202. if cr_deps_entry:
  203. # Use the revision from Chromium's DEPS file.
  204. new_rev = cr_deps_entry.revision
  205. assert libyuv_deps_entry.url == cr_deps_entry.url, (
  206. 'Libyuv DEPS entry %s has a different URL (%s) than Chromium (%s).' %
  207. (path, libyuv_deps_entry.url, cr_deps_entry.url))
  208. else:
  209. # Use the HEAD of the deps repo.
  210. stdout, _ = _RunCommand(['git', 'ls-remote', libyuv_deps_entry.url,
  211. 'HEAD'])
  212. new_rev = stdout.strip().split('\t')[0]
  213. # Check if an update is necessary.
  214. if libyuv_deps_entry.revision != new_rev:
  215. logging.debug('Roll dependency %s to %s', path, new_rev)
  216. result.append(ChangedDep(path, libyuv_deps_entry.url,
  217. libyuv_deps_entry.revision, new_rev))
  218. return sorted(result)
  219. def CalculateChangedClang(new_cr_rev):
  220. def GetClangRev(lines):
  221. for line in lines:
  222. match = CLANG_REVISION_RE.match(line)
  223. if match:
  224. return match.group(1)
  225. raise RollError('Could not parse Clang revision!')
  226. with open(CLANG_UPDATE_SCRIPT_LOCAL_PATH, 'rb') as f:
  227. current_lines = f.readlines()
  228. current_rev = GetClangRev(current_lines)
  229. new_clang_update_py = ReadRemoteCrFile(CLANG_UPDATE_SCRIPT_URL_PATH,
  230. new_cr_rev).splitlines()
  231. new_rev = GetClangRev(new_clang_update_py)
  232. return ChangedDep(CLANG_UPDATE_SCRIPT_LOCAL_PATH, None, current_rev, new_rev)
  233. def GenerateCommitMessage(current_cr_rev, new_cr_rev, current_commit_pos,
  234. new_commit_pos, changed_deps_list, clang_change):
  235. current_cr_rev = current_cr_rev[0:10]
  236. new_cr_rev = new_cr_rev[0:10]
  237. rev_interval = '%s..%s' % (current_cr_rev, new_cr_rev)
  238. git_number_interval = '%s:%s' % (current_commit_pos, new_commit_pos)
  239. commit_msg = ['Roll chromium_revision %s (%s)\n' % (rev_interval,
  240. git_number_interval)]
  241. commit_msg.append('Change log: %s' % (CHROMIUM_LOG_TEMPLATE % rev_interval))
  242. commit_msg.append('Full diff: %s\n' % (CHROMIUM_COMMIT_TEMPLATE %
  243. rev_interval))
  244. if changed_deps_list:
  245. commit_msg.append('Changed dependencies:')
  246. for c in changed_deps_list:
  247. commit_msg.append('* %s: %s/+log/%s..%s' % (c.path, c.url,
  248. c.current_rev[0:10],
  249. c.new_rev[0:10]))
  250. change_url = CHROMIUM_FILE_TEMPLATE % (rev_interval, 'DEPS')
  251. commit_msg.append('DEPS diff: %s\n' % change_url)
  252. else:
  253. commit_msg.append('No dependencies changed.')
  254. if clang_change.current_rev != clang_change.new_rev:
  255. commit_msg.append('Clang version changed %s:%s' %
  256. (clang_change.current_rev, clang_change.new_rev))
  257. change_url = CHROMIUM_FILE_TEMPLATE % (rev_interval,
  258. CLANG_UPDATE_SCRIPT_URL_PATH)
  259. commit_msg.append('Details: %s\n' % change_url)
  260. else:
  261. commit_msg.append('No update to Clang.\n')
  262. # TBR needs to be non-empty for Gerrit to process it.
  263. git_author = _RunCommand(['git', 'config', 'user.email'],
  264. working_dir=CHECKOUT_SRC_DIR)[0].strip()
  265. commit_msg.append('TBR=%s' % git_author)
  266. commit_msg.append('BUG=None')
  267. return '\n'.join(commit_msg)
  268. def UpdateDepsFile(deps_filename, old_cr_revision, new_cr_revision,
  269. changed_deps):
  270. """Update the DEPS file with the new revision."""
  271. # Update the chromium_revision variable.
  272. with open(deps_filename, 'rb') as deps_file:
  273. deps_content = deps_file.read()
  274. deps_content = deps_content.replace(old_cr_revision, new_cr_revision)
  275. with open(deps_filename, 'wb') as deps_file:
  276. deps_file.write(deps_content)
  277. # Update each individual DEPS entry.
  278. for dep in changed_deps:
  279. local_dep_dir = os.path.join(CHECKOUT_ROOT_DIR, dep.path)
  280. if not os.path.isdir(local_dep_dir):
  281. raise RollError(
  282. 'Cannot find local directory %s. Make sure the .gclient file\n'
  283. 'contains all platforms in the target_os list, i.e.\n'
  284. 'target_os = ["android", "unix", "mac", "ios", "win"];\n'
  285. 'Then run "gclient sync" again.' % local_dep_dir)
  286. _RunCommand(
  287. ['gclient', 'setdep', '--revision', '%s@%s' % (dep.path, dep.new_rev)],
  288. working_dir=CHECKOUT_SRC_DIR)
  289. def _IsTreeClean():
  290. stdout, _ = _RunCommand(['git', 'status', '--porcelain'])
  291. if len(stdout) == 0:
  292. return True
  293. logging.error('Dirty/unversioned files:\n%s', stdout)
  294. return False
  295. def _EnsureUpdatedMasterBranch(dry_run):
  296. current_branch = _RunCommand(
  297. ['git', 'rev-parse', '--abbrev-ref', 'HEAD'])[0].splitlines()[0]
  298. if current_branch != 'master':
  299. logging.error('Please checkout the master branch and re-run this script.')
  300. if not dry_run:
  301. sys.exit(-1)
  302. logging.info('Updating master branch...')
  303. _RunCommand(['git', 'pull'])
  304. def _CreateRollBranch(dry_run):
  305. logging.info('Creating roll branch: %s', ROLL_BRANCH_NAME)
  306. if not dry_run:
  307. _RunCommand(['git', 'checkout', '-b', ROLL_BRANCH_NAME])
  308. def _RemovePreviousRollBranch(dry_run):
  309. active_branch, branches = _GetBranches()
  310. if active_branch == ROLL_BRANCH_NAME:
  311. active_branch = 'master'
  312. if ROLL_BRANCH_NAME in branches:
  313. logging.info('Removing previous roll branch (%s)', ROLL_BRANCH_NAME)
  314. if not dry_run:
  315. _RunCommand(['git', 'checkout', active_branch])
  316. _RunCommand(['git', 'branch', '-D', ROLL_BRANCH_NAME])
  317. def _LocalCommit(commit_msg, dry_run):
  318. logging.info('Committing changes locally.')
  319. if not dry_run:
  320. _RunCommand(['git', 'add', '--update', '.'])
  321. _RunCommand(['git', 'commit', '-m', commit_msg])
  322. def ChooseCQMode(skip_cq, cq_over, current_commit_pos, new_commit_pos):
  323. if skip_cq:
  324. return 0
  325. if (new_commit_pos - current_commit_pos) < cq_over:
  326. return 1
  327. return 2
  328. def _UploadCL(commit_queue_mode):
  329. """Upload the committed changes as a changelist to Gerrit.
  330. commit_queue_mode:
  331. - 2: Submit to commit queue.
  332. - 1: Run trybots but do not submit to CQ.
  333. - 0: Skip CQ, upload only.
  334. """
  335. cmd = ['git', 'cl', 'upload', '--force', '--bypass-hooks', '--send-mail']
  336. if commit_queue_mode >= 2:
  337. logging.info('Sending the CL to the CQ...')
  338. cmd.extend(['--use-commit-queue'])
  339. elif commit_queue_mode >= 1:
  340. logging.info('Starting CQ dry run...')
  341. cmd.extend(['--cq-dry-run'])
  342. extra_env = {
  343. 'EDITOR': 'true',
  344. 'SKIP_GCE_AUTH_FOR_GIT': '1',
  345. }
  346. stdout, stderr = _RunCommand(cmd, extra_env=extra_env)
  347. logging.debug('Output from "git cl upload":\nstdout:\n%s\n\nstderr:\n%s',
  348. stdout, stderr)
  349. def main():
  350. p = argparse.ArgumentParser()
  351. p.add_argument('--clean', action='store_true', default=False,
  352. help='Removes any previous local roll branch.')
  353. p.add_argument('-r', '--revision',
  354. help=('Chromium Git revision to roll to. Defaults to the '
  355. 'Chromium HEAD revision if omitted.'))
  356. p.add_argument('--dry-run', action='store_true', default=False,
  357. help=('Calculate changes and modify DEPS, but don\'t create '
  358. 'any local branch, commit, upload CL or send any '
  359. 'tryjobs.'))
  360. p.add_argument('-i', '--ignore-unclean-workdir', action='store_true',
  361. default=False,
  362. help=('Ignore if the current branch is not master or if there '
  363. 'are uncommitted changes (default: %(default)s).'))
  364. grp = p.add_mutually_exclusive_group()
  365. grp.add_argument('--skip-cq', action='store_true', default=False,
  366. help='Skip sending the CL to the CQ (default: %(default)s)')
  367. grp.add_argument('--cq-over', type=int, default=1,
  368. help=('Commit queue dry run if the revision difference '
  369. 'is below this number (default: %(default)s)'))
  370. p.add_argument('-v', '--verbose', action='store_true', default=False,
  371. help='Be extra verbose in printing of log messages.')
  372. opts = p.parse_args()
  373. if opts.verbose:
  374. logging.basicConfig(level=logging.DEBUG)
  375. else:
  376. logging.basicConfig(level=logging.INFO)
  377. if not opts.ignore_unclean_workdir and not _IsTreeClean():
  378. logging.error('Please clean your local checkout first.')
  379. return 1
  380. if opts.clean:
  381. _RemovePreviousRollBranch(opts.dry_run)
  382. if not opts.ignore_unclean_workdir:
  383. _EnsureUpdatedMasterBranch(opts.dry_run)
  384. new_cr_rev = opts.revision
  385. if not new_cr_rev:
  386. stdout, _ = _RunCommand(['git', 'ls-remote', CHROMIUM_SRC_URL, 'HEAD'])
  387. head_rev = stdout.strip().split('\t')[0]
  388. logging.info('No revision specified. Using HEAD: %s', head_rev)
  389. new_cr_rev = head_rev
  390. deps_filename = os.path.join(CHECKOUT_SRC_DIR, 'DEPS')
  391. libyuv_deps = ParseLocalDepsFile(deps_filename)
  392. current_cr_rev = libyuv_deps['vars']['chromium_revision']
  393. current_commit_pos = ParseCommitPosition(ReadRemoteCrCommit(current_cr_rev))
  394. new_commit_pos = ParseCommitPosition(ReadRemoteCrCommit(new_cr_rev))
  395. new_cr_deps = ParseRemoteCrDepsFile(new_cr_rev)
  396. changed_deps = CalculateChangedDeps(libyuv_deps, new_cr_deps)
  397. clang_change = CalculateChangedClang(new_cr_rev)
  398. commit_msg = GenerateCommitMessage(current_cr_rev, new_cr_rev,
  399. current_commit_pos, new_commit_pos,
  400. changed_deps, clang_change)
  401. logging.debug('Commit message:\n%s', commit_msg)
  402. _CreateRollBranch(opts.dry_run)
  403. UpdateDepsFile(deps_filename, current_cr_rev, new_cr_rev, changed_deps)
  404. _LocalCommit(commit_msg, opts.dry_run)
  405. commit_queue_mode = ChooseCQMode(opts.skip_cq, opts.cq_over,
  406. current_commit_pos, new_commit_pos)
  407. logging.info('Uploading CL...')
  408. if not opts.dry_run:
  409. _UploadCL(commit_queue_mode)
  410. return 0
  411. if __name__ == '__main__':
  412. sys.exit(main())