git_rebase_update.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #!/usr/bin/env python
  2. # Copyright 2014 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. """
  6. Tool to update all branches to have the latest changes from their upstreams.
  7. """
  8. import argparse
  9. import collections
  10. import logging
  11. import sys
  12. import textwrap
  13. import os
  14. from fnmatch import fnmatch
  15. from pprint import pformat
  16. import git_common as git
  17. STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch'
  18. STARTING_WORKDIR_KEY = 'depot-tools.rebase-update.starting-workdir'
  19. def find_return_branch_workdir():
  20. """Finds the branch and working directory which we should return to after
  21. rebase-update completes.
  22. These values may persist across multiple invocations of rebase-update, if
  23. rebase-update runs into a conflict mid-way.
  24. """
  25. return_branch = git.config(STARTING_BRANCH_KEY)
  26. workdir = git.config(STARTING_WORKDIR_KEY)
  27. if not return_branch:
  28. workdir = os.getcwd()
  29. git.set_config(STARTING_WORKDIR_KEY, workdir)
  30. return_branch = git.current_branch()
  31. if return_branch != 'HEAD':
  32. git.set_config(STARTING_BRANCH_KEY, return_branch)
  33. return return_branch, workdir
  34. def fetch_remotes(branch_tree):
  35. """Fetches all remotes which are needed to update |branch_tree|."""
  36. fetch_tags = False
  37. remotes = set()
  38. tag_set = git.tags()
  39. fetchspec_map = {}
  40. all_fetchspec_configs = git.run(
  41. 'config', '--get-regexp', r'^remote\..*\.fetch').strip()
  42. for fetchspec_config in all_fetchspec_configs.splitlines():
  43. key, _, fetchspec = fetchspec_config.partition(' ')
  44. dest_spec = fetchspec.partition(':')[2]
  45. remote_name = key.split('.')[1]
  46. fetchspec_map[dest_spec] = remote_name
  47. for parent in branch_tree.itervalues():
  48. if parent in tag_set:
  49. fetch_tags = True
  50. else:
  51. full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
  52. for dest_spec, remote_name in fetchspec_map.iteritems():
  53. if fnmatch(full_ref, dest_spec):
  54. remotes.add(remote_name)
  55. break
  56. fetch_args = []
  57. if fetch_tags:
  58. # Need to fetch all because we don't know what remote the tag comes from :(
  59. # TODO(iannucci): assert that the tags are in the remote fetch refspec
  60. fetch_args = ['--all']
  61. else:
  62. fetch_args.append('--multiple')
  63. fetch_args.extend(remotes)
  64. # TODO(iannucci): Should we fetch git-svn?
  65. if not fetch_args: # pragma: no cover
  66. print 'Nothing to fetch.'
  67. else:
  68. git.run_with_stderr('fetch', *fetch_args, stdout=sys.stdout,
  69. stderr=sys.stderr)
  70. def remove_empty_branches(branch_tree):
  71. tag_set = git.tags()
  72. ensure_root_checkout = git.once(lambda: git.run('checkout', git.root()))
  73. deletions = set()
  74. downstreams = collections.defaultdict(list)
  75. for branch, parent in git.topo_iter(branch_tree, top_down=False):
  76. downstreams[parent].append(branch)
  77. if git.hash_one(branch) == git.hash_one(parent):
  78. ensure_root_checkout()
  79. logging.debug('branch %s merged to %s', branch, parent)
  80. for down in downstreams[branch]:
  81. if down in deletions:
  82. continue
  83. if parent in tag_set:
  84. git.set_branch_config(down, 'remote', '.')
  85. git.set_branch_config(down, 'merge', 'refs/tags/%s' % parent)
  86. print ('Reparented %s to track %s [tag] (was tracking %s)'
  87. % (down, parent, branch))
  88. else:
  89. git.run('branch', '--set-upstream-to', parent, down)
  90. print ('Reparented %s to track %s (was tracking %s)'
  91. % (down, parent, branch))
  92. deletions.add(branch)
  93. print git.run('branch', '-d', branch)
  94. def rebase_branch(branch, parent, start_hash):
  95. logging.debug('considering %s(%s) -> %s(%s) : %s',
  96. branch, git.hash_one(branch), parent, git.hash_one(parent),
  97. start_hash)
  98. # If parent has FROZEN commits, don't base branch on top of them. Instead,
  99. # base branch on top of whatever commit is before them.
  100. back_ups = 0
  101. orig_parent = parent
  102. while git.run('log', '-n1', '--format=%s',
  103. parent, '--').startswith(git.FREEZE):
  104. back_ups += 1
  105. parent = git.run('rev-parse', parent+'~')
  106. if back_ups:
  107. logging.debug('Backed parent up by %d from %s to %s',
  108. back_ups, orig_parent, parent)
  109. if git.hash_one(parent) != start_hash:
  110. # Try a plain rebase first
  111. print 'Rebasing:', branch
  112. rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
  113. if not rebase_ret.success:
  114. # TODO(iannucci): Find collapsible branches in a smarter way?
  115. print "Failed! Attempting to squash", branch, "...",
  116. squash_branch = branch+"_squash_attempt"
  117. git.run('checkout', '-b', squash_branch)
  118. git.squash_current_branch(merge_base=start_hash)
  119. # Try to rebase the branch_squash_attempt branch to see if it's empty.
  120. squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
  121. empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
  122. git.run('checkout', branch)
  123. git.run('branch', '-D', squash_branch)
  124. if squash_ret.success and empty_rebase:
  125. print 'Success!'
  126. git.squash_current_branch(merge_base=start_hash)
  127. git.rebase(parent, start_hash, branch)
  128. else:
  129. print "Failed!"
  130. print
  131. # rebase and leave in mid-rebase state.
  132. # This second rebase attempt should always fail in the same
  133. # way that the first one does. If it magically succeeds then
  134. # something very strange has happened.
  135. second_rebase_ret = git.rebase(parent, start_hash, branch)
  136. if second_rebase_ret.success: # pragma: no cover
  137. print "Second rebase succeeded unexpectedly!"
  138. print "Please see: http://crbug.com/425696"
  139. print "First rebased failed with:"
  140. print rebase_ret.stderr
  141. else:
  142. print "Here's what git-rebase (squashed) had to say:"
  143. print
  144. print squash_ret.stdout
  145. print squash_ret.stderr
  146. print textwrap.dedent(
  147. """\
  148. Squashing failed. You probably have a real merge conflict.
  149. Your working copy is in mid-rebase. Either:
  150. * completely resolve like a normal git-rebase; OR
  151. * abort the rebase and mark this branch as dormant:
  152. git config branch.%s.dormant true
  153. And then run `git rebase-update` again to resume.
  154. """ % branch)
  155. return False
  156. else:
  157. print '%s up-to-date' % branch
  158. git.remove_merge_base(branch)
  159. git.get_or_create_merge_base(branch)
  160. return True
  161. def main(args=None):
  162. parser = argparse.ArgumentParser()
  163. parser.add_argument('--verbose', '-v', action='store_true')
  164. parser.add_argument('--keep-going', '-k', action='store_true',
  165. help='Keep processing past failed rebases.')
  166. parser.add_argument('--no_fetch', '--no-fetch', '-n',
  167. action='store_true',
  168. help='Skip fetching remotes.')
  169. opts = parser.parse_args(args)
  170. if opts.verbose: # pragma: no cover
  171. logging.getLogger().setLevel(logging.DEBUG)
  172. # TODO(iannucci): snapshot all branches somehow, so we can implement
  173. # `git rebase-update --undo`.
  174. # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
  175. # * commit them to a secret ref?
  176. # * Then we could view a summary of each run as a
  177. # `diff --stat` on that secret ref.
  178. if git.in_rebase():
  179. # TODO(iannucci): Be able to resume rebase with flags like --continue,
  180. # etc.
  181. print (
  182. 'Rebase in progress. Please complete the rebase before running '
  183. '`git rebase-update`.'
  184. )
  185. return 1
  186. return_branch, return_workdir = find_return_branch_workdir()
  187. os.chdir(git.run('rev-parse', '--show-toplevel'))
  188. if git.current_branch() == 'HEAD':
  189. if git.run('status', '--porcelain'):
  190. print 'Cannot rebase-update with detached head + uncommitted changes.'
  191. return 1
  192. else:
  193. git.freeze() # just in case there are any local changes.
  194. skipped, branch_tree = git.get_branch_tree()
  195. for branch in skipped:
  196. print 'Skipping %s: No upstream specified' % branch
  197. if not opts.no_fetch:
  198. fetch_remotes(branch_tree)
  199. merge_base = {}
  200. for branch, parent in branch_tree.iteritems():
  201. merge_base[branch] = git.get_or_create_merge_base(branch, parent)
  202. logging.debug('branch_tree: %s' % pformat(branch_tree))
  203. logging.debug('merge_base: %s' % pformat(merge_base))
  204. retcode = 0
  205. unrebased_branches = []
  206. # Rebase each branch starting with the root-most branches and working
  207. # towards the leaves.
  208. for branch, parent in git.topo_iter(branch_tree):
  209. if git.is_dormant(branch):
  210. print 'Skipping dormant branch', branch
  211. else:
  212. ret = rebase_branch(branch, parent, merge_base[branch])
  213. if not ret:
  214. retcode = 1
  215. if opts.keep_going:
  216. print '--keep-going set, continuing with next branch.'
  217. unrebased_branches.append(branch)
  218. if git.in_rebase():
  219. git.run_with_retcode('rebase', '--abort')
  220. if git.in_rebase(): # pragma: no cover
  221. print 'Failed to abort rebase. Something is really wrong.'
  222. break
  223. else:
  224. break
  225. if unrebased_branches:
  226. print
  227. print 'The following branches could not be cleanly rebased:'
  228. for branch in unrebased_branches:
  229. print ' %s' % branch
  230. if not retcode:
  231. remove_empty_branches(branch_tree)
  232. # return_branch may not be there any more.
  233. if return_branch in git.branches():
  234. git.run('checkout', return_branch)
  235. git.thaw()
  236. else:
  237. root_branch = git.root()
  238. if return_branch != 'HEAD':
  239. print (
  240. "%r was merged with its parent, checking out %r instead."
  241. % (return_branch, root_branch)
  242. )
  243. git.run('checkout', root_branch)
  244. if return_workdir:
  245. os.chdir(return_workdir)
  246. git.set_config(STARTING_BRANCH_KEY, '')
  247. git.set_config(STARTING_WORKDIR_KEY, '')
  248. return retcode
  249. if __name__ == '__main__': # pragma: no cover
  250. try:
  251. sys.exit(main())
  252. except KeyboardInterrupt:
  253. sys.stderr.write('interrupted\n')
  254. sys.exit(1)