git_rebase_update.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. #!/usr/bin/env python3
  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. from __future__ import print_function
  9. import argparse
  10. import collections
  11. import logging
  12. import sys
  13. import textwrap
  14. import os
  15. from fnmatch import fnmatch
  16. from pprint import pformat
  17. import git_common as git
  18. STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch'
  19. STARTING_WORKDIR_KEY = 'depot-tools.rebase-update.starting-workdir'
  20. def find_return_branch_workdir():
  21. """Finds the branch and working directory which we should return to after
  22. rebase-update completes.
  23. These values may persist across multiple invocations of rebase-update, if
  24. rebase-update runs into a conflict mid-way.
  25. """
  26. return_branch = git.get_config(STARTING_BRANCH_KEY)
  27. workdir = git.get_config(STARTING_WORKDIR_KEY)
  28. if not return_branch:
  29. workdir = os.getcwd()
  30. git.set_config(STARTING_WORKDIR_KEY, workdir)
  31. return_branch = git.current_branch()
  32. if return_branch != 'HEAD':
  33. git.set_config(STARTING_BRANCH_KEY, return_branch)
  34. return return_branch, workdir
  35. def fetch_remotes(branch_tree):
  36. """Fetches all remotes which are needed to update |branch_tree|."""
  37. fetch_tags = False
  38. remotes = set()
  39. tag_set = git.tags()
  40. fetchspec_map = {}
  41. all_fetchspec_configs = git.get_config_regexp(r'^remote\..*\.fetch')
  42. for fetchspec_config in all_fetchspec_configs:
  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.values():
  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.items():
  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 = {}
  74. reparents = {}
  75. downstreams = collections.defaultdict(list)
  76. for branch, parent in git.topo_iter(branch_tree, top_down=False):
  77. if git.is_dormant(branch):
  78. continue
  79. downstreams[parent].append(branch)
  80. # If branch and parent have the same tree, then branch has to be marked
  81. # for deletion and its children and grand-children reparented to parent.
  82. if git.hash_one(branch+":") == git.hash_one(parent+":"):
  83. ensure_root_checkout()
  84. logging.debug('branch %s merged to %s', branch, parent)
  85. # Mark branch for deletion while remembering the ordering, then add all
  86. # its children as grand-children of its parent and record reparenting
  87. # information if necessary.
  88. deletions[branch] = len(deletions)
  89. for down in downstreams[branch]:
  90. if down in deletions:
  91. continue
  92. # Record the new and old parent for down, or update such a record
  93. # if it already exists. Keep track of the ordering so that reparenting
  94. # happen in topological order.
  95. downstreams[parent].append(down)
  96. if down not in reparents:
  97. reparents[down] = (len(reparents), parent, branch)
  98. else:
  99. order, _, old_parent = reparents[down]
  100. reparents[down] = (order, parent, old_parent)
  101. # Apply all reparenting recorded, in order.
  102. for branch, value in sorted(reparents.items(), key=lambda x:x[1][0]):
  103. _, parent, old_parent = value
  104. if parent in tag_set:
  105. git.set_branch_config(branch, 'remote', '.')
  106. git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent)
  107. print('Reparented %s to track %s [tag] (was tracking %s)' %
  108. (branch, parent, old_parent))
  109. else:
  110. git.run('branch', '--set-upstream-to', parent, branch)
  111. print('Reparented %s to track %s (was tracking %s)' % (branch, parent,
  112. old_parent))
  113. # Apply all deletions recorded, in order.
  114. for branch, _ in sorted(deletions.items(), key=lambda x: x[1]):
  115. print(git.run('branch', '-d', branch))
  116. def rebase_branch(branch, parent, start_hash):
  117. logging.debug('considering %s(%s) -> %s(%s) : %s',
  118. branch, git.hash_one(branch), parent, git.hash_one(parent),
  119. start_hash)
  120. # If parent has FROZEN commits, don't base branch on top of them. Instead,
  121. # base branch on top of whatever commit is before them.
  122. back_ups = 0
  123. orig_parent = parent
  124. while git.run('log', '-n1', '--format=%s',
  125. parent, '--').startswith(git.FREEZE):
  126. back_ups += 1
  127. parent = git.run('rev-parse', parent+'~')
  128. if back_ups:
  129. logging.debug('Backed parent up by %d from %s to %s',
  130. back_ups, orig_parent, parent)
  131. if git.hash_one(parent) != start_hash:
  132. # Try a plain rebase first
  133. print('Rebasing:', branch)
  134. rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
  135. if not rebase_ret.success:
  136. # TODO(iannucci): Find collapsible branches in a smarter way?
  137. print("Failed! Attempting to squash", branch, "...", end=' ')
  138. sys.stdout.flush()
  139. squash_branch = branch+"_squash_attempt"
  140. git.run('checkout', '-b', squash_branch)
  141. git.squash_current_branch(merge_base=start_hash)
  142. # Try to rebase the branch_squash_attempt branch to see if it's empty.
  143. squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
  144. empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
  145. git.run('checkout', branch)
  146. git.run('branch', '-D', squash_branch)
  147. if squash_ret.success and empty_rebase:
  148. print('Success!')
  149. git.squash_current_branch(merge_base=start_hash)
  150. git.rebase(parent, start_hash, branch)
  151. else:
  152. print("Failed!")
  153. print()
  154. # rebase and leave in mid-rebase state.
  155. # This second rebase attempt should always fail in the same
  156. # way that the first one does. If it magically succeeds then
  157. # something very strange has happened.
  158. second_rebase_ret = git.rebase(parent, start_hash, branch)
  159. if second_rebase_ret.success: # pragma: no cover
  160. print("Second rebase succeeded unexpectedly!")
  161. print("Please see: http://crbug.com/425696")
  162. print("First rebased failed with:")
  163. print(rebase_ret.stderr)
  164. else:
  165. print("Here's what git-rebase (squashed) had to say:")
  166. print()
  167. print(squash_ret.stdout)
  168. print(squash_ret.stderr)
  169. print(textwrap.dedent("""\
  170. Squashing failed. You probably have a real merge conflict.
  171. Your working copy is in mid-rebase. Either:
  172. * completely resolve like a normal git-rebase; OR
  173. * abort the rebase and mark this branch as dormant:
  174. git rebase --abort && \\
  175. git config branch.%s.dormant true
  176. And then run `git rebase-update -n` to resume.
  177. """ % branch))
  178. return False
  179. else:
  180. print('%s up-to-date' % branch)
  181. git.remove_merge_base(branch)
  182. git.get_or_create_merge_base(branch)
  183. return True
  184. def main(args=None):
  185. parser = argparse.ArgumentParser()
  186. parser.add_argument('--verbose', '-v', action='store_true')
  187. parser.add_argument('--keep-going', '-k', action='store_true',
  188. help='Keep processing past failed rebases.')
  189. parser.add_argument('--no_fetch', '--no-fetch', '-n',
  190. action='store_true',
  191. help='Skip fetching remotes.')
  192. parser.add_argument(
  193. '--current', action='store_true', help='Only rebase the current branch.')
  194. parser.add_argument('branches', nargs='*',
  195. help='Branches to be rebased. All branches are assumed '
  196. 'if none specified.')
  197. parser.add_argument('--keep-empty', '-e', action='store_true',
  198. help='Do not automatically delete empty branches.')
  199. opts = parser.parse_args(args)
  200. if opts.verbose: # pragma: no cover
  201. logging.getLogger().setLevel(logging.DEBUG)
  202. # TODO(iannucci): snapshot all branches somehow, so we can implement
  203. # `git rebase-update --undo`.
  204. # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
  205. # * commit them to a secret ref?
  206. # * Then we could view a summary of each run as a
  207. # `diff --stat` on that secret ref.
  208. if git.in_rebase():
  209. # TODO(iannucci): Be able to resume rebase with flags like --continue,
  210. # etc.
  211. print('Rebase in progress. Please complete the rebase before running '
  212. '`git rebase-update`.')
  213. return 1
  214. return_branch, return_workdir = find_return_branch_workdir()
  215. os.chdir(git.run('rev-parse', '--show-toplevel'))
  216. if git.current_branch() == 'HEAD':
  217. if git.run('status', '--porcelain'):
  218. print('Cannot rebase-update with detached head + uncommitted changes.')
  219. return 1
  220. else:
  221. git.freeze() # just in case there are any local changes.
  222. branches_to_rebase = set(opts.branches)
  223. if opts.current:
  224. branches_to_rebase.add(git.current_branch())
  225. skipped, branch_tree = git.get_branch_tree(use_limit=not opts.current)
  226. if branches_to_rebase:
  227. skipped = set(skipped).intersection(branches_to_rebase)
  228. for branch in skipped:
  229. print('Skipping %s: No upstream specified' % branch)
  230. if not opts.no_fetch:
  231. fetch_remotes(branch_tree)
  232. merge_base = {}
  233. for branch, parent in branch_tree.items():
  234. merge_base[branch] = git.get_or_create_merge_base(branch, parent)
  235. logging.debug('branch_tree: %s' % pformat(branch_tree))
  236. logging.debug('merge_base: %s' % pformat(merge_base))
  237. retcode = 0
  238. unrebased_branches = []
  239. # Rebase each branch starting with the root-most branches and working
  240. # towards the leaves.
  241. for branch, parent in git.topo_iter(branch_tree):
  242. # Only rebase specified branches, unless none specified.
  243. if branches_to_rebase and branch not in branches_to_rebase:
  244. continue
  245. if git.is_dormant(branch):
  246. print('Skipping dormant branch', branch)
  247. else:
  248. ret = rebase_branch(branch, parent, merge_base[branch])
  249. if not ret:
  250. retcode = 1
  251. if opts.keep_going:
  252. print('--keep-going set, continuing with next branch.')
  253. unrebased_branches.append(branch)
  254. if git.in_rebase():
  255. git.run_with_retcode('rebase', '--abort')
  256. if git.in_rebase(): # pragma: no cover
  257. print('Failed to abort rebase. Something is really wrong.')
  258. break
  259. else:
  260. break
  261. if unrebased_branches:
  262. print()
  263. print('The following branches could not be cleanly rebased:')
  264. for branch in unrebased_branches:
  265. print(' %s' % branch)
  266. if not retcode:
  267. if not opts.keep_empty:
  268. remove_empty_branches(branch_tree)
  269. # return_branch may not be there any more.
  270. if return_branch in git.branches(use_limit=False):
  271. git.run('checkout', return_branch)
  272. git.thaw()
  273. else:
  274. root_branch = git.root()
  275. if return_branch != 'HEAD':
  276. print("%s was merged with its parent, checking out %s instead." %
  277. (git.unicode_repr(return_branch), git.unicode_repr(root_branch)))
  278. git.run('checkout', root_branch)
  279. # return_workdir may also not be there any more.
  280. if return_workdir:
  281. try:
  282. os.chdir(return_workdir)
  283. except OSError as e:
  284. print(
  285. "Unable to return to original workdir %r: %s" % (return_workdir, e))
  286. git.set_config(STARTING_BRANCH_KEY, '')
  287. git.set_config(STARTING_WORKDIR_KEY, '')
  288. print()
  289. print("Running `git gc --auto` - Ctrl-C to abort is OK.")
  290. git.run('gc', '--auto')
  291. return retcode
  292. if __name__ == '__main__': # pragma: no cover
  293. try:
  294. sys.exit(main())
  295. except KeyboardInterrupt:
  296. sys.stderr.write('interrupted\n')
  297. sys.exit(1)