blob: 89eef39803968b93cdac3370ed2d7a3cc718fa79 [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
Raul Tambre80ee78e2019-05-06 22:41:05 +000010from __future__ import print_function
11
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000012import argparse
13import collections
14import logging
15import sys
16import textwrap
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000017import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000018
szager@chromium.org937159d2014-09-24 17:25:45 +000019from fnmatch import fnmatch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000020from pprint import pformat
21
22import git_common as git
23
24
25STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch'
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000026STARTING_WORKDIR_KEY = 'depot-tools.rebase-update.starting-workdir'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000027
28
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000029def find_return_branch_workdir():
30 """Finds the branch and working directory which we should return to after
31 rebase-update completes.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000032
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000033 These values may persist across multiple invocations of rebase-update, if
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000034 rebase-update runs into a conflict mid-way.
35 """
agable7aa2ddd2016-06-21 07:47:00 -070036 return_branch = git.get_config(STARTING_BRANCH_KEY)
37 workdir = git.get_config(STARTING_WORKDIR_KEY)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +000038 if not return_branch:
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000039 workdir = os.getcwd()
40 git.set_config(STARTING_WORKDIR_KEY, workdir)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000041 return_branch = git.current_branch()
42 if return_branch != 'HEAD':
43 git.set_config(STARTING_BRANCH_KEY, return_branch)
44
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000045 return return_branch, workdir
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000046
47
48def fetch_remotes(branch_tree):
49 """Fetches all remotes which are needed to update |branch_tree|."""
50 fetch_tags = False
51 remotes = set()
52 tag_set = git.tags()
szager@chromium.org937159d2014-09-24 17:25:45 +000053 fetchspec_map = {}
agable7aa2ddd2016-06-21 07:47:00 -070054 all_fetchspec_configs = git.get_config_regexp(r'^remote\..*\.fetch')
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000055 for fetchspec_config in all_fetchspec_configs:
szager@chromium.org937159d2014-09-24 17:25:45 +000056 key, _, fetchspec = fetchspec_config.partition(' ')
57 dest_spec = fetchspec.partition(':')[2]
58 remote_name = key.split('.')[1]
59 fetchspec_map[dest_spec] = remote_name
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000060 for parent in branch_tree.values():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000061 if parent in tag_set:
62 fetch_tags = True
63 else:
64 full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000065 for dest_spec, remote_name in fetchspec_map.items():
szager@chromium.org937159d2014-09-24 17:25:45 +000066 if fnmatch(full_ref, dest_spec):
67 remotes.add(remote_name)
68 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000069
70 fetch_args = []
71 if fetch_tags:
72 # Need to fetch all because we don't know what remote the tag comes from :(
73 # TODO(iannucci): assert that the tags are in the remote fetch refspec
74 fetch_args = ['--all']
75 else:
76 fetch_args.append('--multiple')
77 fetch_args.extend(remotes)
78 # TODO(iannucci): Should we fetch git-svn?
79
80 if not fetch_args: # pragma: no cover
Raul Tambre80ee78e2019-05-06 22:41:05 +000081 print('Nothing to fetch.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000082 else:
iannucci@chromium.org43f4ecc2014-05-08 19:22:47 +000083 git.run_with_stderr('fetch', *fetch_args, stdout=sys.stdout,
84 stderr=sys.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000085
86
87def remove_empty_branches(branch_tree):
88 tag_set = git.tags()
89 ensure_root_checkout = git.once(lambda: git.run('checkout', git.root()))
90
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +000091 deletions = {}
92 reparents = {}
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000093 downstreams = collections.defaultdict(list)
94 for branch, parent in git.topo_iter(branch_tree, top_down=False):
Dale Curtis06101932020-03-30 23:01:43 +000095 if git.is_dormant(branch):
96 continue
97
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000098 downstreams[parent].append(branch)
99
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +0000100 # If branch and parent have the same tree, then branch has to be marked
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000101 # for deletion and its children and grand-children reparented to parent.
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +0000102 if git.hash_one(branch+":") == git.hash_one(parent+":"):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000103 ensure_root_checkout()
104
105 logging.debug('branch %s merged to %s', branch, parent)
106
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000107 # Mark branch for deletion while remembering the ordering, then add all
108 # its children as grand-children of its parent and record reparenting
109 # information if necessary.
110 deletions[branch] = len(deletions)
111
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000112 for down in downstreams[branch]:
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000113 if down in deletions:
114 continue
115
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000116 # Record the new and old parent for down, or update such a record
117 # if it already exists. Keep track of the ordering so that reparenting
118 # happen in topological order.
119 downstreams[parent].append(down)
120 if down not in reparents:
121 reparents[down] = (len(reparents), parent, branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000122 else:
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000123 order, _, old_parent = reparents[down]
124 reparents[down] = (order, parent, old_parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000125
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000126 # Apply all reparenting recorded, in order.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000127 for branch, value in sorted(reparents.items(), key=lambda x:x[1][0]):
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000128 _, parent, old_parent = value
129 if parent in tag_set:
130 git.set_branch_config(branch, 'remote', '.')
131 git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent)
Raul Tambre80ee78e2019-05-06 22:41:05 +0000132 print('Reparented %s to track %s [tag] (was tracking %s)' %
133 (branch, parent, old_parent))
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000134 else:
135 git.run('branch', '--set-upstream-to', parent, branch)
Raul Tambre80ee78e2019-05-06 22:41:05 +0000136 print('Reparented %s to track %s (was tracking %s)' % (branch, parent,
137 old_parent))
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000138
139 # Apply all deletions recorded, in order.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000140 for branch, _ in sorted(deletions.items(), key=lambda x: x[1]):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000141 print(git.run('branch', '-d', branch))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000142
143
Joey Arhar80cc67c2023-04-10 16:31:39 +0000144def rebase_branch(branch, parent, start_hash, no_squash):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000145 logging.debug('considering %s(%s) -> %s(%s) : %s',
146 branch, git.hash_one(branch), parent, git.hash_one(parent),
147 start_hash)
148
149 # If parent has FROZEN commits, don't base branch on top of them. Instead,
150 # base branch on top of whatever commit is before them.
151 back_ups = 0
152 orig_parent = parent
153 while git.run('log', '-n1', '--format=%s',
154 parent, '--').startswith(git.FREEZE):
155 back_ups += 1
156 parent = git.run('rev-parse', parent+'~')
157
158 if back_ups:
159 logging.debug('Backed parent up by %d from %s to %s',
160 back_ups, orig_parent, parent)
161
162 if git.hash_one(parent) != start_hash:
163 # Try a plain rebase first
Raul Tambre80ee78e2019-05-06 22:41:05 +0000164 print('Rebasing:', branch)
Joey Arhar80cc67c2023-04-10 16:31:39 +0000165 rebase_ret = git.rebase(parent, start_hash, branch, abort = not no_squash)
sbc@chromium.org384039b2014-10-13 21:01:00 +0000166 if not rebase_ret.success:
Joey Arhar80cc67c2023-04-10 16:31:39 +0000167 if no_squash:
168 print(textwrap.dedent("""\
169 Your working copy is in mid-rebase. Either:
170 * completely resolve like a normal git-rebase; OR
171 * abort the rebase and mark this branch as dormant:
172 git config branch.%s.dormant true
173
174 And then run `git rebase-update` again to resume.
175 """ % branch))
176 return False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000177 # TODO(iannucci): Find collapsible branches in a smarter way?
Raul Tambre80ee78e2019-05-06 22:41:05 +0000178 print("Failed! Attempting to squash", branch, "...", end=' ')
Andrew Moylanbfc40822017-10-25 11:23:36 +1100179 sys.stdout.flush()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000180 squash_branch = branch+"_squash_attempt"
181 git.run('checkout', '-b', squash_branch)
182 git.squash_current_branch(merge_base=start_hash)
183
184 # Try to rebase the branch_squash_attempt branch to see if it's empty.
185 squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
186 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
187 git.run('checkout', branch)
188 git.run('branch', '-D', squash_branch)
189 if squash_ret.success and empty_rebase:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000190 print('Success!')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000191 git.squash_current_branch(merge_base=start_hash)
192 git.rebase(parent, start_hash, branch)
193 else:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000194 print("Failed!")
195 print()
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000196
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000197 # rebase and leave in mid-rebase state.
sbc@chromium.org384039b2014-10-13 21:01:00 +0000198 # This second rebase attempt should always fail in the same
199 # way that the first one does. If it magically succeeds then
200 # something very strange has happened.
201 second_rebase_ret = git.rebase(parent, start_hash, branch)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000202 if second_rebase_ret.success: # pragma: no cover
Raul Tambre80ee78e2019-05-06 22:41:05 +0000203 print("Second rebase succeeded unexpectedly!")
204 print("Please see: http://crbug.com/425696")
205 print("First rebased failed with:")
206 print(rebase_ret.stderr)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000207 else:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000208 print("Here's what git-rebase (squashed) had to say:")
209 print()
Wezfef5cf82020-04-23 06:40:49 +0000210 print(squash_ret.stdout)
211 print(squash_ret.stderr)
Raul Tambre80ee78e2019-05-06 22:41:05 +0000212 print(textwrap.dedent("""\
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000213 Squashing failed. You probably have a real merge conflict.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000214
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000215 Your working copy is in mid-rebase. Either:
216 * completely resolve like a normal git-rebase; OR
217 * abort the rebase and mark this branch as dormant:
Chloe Pellinge515e5d2022-04-05 16:37:53 +0000218 git rebase --abort && \\
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000219 git config branch.%s.dormant true
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000220
Victor Vianna9a6aa082022-11-29 00:59:52 +0000221 And then run `git rebase-update -n` to resume.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000222 """ % branch))
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000223 return False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000224 else:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000225 print('%s up-to-date' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000226
227 git.remove_merge_base(branch)
228 git.get_or_create_merge_base(branch)
229
230 return True
231
232
sbc@chromium.org013731e2015-02-26 18:28:43 +0000233def main(args=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000234 parser = argparse.ArgumentParser()
235 parser.add_argument('--verbose', '-v', action='store_true')
stip@chromium.org74374f92015-09-10 23:47:24 +0000236 parser.add_argument('--keep-going', '-k', action='store_true',
237 help='Keep processing past failed rebases.')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000238 parser.add_argument('--no_fetch', '--no-fetch', '-n',
239 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000240 help='Skip fetching remotes.')
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000241 parser.add_argument(
242 '--current', action='store_true', help='Only rebase the current branch.')
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000243 parser.add_argument('branches', nargs='*',
244 help='Branches to be rebased. All branches are assumed '
245 'if none specified.')
Allen Bauer8e404a72020-07-10 21:22:54 +0000246 parser.add_argument('--keep-empty', '-e', action='store_true',
247 help='Do not automatically delete empty branches.')
Joey Arhar80cc67c2023-04-10 16:31:39 +0000248 parser.add_argument(
249 '--no-squash', action='store_true',
250 help='Will not try to squash branches when rebasing fails.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000251 opts = parser.parse_args(args)
252
253 if opts.verbose: # pragma: no cover
254 logging.getLogger().setLevel(logging.DEBUG)
255
256 # TODO(iannucci): snapshot all branches somehow, so we can implement
257 # `git rebase-update --undo`.
258 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
259 # * commit them to a secret ref?
260 # * Then we could view a summary of each run as a
261 # `diff --stat` on that secret ref.
262
263 if git.in_rebase():
264 # TODO(iannucci): Be able to resume rebase with flags like --continue,
265 # etc.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000266 print('Rebase in progress. Please complete the rebase before running '
267 '`git rebase-update`.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000268 return 1
269
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000270 return_branch, return_workdir = find_return_branch_workdir()
271 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000272
Gavin Mak94507672021-09-28 21:11:29 +0000273 if git.current_branch() == 'HEAD':
274 if git.run('status', '--porcelain'):
275 print('Cannot rebase-update with detached head + uncommitted changes.')
276 return 1
277 else:
278 git.freeze() # just in case there are any local changes.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000279
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000280 branches_to_rebase = set(opts.branches)
281 if opts.current:
282 branches_to_rebase.add(git.current_branch())
283
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000284 skipped, branch_tree = git.get_branch_tree(use_limit=not opts.current)
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000285 if branches_to_rebase:
286 skipped = set(skipped).intersection(branches_to_rebase)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000287 for branch in skipped:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000288 print('Skipping %s: No upstream specified' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000289
290 if not opts.no_fetch:
291 fetch_remotes(branch_tree)
292
293 merge_base = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000294 for branch, parent in branch_tree.items():
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000295 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
296
297 logging.debug('branch_tree: %s' % pformat(branch_tree))
298 logging.debug('merge_base: %s' % pformat(merge_base))
299
300 retcode = 0
stip@chromium.org74374f92015-09-10 23:47:24 +0000301 unrebased_branches = []
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000302 # Rebase each branch starting with the root-most branches and working
303 # towards the leaves.
304 for branch, parent in git.topo_iter(branch_tree):
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000305 # Only rebase specified branches, unless none specified.
Henrique Ferreirofe83cfa2019-02-28 20:02:45 +0000306 if branches_to_rebase and branch not in branches_to_rebase:
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000307 continue
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000308 if git.is_dormant(branch):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000309 print('Skipping dormant branch', branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000310 else:
Joey Arhar80cc67c2023-04-10 16:31:39 +0000311 ret = rebase_branch(branch, parent, merge_base[branch], opts.no_squash)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000312 if not ret:
313 retcode = 1
stip@chromium.org74374f92015-09-10 23:47:24 +0000314
315 if opts.keep_going:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000316 print('--keep-going set, continuing with next branch.')
stip@chromium.org74374f92015-09-10 23:47:24 +0000317 unrebased_branches.append(branch)
318 if git.in_rebase():
319 git.run_with_retcode('rebase', '--abort')
320 if git.in_rebase(): # pragma: no cover
Raul Tambre80ee78e2019-05-06 22:41:05 +0000321 print('Failed to abort rebase. Something is really wrong.')
stip@chromium.org74374f92015-09-10 23:47:24 +0000322 break
323 else:
324 break
325
326 if unrebased_branches:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000327 print()
328 print('The following branches could not be cleanly rebased:')
stip@chromium.org74374f92015-09-10 23:47:24 +0000329 for branch in unrebased_branches:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000330 print(' %s' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000331
332 if not retcode:
Allen Bauer8e404a72020-07-10 21:22:54 +0000333 if not opts.keep_empty:
334 remove_empty_branches(branch_tree)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000335
336 # return_branch may not be there any more.
Gavin Mak2cbe95c2023-03-06 22:39:56 +0000337 if return_branch in git.branches(use_limit=False):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000338 git.run('checkout', return_branch)
Gavin Mak94507672021-09-28 21:11:29 +0000339 git.thaw()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000340 else:
341 root_branch = git.root()
342 if return_branch != 'HEAD':
Edward Lemur12a537f2019-10-03 21:57:15 +0000343 print("%s was merged with its parent, checking out %s instead." %
344 (git.unicode_repr(return_branch), git.unicode_repr(root_branch)))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000345 git.run('checkout', root_branch)
Robert Iannuccic87e36a2017-01-23 17:16:54 -0800346
347 # return_workdir may also not be there any more.
iannucci@chromium.org196809e2015-06-12 02:10:04 +0000348 if return_workdir:
Robert Iannuccic87e36a2017-01-23 17:16:54 -0800349 try:
350 os.chdir(return_workdir)
351 except OSError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000352 print(
353 "Unable to return to original workdir %r: %s" % (return_workdir, e))
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000354 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000355 git.set_config(STARTING_WORKDIR_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000356
Robert Iannuccid3acb162021-05-04 21:37:40 +0000357 print()
358 print("Running `git gc --auto` - Ctrl-C to abort is OK.")
359 git.run('gc', '--auto')
360
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000361 return retcode
362
363
364if __name__ == '__main__': # pragma: no cover
sbc@chromium.org013731e2015-02-26 18:28:43 +0000365 try:
366 sys.exit(main())
367 except KeyboardInterrupt:
368 sys.stderr.write('interrupted\n')
369 sys.exit(1)