blob: 9c9881ab6a84468b68b005f0c3c43266eca343b9 [file] [log] [blame]
Josip Sokcevic4de5dea2022-03-23 21:15:14 +00001#!/usr/bin/env python3
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00002# 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"""
7Tool to update all branches to have the latest changes from their upstreams.
8"""
9
10import argparse
11import collections
12import logging
13import sys
14import textwrap
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000015import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000016
szager@chromium.org937159d2014-09-24 17:25:45 +000017from fnmatch import fnmatch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000018from pprint import pformat
19
20import git_common as git
21
22
23STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch'
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000024STARTING_WORKDIR_KEY = 'depot-tools.rebase-update.starting-workdir'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000025
26
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000027def find_return_branch_workdir():
28 """Finds the branch and working directory which we should return to after
29 rebase-update completes.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000030
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000031 These values may persist across multiple invocations of rebase-update, if
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000032 rebase-update runs into a conflict mid-way.
33 """
agable7aa2ddd2016-06-21 07:47:00 -070034 return_branch = git.get_config(STARTING_BRANCH_KEY)
35 workdir = git.get_config(STARTING_WORKDIR_KEY)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +000036 if not return_branch:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000037 workdir = os.getcwd()
38 git.set_config(STARTING_WORKDIR_KEY, workdir)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000039 return_branch = git.current_branch()
40 if return_branch != 'HEAD':
41 git.set_config(STARTING_BRANCH_KEY, return_branch)
42
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000043 return return_branch, workdir
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000044
45
46def fetch_remotes(branch_tree):
47 """Fetches all remotes which are needed to update |branch_tree|."""
48 fetch_tags = False
49 remotes = set()
50 tag_set = git.tags()
szager@chromium.org937159d2014-09-24 17:25:45 +000051 fetchspec_map = {}
agable7aa2ddd2016-06-21 07:47:00 -070052 all_fetchspec_configs = git.get_config_regexp(r'^remote\..*\.fetch')
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000053 for fetchspec_config in all_fetchspec_configs:
szager@chromium.org937159d2014-09-24 17:25:45 +000054 key, _, fetchspec = fetchspec_config.partition(' ')
55 dest_spec = fetchspec.partition(':')[2]
56 remote_name = key.split('.')[1]
57 fetchspec_map[dest_spec] = remote_name
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000058 for parent in branch_tree.values():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000059 if parent in tag_set:
60 fetch_tags = True
61 else:
62 full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000063 for dest_spec, remote_name in fetchspec_map.items():
szager@chromium.org937159d2014-09-24 17:25:45 +000064 if fnmatch(full_ref, dest_spec):
65 remotes.add(remote_name)
66 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000067
68 fetch_args = []
69 if fetch_tags:
70 # Need to fetch all because we don't know what remote the tag comes from :(
71 # TODO(iannucci): assert that the tags are in the remote fetch refspec
72 fetch_args = ['--all']
73 else:
74 fetch_args.append('--multiple')
75 fetch_args.extend(remotes)
76 # TODO(iannucci): Should we fetch git-svn?
77
78 if not fetch_args: # pragma: no cover
Raul Tambre80ee78e2019-05-06 22:41:05 +000079 print('Nothing to fetch.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000080 else:
iannucci@chromium.org43f4ecc2014-05-08 19:22:47 +000081 git.run_with_stderr('fetch', *fetch_args, stdout=sys.stdout,
82 stderr=sys.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000083
84
85def remove_empty_branches(branch_tree):
86 tag_set = git.tags()
87 ensure_root_checkout = git.once(lambda: git.run('checkout', git.root()))
88
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +000089 deletions = {}
90 reparents = {}
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000091 downstreams = collections.defaultdict(list)
92 for branch, parent in git.topo_iter(branch_tree, top_down=False):
Dale Curtis06101932020-03-30 23:01:43 +000093 if git.is_dormant(branch):
94 continue
95
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000096 downstreams[parent].append(branch)
97
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +000098 # If branch and parent have the same tree, then branch has to be marked
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +000099 # for deletion and its children and grand-children reparented to parent.
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +0000100 if git.hash_one(branch+":") == git.hash_one(parent+":"):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000101 ensure_root_checkout()
102
103 logging.debug('branch %s merged to %s', branch, parent)
104
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000105 # Mark branch for deletion while remembering the ordering, then add all
106 # its children as grand-children of its parent and record reparenting
107 # information if necessary.
108 deletions[branch] = len(deletions)
109
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000110 for down in downstreams[branch]:
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000111 if down in deletions:
112 continue
113
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000114 # Record the new and old parent for down, or update such a record
115 # if it already exists. Keep track of the ordering so that reparenting
116 # happen in topological order.
117 downstreams[parent].append(down)
118 if down not in reparents:
119 reparents[down] = (len(reparents), parent, branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000120 else:
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000121 order, _, old_parent = reparents[down]
122 reparents[down] = (order, parent, old_parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000123
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000124 # Apply all reparenting recorded, in order.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000125 for branch, value in sorted(reparents.items(), key=lambda x:x[1][0]):
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000126 _, parent, old_parent = value
127 if parent in tag_set:
128 git.set_branch_config(branch, 'remote', '.')
129 git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent)
Raul Tambre80ee78e2019-05-06 22:41:05 +0000130 print('Reparented %s to track %s [tag] (was tracking %s)' %
131 (branch, parent, old_parent))
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000132 else:
133 git.run('branch', '--set-upstream-to', parent, branch)
Raul Tambre80ee78e2019-05-06 22:41:05 +0000134 print('Reparented %s to track %s (was tracking %s)' % (branch, parent,
135 old_parent))
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000136
137 # Apply all deletions recorded, in order.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000138 for branch, _ in sorted(deletions.items(), key=lambda x: x[1]):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000139 print(git.run('branch', '-d', branch))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000140
141
Joanna Wang677da3c2023-04-10 19:44:07 +0000142def rebase_branch(branch, parent, start_hash):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000143 logging.debug('considering %s(%s) -> %s(%s) : %s',
144 branch, git.hash_one(branch), parent, git.hash_one(parent),
145 start_hash)
146
147 # If parent has FROZEN commits, don't base branch on top of them. Instead,
148 # base branch on top of whatever commit is before them.
149 back_ups = 0
150 orig_parent = parent
151 while git.run('log', '-n1', '--format=%s',
152 parent, '--').startswith(git.FREEZE):
153 back_ups += 1
154 parent = git.run('rev-parse', parent+'~')
155
156 if back_ups:
157 logging.debug('Backed parent up by %d from %s to %s',
158 back_ups, orig_parent, parent)
159
160 if git.hash_one(parent) != start_hash:
161 # Try a plain rebase first
Raul Tambre80ee78e2019-05-06 22:41:05 +0000162 print('Rebasing:', branch)
Joanna Wang677da3c2023-04-10 19:44:07 +0000163 rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000164 if not rebase_ret.success:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000165 # TODO(iannucci): Find collapsible branches in a smarter way?
Raul Tambre80ee78e2019-05-06 22:41:05 +0000166 print("Failed! Attempting to squash", branch, "...", end=' ')
Andrew Moylanbfc40822017-10-25 11:23:36 +1100167 sys.stdout.flush()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000168 squash_branch = branch+"_squash_attempt"
169 git.run('checkout', '-b', squash_branch)
170 git.squash_current_branch(merge_base=start_hash)
171
172 # Try to rebase the branch_squash_attempt branch to see if it's empty.
173 squash_ret = git.rebase(parent, start_hash, squash_branch, 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:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000178 print('Success!')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000179 git.squash_current_branch(merge_base=start_hash)
180 git.rebase(parent, start_hash, branch)
181 else:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000182 print("Failed!")
183 print()
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000184
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000185 # rebase and leave in mid-rebase state.
sbc@chromium.org384039b2014-10-13 21:01:00 +0000186 # This second rebase attempt should always fail in the same
187 # way that the first one does. If it magically succeeds then
188 # something very strange has happened.
189 second_rebase_ret = git.rebase(parent, start_hash, branch)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000190 if second_rebase_ret.success: # pragma: no cover
Raul Tambre80ee78e2019-05-06 22:41:05 +0000191 print("Second rebase succeeded unexpectedly!")
192 print("Please see: http://crbug.com/425696")
193 print("First rebased failed with:")
194 print(rebase_ret.stderr)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000195 else:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000196 print("Here's what git-rebase (squashed) had to say:")
197 print()
Wezfef5cf82020-04-23 06:40:49 +0000198 print(squash_ret.stdout)
199 print(squash_ret.stderr)
Raul Tambre80ee78e2019-05-06 22:41:05 +0000200 print(textwrap.dedent("""\
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000201 Squashing failed. You probably have a real merge conflict.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000202
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000203 Your working copy is in mid-rebase. Either:
204 * completely resolve like a normal git-rebase; OR
205 * abort the rebase and mark this branch as dormant:
Chloe Pellinge515e5d2022-04-05 16:37:53 +0000206 git rebase --abort && \\
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000207 git config branch.%s.dormant true
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000208
Victor Vianna9a6aa082022-11-29 00:59:52 +0000209 And then run `git rebase-update -n` to resume.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000210 """ % branch))
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000211 return False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000212 else:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000213 print('%s up-to-date' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000214
215 git.remove_merge_base(branch)
216 git.get_or_create_merge_base(branch)
217
218 return True
219
220
sbc@chromium.org013731e2015-02-26 18:28:43 +0000221def main(args=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000222 parser = argparse.ArgumentParser()
223 parser.add_argument('--verbose', '-v', action='store_true')
stip@chromium.org74374f92015-09-10 23:47:24 +0000224 parser.add_argument('--keep-going', '-k', action='store_true',
225 help='Keep processing past failed rebases.')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000226 parser.add_argument('--no_fetch', '--no-fetch', '-n',
227 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000228 help='Skip fetching remotes.')
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000229 parser.add_argument(
230 '--current', action='store_true', help='Only rebase the current branch.')
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000231 parser.add_argument('branches', nargs='*',
232 help='Branches to be rebased. All branches are assumed '
233 'if none specified.')
Allen Bauer8e404a72020-07-10 21:22:54 +0000234 parser.add_argument('--keep-empty', '-e', action='store_true',
235 help='Do not automatically delete empty branches.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000236 opts = parser.parse_args(args)
237
238 if opts.verbose: # pragma: no cover
239 logging.getLogger().setLevel(logging.DEBUG)
240
241 # TODO(iannucci): snapshot all branches somehow, so we can implement
242 # `git rebase-update --undo`.
243 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
244 # * commit them to a secret ref?
245 # * Then we could view a summary of each run as a
246 # `diff --stat` on that secret ref.
247
248 if git.in_rebase():
249 # TODO(iannucci): Be able to resume rebase with flags like --continue,
250 # etc.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000251 print('Rebase in progress. Please complete the rebase before running '
252 '`git rebase-update`.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000253 return 1
254
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000255 return_branch, return_workdir = find_return_branch_workdir()
256 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000257
Gavin Mak94507672021-09-28 21:11:29 +0000258 if git.current_branch() == 'HEAD':
Robert Iannuccic5dab152023-07-11 23:56:17 +0000259 if git.run('status', '--porcelain', '--ignore-submodules=all'):
Gavin Mak94507672021-09-28 21:11:29 +0000260 print('Cannot rebase-update with detached head + uncommitted changes.')
261 return 1
262 else:
263 git.freeze() # just in case there are any local changes.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000264
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000265 branches_to_rebase = set(opts.branches)
266 if opts.current:
267 branches_to_rebase.add(git.current_branch())
268
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000269 skipped, branch_tree = git.get_branch_tree(use_limit=not opts.current)
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000270 if branches_to_rebase:
271 skipped = set(skipped).intersection(branches_to_rebase)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000272 for branch in skipped:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000273 print('Skipping %s: No upstream specified' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000274
275 if not opts.no_fetch:
276 fetch_remotes(branch_tree)
277
278 merge_base = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000279 for branch, parent in branch_tree.items():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000280 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
281
282 logging.debug('branch_tree: %s' % pformat(branch_tree))
283 logging.debug('merge_base: %s' % pformat(merge_base))
284
285 retcode = 0
stip@chromium.org74374f92015-09-10 23:47:24 +0000286 unrebased_branches = []
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000287 # Rebase each branch starting with the root-most branches and working
288 # towards the leaves.
289 for branch, parent in git.topo_iter(branch_tree):
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000290 # Only rebase specified branches, unless none specified.
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000291 if branches_to_rebase and branch not in branches_to_rebase:
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000292 continue
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000293 if git.is_dormant(branch):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000294 print('Skipping dormant branch', branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000295 else:
Joanna Wang677da3c2023-04-10 19:44:07 +0000296 ret = rebase_branch(branch, parent, merge_base[branch])
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000297 if not ret:
298 retcode = 1
stip@chromium.org74374f92015-09-10 23:47:24 +0000299
300 if opts.keep_going:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000301 print('--keep-going set, continuing with next branch.')
stip@chromium.org74374f92015-09-10 23:47:24 +0000302 unrebased_branches.append(branch)
303 if git.in_rebase():
304 git.run_with_retcode('rebase', '--abort')
305 if git.in_rebase(): # pragma: no cover
Raul Tambre80ee78e2019-05-06 22:41:05 +0000306 print('Failed to abort rebase. Something is really wrong.')
stip@chromium.org74374f92015-09-10 23:47:24 +0000307 break
308 else:
309 break
310
311 if unrebased_branches:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000312 print()
313 print('The following branches could not be cleanly rebased:')
stip@chromium.org74374f92015-09-10 23:47:24 +0000314 for branch in unrebased_branches:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000315 print(' %s' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000316
317 if not retcode:
Allen Bauer8e404a72020-07-10 21:22:54 +0000318 if not opts.keep_empty:
319 remove_empty_branches(branch_tree)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000320
321 # return_branch may not be there any more.
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000322 if return_branch in git.branches(use_limit=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000323 git.run('checkout', return_branch)
Gavin Mak94507672021-09-28 21:11:29 +0000324 git.thaw()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000325 else:
326 root_branch = git.root()
327 if return_branch != 'HEAD':
Edward Lemur12a537f2019-10-03 21:57:15 +0000328 print("%s was merged with its parent, checking out %s instead." %
329 (git.unicode_repr(return_branch), git.unicode_repr(root_branch)))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000330 git.run('checkout', root_branch)
Robert Iannuccic87e36a2017-01-23 17:16:54 -0800331
332 # return_workdir may also not be there any more.
iannucci@chromium.org196809e2015-06-12 02:10:04 +0000333 if return_workdir:
Robert Iannuccic87e36a2017-01-23 17:16:54 -0800334 try:
335 os.chdir(return_workdir)
336 except OSError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000337 print(
338 "Unable to return to original workdir %r: %s" % (return_workdir, e))
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000339 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000340 git.set_config(STARTING_WORKDIR_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000341
Robert Iannuccid3acb162021-05-04 21:37:40 +0000342 print()
343 print("Running `git gc --auto` - Ctrl-C to abort is OK.")
344 git.run('gc', '--auto')
345
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000346 return retcode
347
348
349if __name__ == '__main__': # pragma: no cover
sbc@chromium.org013731e2015-02-26 18:28:43 +0000350 try:
351 sys.exit(main())
352 except KeyboardInterrupt:
353 sys.stderr.write('interrupted\n')
354 sys.exit(1)