git_rebase_update.py 16 KB

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