roll_dep.py 13 KB

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