git_rebase_update.py 15 KB

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