roll_dep.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. #!/usr/bin/env python3
  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. """Rolls DEPS controlled dependency.
  6. Works only with git checkout and git dependencies. Currently this script will
  7. always roll to the tip of to origin/main.
  8. """
  9. from __future__ import print_function
  10. import argparse
  11. import itertools
  12. import os
  13. import re
  14. import subprocess2
  15. import sys
  16. import tempfile
  17. NEED_SHELL = sys.platform.startswith('win')
  18. GCLIENT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  19. 'gclient.py')
  20. # Commit subject that will be considered a roll. In the format generated by the
  21. # git log used, so it's "<year>-<month>-<day> <author> <subject>"
  22. _ROLL_SUBJECT = re.compile(
  23. # Date
  24. r'^\d\d\d\d-\d\d-\d\d '
  25. # Author
  26. r'[^ ]+ '
  27. # Subject
  28. r'('
  29. # Generated by
  30. # https://skia.googlesource.com/buildbot/+/HEAdA/autoroll/go/repo_manager/deps_repo_manager.go
  31. r'Roll [^ ]+ [a-f0-9]+\.\.[a-f0-9]+ \(\d+ commits\)'
  32. r'|'
  33. # Generated by
  34. # https://chromium.googlesource.com/infra/infra/+/HEAD/recipes/recipe_modules/recipe_autoroller/api.py
  35. r'Roll recipe dependencies \(trivial\)\.'
  36. r')$')
  37. class Error(Exception):
  38. pass
  39. class AlreadyRolledError(Error):
  40. pass
  41. def check_output(*args, **kwargs):
  42. """subprocess2.check_output() passing shell=True on Windows for git."""
  43. kwargs.setdefault('shell', NEED_SHELL)
  44. return subprocess2.check_output(*args, **kwargs).decode('utf-8')
  45. def check_call(*args, **kwargs):
  46. """subprocess2.check_call() passing shell=True on Windows for git."""
  47. kwargs.setdefault('shell', NEED_SHELL)
  48. subprocess2.check_call(*args, **kwargs)
  49. def return_code(*args, **kwargs):
  50. """subprocess2.call() passing shell=True on Windows for git and
  51. subprocess2.DEVNULL for stdout and stderr."""
  52. kwargs.setdefault('shell', NEED_SHELL)
  53. kwargs.setdefault('stdout', subprocess2.DEVNULL)
  54. kwargs.setdefault('stderr', subprocess2.DEVNULL)
  55. return subprocess2.call(*args, **kwargs)
  56. def is_pristine(root):
  57. """Returns True if a git checkout is pristine."""
  58. # `git rev-parse --verify` has a non-zero return code if the revision
  59. # doesn't exist.
  60. diff_cmd = ['git', 'diff', '--ignore-submodules', 'origin/main']
  61. return (not check_output(diff_cmd, cwd=root).strip()
  62. and not check_output(diff_cmd + ['--cached'], cwd=root).strip())
  63. def get_log_url(upstream_url, head, tot):
  64. """Returns an URL to read logs via a Web UI if applicable."""
  65. if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
  66. # gitiles
  67. return '%s/+log/%s..%s' % (upstream_url, head[:12], tot[:12])
  68. if upstream_url.startswith('https://github.com/'):
  69. upstream_url = upstream_url.rstrip('/')
  70. if upstream_url.endswith('.git'):
  71. upstream_url = upstream_url[:-len('.git')]
  72. return '%s/compare/%s...%s' % (upstream_url, head[:12], tot[:12])
  73. return None
  74. def should_show_log(upstream_url):
  75. """Returns True if a short log should be included in the tree."""
  76. # Skip logs for very active projects.
  77. if upstream_url.endswith('/v8/v8.git'):
  78. return False
  79. if 'webrtc' in upstream_url:
  80. return False
  81. return True
  82. def gclient(args):
  83. """Executes gclient with the given args and returns the stdout."""
  84. return check_output([sys.executable, GCLIENT_PATH] + args).strip()
  85. def generate_commit_message(full_dir, dependency, head, roll_to, no_log,
  86. log_limit):
  87. """Creates the commit message for this specific roll."""
  88. commit_range = '%s..%s' % (head, roll_to)
  89. commit_range_for_header = '%s..%s' % (head[:9], roll_to[:9])
  90. upstream_url = check_output(['git', 'config', 'remote.origin.url'],
  91. cwd=full_dir).strip()
  92. log_url = get_log_url(upstream_url, head, roll_to)
  93. cmd = ['git', 'log', commit_range, '--date=short', '--no-merges']
  94. logs = check_output(
  95. # Args with '=' are automatically quoted.
  96. cmd + ['--format=%ad %ae %s', '--'],
  97. cwd=full_dir).rstrip()
  98. logs = re.sub(r'(?m)^(\d\d\d\d-\d\d-\d\d [^@]+)@[^ ]+( .*)$', r'\1\2', logs)
  99. lines = logs.splitlines()
  100. cleaned_lines = [l for l in lines if not _ROLL_SUBJECT.match(l)]
  101. logs = '\n'.join(cleaned_lines) + '\n'
  102. nb_commits = len(lines)
  103. rolls = nb_commits - len(cleaned_lines)
  104. header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
  105. dependency, commit_range_for_header, nb_commits,
  106. 's' if nb_commits > 1 else '',
  107. ('; %s trivial rolls' % rolls) if rolls else '')
  108. log_section = ''
  109. if log_url:
  110. log_section = log_url + '\n\n'
  111. log_section += '$ %s ' % ' '.join(cmd)
  112. log_section += '--format=\'%ad %ae %s\'\n'
  113. log_section = log_section.replace(commit_range, commit_range_for_header)
  114. # It is important that --no-log continues to work, as it is used by
  115. # internal -> external rollers. Please do not remove or break it.
  116. if not no_log and should_show_log(upstream_url):
  117. if len(cleaned_lines) > log_limit:
  118. # Keep the first N/2 log entries and last N/2 entries.
  119. lines = logs.splitlines(True)
  120. lines = lines[:log_limit // 2] + ['(...)\n'
  121. ] + lines[-log_limit // 2:]
  122. logs = ''.join(lines)
  123. log_section += logs
  124. return header + log_section
  125. def is_submoduled():
  126. """Returns true if gclient root has submodules"""
  127. return os.path.isfile(os.path.join(gclient(['root']), ".gitmodules"))
  128. def get_submodule_rev(submodule):
  129. """Returns revision of the given submodule path"""
  130. rev_output = check_output(['git', 'submodule', 'status', submodule],
  131. cwd=gclient(['root'])).strip()
  132. # git submodule status <path> returns all submodules with its rev in the
  133. # pattern: `(+|-| )(<revision>) (submodule.path)`
  134. revision = rev_output.split(' ')[0]
  135. return revision[1:] if revision[0] in ('+', '-') else revision
  136. def calculate_roll(full_dir, dependency, roll_to):
  137. """Calculates the roll for a dependency by processing gclient_dict, and
  138. fetching the dependency via git.
  139. """
  140. # if the super-project uses submodules, get rev directly using git.
  141. if is_submoduled():
  142. head = get_submodule_rev(dependency)
  143. else:
  144. head = gclient(['getdep', '-r', dependency])
  145. if not head:
  146. raise Error('%s is unpinned.' % dependency)
  147. check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
  148. if roll_to == 'origin/HEAD':
  149. check_output(['git', 'remote', 'set-head', 'origin', '-a'],
  150. cwd=full_dir)
  151. roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
  152. return head, roll_to
  153. def gen_commit_msg(logs, cmdline, reviewers, bug):
  154. """Returns the final commit message."""
  155. commit_msg = ''
  156. if len(logs) > 1:
  157. commit_msg = 'Rolling %d dependencies\n\n' % len(logs)
  158. commit_msg += '\n\n'.join(logs)
  159. commit_msg += '\nCreated with:\n ' + cmdline + '\n'
  160. commit_msg += 'R=%s\n' % ','.join(reviewers) if reviewers else ''
  161. commit_msg += '\nBug: %s\n' % bug if bug else ''
  162. return commit_msg
  163. def finalize(commit_msg, current_dir, rolls):
  164. """Commits changes to the DEPS file, then uploads a CL."""
  165. print('Commit message:')
  166. print('\n'.join(' ' + i for i in commit_msg.splitlines()))
  167. # Pull the dependency to the right revision. This is surprising to users
  168. # otherwise. The revision update is done before commiting to update
  169. # submodule revision if present.
  170. for dependency, (_head, roll_to, full_dir) in sorted(rolls.items()):
  171. check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
  172. # This adds the submodule revision update to the commit.
  173. if is_submoduled():
  174. check_call([
  175. 'git', 'update-index', '--add', '--cacheinfo',
  176. '160000,{},{}'.format(roll_to, dependency)
  177. ],
  178. cwd=current_dir)
  179. check_call(['git', 'add', 'DEPS'], cwd=current_dir)
  180. # We have to set delete=False and then let the object go out of scope so
  181. # that the file can be opened by name on Windows.
  182. with tempfile.NamedTemporaryFile('w+', newline='', delete=False) as f:
  183. commit_filename = f.name
  184. f.write(commit_msg)
  185. check_call(['git', 'commit', '--quiet', '--file', commit_filename],
  186. cwd=current_dir)
  187. os.remove(commit_filename)
  188. def main():
  189. parser = argparse.ArgumentParser(description=__doc__)
  190. parser.add_argument('--ignore-dirty-tree',
  191. action='store_true',
  192. help='Roll anyways, even if there is a diff.')
  193. parser.add_argument(
  194. '-r',
  195. '--reviewer',
  196. action='append',
  197. help='To specify multiple reviewers, either use a comma separated '
  198. 'list, e.g. -r joe,jane,john or provide the flag multiple times, e.g. '
  199. '-r joe -r jane. Defaults to @chromium.org')
  200. parser.add_argument('-b',
  201. '--bug',
  202. help='Associate a bug number to the roll')
  203. # It is important that --no-log continues to work, as it is used by
  204. # internal -> external rollers. Please do not remove or break it.
  205. parser.add_argument(
  206. '--no-log',
  207. action='store_true',
  208. help='Do not include the short log in the commit message')
  209. parser.add_argument('--log-limit',
  210. type=int,
  211. default=100,
  212. help='Trim log after N commits (default: %(default)s)')
  213. parser.add_argument(
  214. '--roll-to',
  215. default='origin/HEAD',
  216. help='Specify the new commit to roll to (default: %(default)s)')
  217. parser.add_argument('--key',
  218. action='append',
  219. default=[],
  220. help='Regex(es) for dependency in DEPS file')
  221. parser.add_argument('dep_path', nargs='+', help='Path(s) to dependency')
  222. args = parser.parse_args()
  223. if len(args.dep_path) > 1:
  224. if args.roll_to != 'origin/HEAD':
  225. parser.error(
  226. 'Can\'t use multiple paths to roll simultaneously and --roll-to'
  227. )
  228. if args.key:
  229. parser.error(
  230. 'Can\'t use multiple paths to roll simultaneously and --key')
  231. reviewers = None
  232. if args.reviewer:
  233. reviewers = list(itertools.chain(*[r.split(',')
  234. for r in args.reviewer]))
  235. for i, r in enumerate(reviewers):
  236. if not '@' in r:
  237. reviewers[i] = r + '@chromium.org'
  238. gclient_root = gclient(['root'])
  239. current_dir = os.getcwd()
  240. dependencies = sorted(
  241. d.replace('\\', '/').rstrip('/') for d in args.dep_path)
  242. cmdline = 'roll-dep ' + ' '.join(dependencies) + ''.join(' --key ' + k
  243. for k in args.key)
  244. try:
  245. if not args.ignore_dirty_tree and not is_pristine(current_dir):
  246. raise Error('Ensure %s is clean first (no non-merged commits).' %
  247. current_dir)
  248. # First gather all the information without modifying anything, except
  249. # for a git fetch.
  250. rolls = {}
  251. for dependency in dependencies:
  252. full_dir = os.path.normpath(os.path.join(gclient_root, dependency))
  253. if not os.path.isdir(full_dir):
  254. print('Dependency %s not found at %s' % (dependency, full_dir))
  255. full_dir = os.path.normpath(
  256. os.path.join(current_dir, dependency))
  257. print('Will look for relative dependency at %s' % full_dir)
  258. if not os.path.isdir(full_dir):
  259. raise Error('Directory not found: %s (%s)' %
  260. (dependency, full_dir))
  261. head, roll_to = calculate_roll(full_dir, dependency, args.roll_to)
  262. if roll_to == head:
  263. if len(dependencies) == 1:
  264. raise AlreadyRolledError('No revision to roll!')
  265. print('%s: Already at latest commit %s' % (dependency, roll_to))
  266. else:
  267. print('%s: Rolling from %s to %s' %
  268. (dependency, head[:10], roll_to[:10]))
  269. rolls[dependency] = (head, roll_to, full_dir)
  270. logs = []
  271. setdep_args = []
  272. for dependency, (head, roll_to, full_dir) in sorted(rolls.items()):
  273. log = generate_commit_message(full_dir, dependency, head, roll_to,
  274. args.no_log, args.log_limit)
  275. logs.append(log)
  276. setdep_args.extend(['-r', '{}@{}'.format(dependency, roll_to)])
  277. # DEPS is updated even if the repository uses submodules.
  278. gclient(['setdep'] + setdep_args)
  279. commit_msg = gen_commit_msg(logs, cmdline, reviewers, args.bug)
  280. finalize(commit_msg, current_dir, rolls)
  281. except Error as e:
  282. sys.stderr.write('error: %s\n' % e)
  283. return 2 if isinstance(e, AlreadyRolledError) else 1
  284. except subprocess2.CalledProcessError:
  285. return 1
  286. print('')
  287. if not reviewers:
  288. print('You forgot to pass -r, make sure to insert a R=foo@example.com '
  289. 'line')
  290. print('to the commit description before emailing.')
  291. print('')
  292. print('Run:')
  293. print(' git cl upload --send-mail')
  294. return 0
  295. if __name__ == '__main__':
  296. sys.exit(main())