roll_dep.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env vpython
  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
  7. script will always roll to the tip of to origin/master.
  8. """
  9. from __future__ import print_function
  10. import argparse
  11. import collections
  12. import gclient_eval
  13. import os
  14. import re
  15. import subprocess
  16. import sys
  17. NEED_SHELL = sys.platform.startswith('win')
  18. GCLIENT_PATH = os.path.join(
  19. os.path.dirname(os.path.abspath(__file__)), '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/+/master/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/+/master/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. """subprocess.check_output() passing shell=True on Windows for git."""
  43. kwargs.setdefault('shell', NEED_SHELL)
  44. return subprocess.check_output(*args, **kwargs)
  45. def check_call(*args, **kwargs):
  46. """subprocess.check_call() passing shell=True on Windows for git."""
  47. kwargs.setdefault('shell', NEED_SHELL)
  48. subprocess.check_call(*args, **kwargs)
  49. def is_pristine(root, merge_base='origin/master'):
  50. """Returns True if a git checkout is pristine."""
  51. cmd = ['git', 'diff', '--ignore-submodules', merge_base]
  52. return not (check_output(cmd, cwd=root).strip() or
  53. check_output(cmd + ['--cached'], cwd=root).strip())
  54. def get_log_url(upstream_url, head, master):
  55. """Returns an URL to read logs via a Web UI if applicable."""
  56. if re.match(r'https://[^/]*\.googlesource\.com/', upstream_url):
  57. # gitiles
  58. return '%s/+log/%s..%s' % (upstream_url, head[:12], master[:12])
  59. if upstream_url.startswith('https://github.com/'):
  60. upstream_url = upstream_url.rstrip('/')
  61. if upstream_url.endswith('.git'):
  62. upstream_url = upstream_url[:-len('.git')]
  63. return '%s/compare/%s...%s' % (upstream_url, head[:12], master[:12])
  64. return None
  65. def should_show_log(upstream_url):
  66. """Returns True if a short log should be included in the tree."""
  67. # Skip logs for very active projects.
  68. if upstream_url.endswith('/v8/v8.git'):
  69. return False
  70. if 'webrtc' in upstream_url:
  71. return False
  72. return True
  73. def gclient(args):
  74. """Executes gclient with the given args and returns the stdout."""
  75. return check_output([sys.executable, GCLIENT_PATH] + args).strip()
  76. def generate_commit_message(
  77. full_dir, dependency, head, roll_to, no_log, log_limit):
  78. """Creates the commit message for this specific roll."""
  79. commit_range = '%s..%s' % (head[:9], roll_to[:9])
  80. upstream_url = check_output(
  81. ['git', 'config', 'remote.origin.url'], cwd=full_dir).strip()
  82. log_url = get_log_url(upstream_url, head, roll_to)
  83. cmd = ['git', 'log', commit_range, '--date=short', '--no-merges']
  84. logs = check_output(
  85. cmd + ['--format=%ad %ae %s'], # Args with '=' are automatically quoted.
  86. cwd=full_dir).rstrip()
  87. logs = re.sub(r'(?m)^(\d\d\d\d-\d\d-\d\d [^@]+)@[^ ]+( .*)$', r'\1\2', logs)
  88. lines = logs.splitlines()
  89. cleaned_lines = [l for l in lines if not _ROLL_SUBJECT.match(l)]
  90. logs = '\n'.join(cleaned_lines) + '\n'
  91. nb_commits = len(lines)
  92. rolls = nb_commits - len(cleaned_lines)
  93. header = 'Roll %s/ %s (%d commit%s%s)\n\n' % (
  94. dependency,
  95. commit_range,
  96. nb_commits,
  97. 's' if nb_commits > 1 else '',
  98. ('; %s trivial rolls' % rolls) if rolls else '')
  99. log_section = ''
  100. if log_url:
  101. log_section = log_url + '\n\n'
  102. log_section += '$ %s ' % ' '.join(cmd)
  103. log_section += '--format=\'%ad %ae %s\'\n'
  104. # It is important that --no-log continues to work, as it is used by
  105. # internal -> external rollers. Please do not remove or break it.
  106. if not no_log and should_show_log(upstream_url):
  107. if len(cleaned_lines) > log_limit:
  108. # Keep the first N/2 log entries and last N/2 entries.
  109. lines = logs.splitlines(True)
  110. lines = lines[:log_limit/2] + ['(...)\n'] + lines[-log_limit/2:]
  111. logs = ''.join(lines)
  112. log_section += logs
  113. return header + log_section
  114. def calculate_roll(full_dir, dependency, roll_to):
  115. """Calculates the roll for a dependency by processing gclient_dict, and
  116. fetching the dependency via git.
  117. """
  118. head = gclient(['getdep', '-r', dependency])
  119. if not head:
  120. raise Error('%s is unpinned.' % dependency)
  121. check_call(['git', 'fetch', 'origin', '--quiet'], cwd=full_dir)
  122. roll_to = check_output(['git', 'rev-parse', roll_to], cwd=full_dir).strip()
  123. return head, roll_to
  124. def gen_commit_msg(logs, cmdline, reviewers, bug):
  125. """Returns the final commit message."""
  126. commit_msg = ''
  127. if len(logs) > 1:
  128. commit_msg = 'Rolling %d dependencies\n\n' % len(logs)
  129. commit_msg += '\n\n'.join(logs)
  130. commit_msg += '\nCreated with:\n ' + cmdline + '\n'
  131. commit_msg += 'R=%s\n' % ','.join(reviewers) if reviewers else ''
  132. commit_msg += '\nBug: %s\n' % bug if bug else ''
  133. return commit_msg
  134. def finalize(commit_msg, current_dir, rolls):
  135. """Commits changes to the DEPS file, then uploads a CL."""
  136. print('Commit message:')
  137. print('\n'.join(' ' + i for i in commit_msg.splitlines()))
  138. check_call(['git', 'add', 'DEPS'], cwd=current_dir)
  139. check_call(['git', 'commit', '--quiet', '-m', commit_msg], cwd=current_dir)
  140. # Pull the dependency to the right revision. This is surprising to users
  141. # otherwise.
  142. for _head, roll_to, full_dir in sorted(rolls.itervalues()):
  143. check_call(['git', 'checkout', '--quiet', roll_to], cwd=full_dir)
  144. def main():
  145. parser = argparse.ArgumentParser(description=__doc__)
  146. parser.add_argument(
  147. '--ignore-dirty-tree', action='store_true',
  148. help='Roll anyways, even if there is a diff.')
  149. parser.add_argument(
  150. '-r', '--reviewer',
  151. help='To specify multiple reviewers, use comma separated list, e.g. '
  152. '-r joe,jane,john. Defaults to @chromium.org')
  153. parser.add_argument('-b', '--bug', help='Associate a bug number to the roll')
  154. # It is important that --no-log continues to work, as it is used by
  155. # internal -> external rollers. Please do not remove or break it.
  156. parser.add_argument(
  157. '--no-log', action='store_true',
  158. help='Do not include the short log in the commit message')
  159. parser.add_argument(
  160. '--log-limit', type=int, default=100,
  161. help='Trim log after N commits (default: %(default)s)')
  162. parser.add_argument(
  163. '--roll-to', default='origin/master',
  164. help='Specify the new commit to roll to (default: %(default)s)')
  165. parser.add_argument(
  166. '--key', action='append', default=[],
  167. help='Regex(es) for dependency in DEPS file')
  168. parser.add_argument('dep_path', nargs='+', help='Path(s) to dependency')
  169. args = parser.parse_args()
  170. if len(args.dep_path) > 1:
  171. if args.roll_to != 'origin/master':
  172. parser.error(
  173. 'Can\'t use multiple paths to roll simultaneously and --roll-to')
  174. if args.key:
  175. parser.error(
  176. 'Can\'t use multiple paths to roll simultaneously and --key')
  177. reviewers = None
  178. if args.reviewer:
  179. reviewers = args.reviewer.split(',')
  180. for i, r in enumerate(reviewers):
  181. if not '@' in r:
  182. reviewers[i] = r + '@chromium.org'
  183. gclient_root = gclient(['root'])
  184. current_dir = os.getcwd()
  185. dependencies = sorted(d.rstrip('/').rstrip('\\') for d in args.dep_path)
  186. cmdline = 'roll-dep ' + ' '.join(dependencies) + ''.join(
  187. ' --key ' + k for k in args.key)
  188. try:
  189. if not args.ignore_dirty_tree and not is_pristine(current_dir):
  190. raise Error(
  191. 'Ensure %s is clean first (no non-merged commits).' % current_dir)
  192. # First gather all the information without modifying anything, except for a
  193. # git fetch.
  194. rolls = {}
  195. for dependency in dependencies:
  196. full_dir = os.path.normpath(os.path.join(gclient_root, dependency))
  197. if not os.path.isdir(full_dir):
  198. print('Dependency %s not found at %s' % (dependency, full_dir))
  199. full_dir = os.path.normpath(os.path.join(current_dir, dependency))
  200. print('Will look for relative dependency at %s' % full_dir)
  201. if not os.path.isdir(full_dir):
  202. raise Error('Directory not found: %s (%s)' % (dependency, full_dir))
  203. head, roll_to = calculate_roll(full_dir, dependency, args.roll_to)
  204. if roll_to == head:
  205. if len(dependencies) == 1:
  206. raise AlreadyRolledError('No revision to roll!')
  207. print('%s: Already at latest commit %s' % (dependency, roll_to))
  208. else:
  209. print(
  210. '%s: Rolling from %s to %s' % (dependency, head[:10], roll_to[:10]))
  211. rolls[dependency] = (head, roll_to, full_dir)
  212. logs = []
  213. setdep_args = []
  214. for dependency, (head, roll_to, full_dir) in sorted(rolls.iteritems()):
  215. log = generate_commit_message(
  216. full_dir, dependency, head, roll_to, args.no_log, args.log_limit)
  217. logs.append(log)
  218. setdep_args.extend(['-r', '{}@{}'.format(dependency, roll_to)])
  219. gclient(['setdep'] + setdep_args)
  220. commit_msg = gen_commit_msg(logs, cmdline, reviewers, args.bug)
  221. finalize(commit_msg, current_dir, rolls)
  222. except Error as e:
  223. sys.stderr.write('error: %s\n' % e)
  224. return 2 if isinstance(e, AlreadyRolledError) else 1
  225. print('')
  226. if not reviewers:
  227. print('You forgot to pass -r, make sure to insert a R=foo@example.com line')
  228. print('to the commit description before emailing.')
  229. print('')
  230. print('Run:')
  231. print(' git cl upload --send-mail')
  232. return 0
  233. if __name__ == '__main__':
  234. sys.exit(main())