git_rebase_update.py 14 KB

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