blob: 13be0d6ab8947ae7a297201a15cd2c025d192402 [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.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00005"""
6Tool to update all branches to have the latest changes from their upstreams.
7"""
8
9import argparse
10import collections
11import logging
12import sys
13import textwrap
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000014import os
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000015
szager@chromium.org937159d2014-09-24 17:25:45 +000016from fnmatch import fnmatch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000017from pprint import pformat
18
19import git_common as git
20
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000021STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch'
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000022STARTING_WORKDIR_KEY = 'depot-tools.rebase-update.starting-workdir'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000023
24
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000025def find_return_branch_workdir():
Mike Frysinger124bb8e2023-09-06 05:48:55 +000026 """Finds the branch and working directory which we should return to after
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000027 rebase-update completes.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000028
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000029 These values may persist across multiple invocations of rebase-update, if
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000030 rebase-update runs into a conflict mid-way.
31 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +000032 return_branch = git.get_config(STARTING_BRANCH_KEY)
33 workdir = git.get_config(STARTING_WORKDIR_KEY)
34 if not return_branch:
35 workdir = os.getcwd()
36 git.set_config(STARTING_WORKDIR_KEY, workdir)
37 return_branch = git.current_branch()
38 if return_branch != 'HEAD':
39 git.set_config(STARTING_BRANCH_KEY, return_branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000040
Mike Frysinger124bb8e2023-09-06 05:48:55 +000041 return return_branch, workdir
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000042
43
44def fetch_remotes(branch_tree):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000045 """Fetches all remotes which are needed to update |branch_tree|."""
46 fetch_tags = False
47 remotes = set()
48 tag_set = git.tags()
49 fetchspec_map = {}
50 all_fetchspec_configs = git.get_config_regexp(r'^remote\..*\.fetch')
51 for fetchspec_config in all_fetchspec_configs:
52 key, _, fetchspec = fetchspec_config.partition(' ')
53 dest_spec = fetchspec.partition(':')[2]
54 remote_name = key.split('.')[1]
55 fetchspec_map[dest_spec] = remote_name
56 for parent in branch_tree.values():
57 if parent in tag_set:
58 fetch_tags = True
59 else:
60 full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
61 for dest_spec, remote_name in fetchspec_map.items():
62 if fnmatch(full_ref, dest_spec):
63 remotes.add(remote_name)
64 break
65
66 fetch_args = []
67 if fetch_tags:
68 # Need to fetch all because we don't know what remote the tag comes from
69 # :( TODO(iannucci): assert that the tags are in the remote fetch
70 # refspec
71 fetch_args = ['--all']
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000072 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +000073 fetch_args.append('--multiple')
74 fetch_args.extend(remotes)
75 # TODO(iannucci): Should we fetch git-svn?
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000076
Mike Frysinger124bb8e2023-09-06 05:48:55 +000077 if not fetch_args: # pragma: no cover
78 print('Nothing to fetch.')
79 else:
80 git.run_with_stderr('fetch',
81 *fetch_args,
82 stdout=sys.stdout,
83 stderr=sys.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000084
85
86def remove_empty_branches(branch_tree):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000087 tag_set = git.tags()
88 ensure_root_checkout = git.once(lambda: git.run('checkout', git.root()))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000089
Mike Frysinger124bb8e2023-09-06 05:48:55 +000090 deletions = {}
91 reparents = {}
92 downstreams = collections.defaultdict(list)
93 for branch, parent in git.topo_iter(branch_tree, top_down=False):
94 if git.is_dormant(branch):
95 continue
Dale Curtis06101932020-03-30 23:01:43 +000096
Mike Frysinger124bb8e2023-09-06 05:48:55 +000097 downstreams[parent].append(branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000098
Mike Frysinger124bb8e2023-09-06 05:48:55 +000099 # If branch and parent have the same tree, then branch has to be marked
100 # for deletion and its children and grand-children reparented to parent.
101 if git.hash_one(branch + ":") == git.hash_one(parent + ":"):
102 ensure_root_checkout()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000103
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000104 logging.debug('branch %s merged to %s', branch, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000105
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000106 # Mark branch for deletion while remembering the ordering, then add
107 # all its children as grand-children of its parent and record
108 # reparenting information if necessary.
109 deletions[branch] = len(deletions)
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000110
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000111 for down in downstreams[branch]:
112 if down in deletions:
113 continue
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000114
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000115 # Record the new and old parent for down, or update such a
116 # record if it already exists. Keep track of the ordering so
117 # that reparenting happen in topological order.
118 downstreams[parent].append(down)
119 if down not in reparents:
120 reparents[down] = (len(reparents), parent, branch)
121 else:
122 order, _, old_parent = reparents[down]
123 reparents[down] = (order, parent, old_parent)
124
125 # Apply all reparenting recorded, in order.
126 for branch, value in sorted(reparents.items(), key=lambda x: x[1][0]):
127 _, parent, old_parent = value
128 if parent in tag_set:
129 git.set_branch_config(branch, 'remote', '.')
130 git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent)
131 print('Reparented %s to track %s [tag] (was tracking %s)' %
132 (branch, parent, old_parent))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000133 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000134 git.run('branch', '--set-upstream-to', parent, branch)
135 print('Reparented %s to track %s (was tracking %s)' %
136 (branch, parent, old_parent))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000137
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000138 # Apply all deletions recorded, in order.
139 for branch, _ in sorted(deletions.items(), key=lambda x: x[1]):
140 print(git.run('branch', '-d', branch))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000141
142
Joanna Wang677da3c2023-04-10 19:44:07 +0000143def rebase_branch(branch, parent, start_hash):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000144 logging.debug('considering %s(%s) -> %s(%s) : %s', branch,
145 git.hash_one(branch), parent, git.hash_one(parent),
146 start_hash)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000147
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000148 # If parent has FROZEN commits, don't base branch on top of them. Instead,
149 # base branch on top of whatever commit is before them.
150 back_ups = 0
151 orig_parent = parent
152 while git.run('log', '-n1', '--format=%s', parent,
153 '--').startswith(git.FREEZE):
154 back_ups += 1
155 parent = git.run('rev-parse', parent + '~')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000156
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000157 if back_ups:
158 logging.debug('Backed parent up by %d from %s to %s', back_ups,
159 orig_parent, parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000160
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000161 if git.hash_one(parent) != start_hash:
162 # Try a plain rebase first
163 print('Rebasing:', branch)
164 rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
165 if not rebase_ret.success:
166 # TODO(iannucci): Find collapsible branches in a smarter way?
167 print("Failed! Attempting to squash", branch, "...", end=' ')
168 sys.stdout.flush()
169 squash_branch = branch + "_squash_attempt"
170 git.run('checkout', '-b', squash_branch)
171 git.squash_current_branch(merge_base=start_hash)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000172
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000173 # Try to rebase the branch_squash_attempt branch to see if it's
174 # empty.
175 squash_ret = git.rebase(parent,
176 start_hash,
177 squash_branch,
178 abort=True)
179 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
180 git.run('checkout', branch)
181 git.run('branch', '-D', squash_branch)
182 if squash_ret.success and empty_rebase:
183 print('Success!')
184 git.squash_current_branch(merge_base=start_hash)
185 git.rebase(parent, start_hash, branch)
186 else:
187 print("Failed!")
188 print()
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000189
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000190 # rebase and leave in mid-rebase state.
191 # This second rebase attempt should always fail in the same
192 # way that the first one does. If it magically succeeds then
193 # something very strange has happened.
194 second_rebase_ret = git.rebase(parent, start_hash, branch)
195 if second_rebase_ret.success: # pragma: no cover
196 print("Second rebase succeeded unexpectedly!")
197 print("Please see: http://crbug.com/425696")
198 print("First rebased failed with:")
199 print(rebase_ret.stderr)
200 else:
201 print("Here's what git-rebase (squashed) had to say:")
202 print()
203 print(squash_ret.stdout)
204 print(squash_ret.stderr)
205 print(
206 textwrap.dedent("""\
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000207 Squashing failed. You probably have a real merge conflict.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000208
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000209 Your working copy is in mid-rebase. Either:
210 * completely resolve like a normal git-rebase; OR
211 * abort the rebase and mark this branch as dormant:
Chloe Pellinge515e5d2022-04-05 16:37:53 +0000212 git rebase --abort && \\
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000213 git config branch.%s.dormant true
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000214
Victor Vianna9a6aa082022-11-29 00:59:52 +0000215 And then run `git rebase-update -n` to resume.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000216 """ % branch))
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000217 return False
218 else:
219 print('%s up-to-date' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000220
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000221 git.remove_merge_base(branch)
222 git.get_or_create_merge_base(branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000223
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000224 return True
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000225
226
sbc@chromium.org013731e2015-02-26 18:28:43 +0000227def main(args=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000228 parser = argparse.ArgumentParser()
229 parser.add_argument('--verbose', '-v', action='store_true')
230 parser.add_argument('--keep-going',
231 '-k',
232 action='store_true',
233 help='Keep processing past failed rebases.')
234 parser.add_argument('--no_fetch',
235 '--no-fetch',
236 '-n',
237 action='store_true',
238 help='Skip fetching remotes.')
239 parser.add_argument('--current',
240 action='store_true',
241 help='Only rebase the current branch.')
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 opts = parser.parse_args(args)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000251
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000252 if opts.verbose: # pragma: no cover
253 logging.getLogger().setLevel(logging.DEBUG)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000254
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000255 # TODO(iannucci): snapshot all branches somehow, so we can implement
256 # `git rebase-update --undo`.
257 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
258 # * commit them to a secret ref?
259 # * Then we could view a summary of each run as a
260 # `diff --stat` on that secret ref.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000261
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000262 if git.in_rebase():
263 # TODO(iannucci): Be able to resume rebase with flags like --continue,
264 # etc.
265 print('Rebase in progress. Please complete the rebase before running '
266 '`git rebase-update`.')
267 return 1
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000268
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000269 return_branch, return_workdir = find_return_branch_workdir()
270 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000271
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000272 if git.current_branch() == 'HEAD':
273 if git.run('status', '--porcelain', '--ignore-submodules=all'):
274 print(
275 'Cannot rebase-update with detached head + uncommitted changes.'
276 )
277 return 1
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000278 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000279 git.freeze() # just in case there are any local changes.
stip@chromium.org74374f92015-09-10 23:47:24 +0000280
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000281 branches_to_rebase = set(opts.branches)
282 if opts.current:
283 branches_to_rebase.add(git.current_branch())
284
285 skipped, branch_tree = git.get_branch_tree(use_limit=not opts.current)
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' % branch)
290
291 if not opts.no_fetch:
292 fetch_remotes(branch_tree)
293
294 merge_base = {}
295 for branch, parent in branch_tree.items():
296 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
297
298 logging.debug('branch_tree: %s' % pformat(branch_tree))
299 logging.debug('merge_base: %s' % pformat(merge_base))
300
301 retcode = 0
302 unrebased_branches = []
303 # Rebase each branch starting with the root-most branches and working
304 # towards the leaves.
305 for branch, parent in git.topo_iter(branch_tree):
306 # Only rebase specified branches, unless none specified.
307 if branches_to_rebase and branch not in branches_to_rebase:
308 continue
309 if git.is_dormant(branch):
310 print('Skipping dormant branch', branch)
stip@chromium.org74374f92015-09-10 23:47:24 +0000311 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000312 ret = rebase_branch(branch, parent, merge_base[branch])
313 if not ret:
314 retcode = 1
stip@chromium.org74374f92015-09-10 23:47:24 +0000315
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000316 if opts.keep_going:
317 print('--keep-going set, continuing with next branch.')
318 unrebased_branches.append(branch)
319 if git.in_rebase():
320 git.run_with_retcode('rebase', '--abort')
321 if git.in_rebase(): # pragma: no cover
322 print(
323 'Failed to abort rebase. Something is really wrong.'
324 )
325 break
326 else:
327 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000328
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000329 if unrebased_branches:
330 print()
331 print('The following branches could not be cleanly rebased:')
332 for branch in unrebased_branches:
333 print(' %s' % branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000334
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000335 if not retcode:
336 if not opts.keep_empty:
337 remove_empty_branches(branch_tree)
Robert Iannuccic87e36a2017-01-23 17:16:54 -0800338
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000339 # return_branch may not be there any more.
340 if return_branch in git.branches(use_limit=False):
341 git.run('checkout', return_branch)
342 git.thaw()
343 else:
344 root_branch = git.root()
345 if return_branch != 'HEAD':
346 print(
347 "%s was merged with its parent, checking out %s instead." %
348 (git.unicode_repr(return_branch),
349 git.unicode_repr(root_branch)))
350 git.run('checkout', root_branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000351
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000352 # return_workdir may also not be there any more.
353 if return_workdir:
354 try:
355 os.chdir(return_workdir)
356 except OSError as e:
357 print("Unable to return to original workdir %r: %s" %
358 (return_workdir, e))
359 git.set_config(STARTING_BRANCH_KEY, '')
360 git.set_config(STARTING_WORKDIR_KEY, '')
Robert Iannuccid3acb162021-05-04 21:37:40 +0000361
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000362 print()
363 print("Running `git gc --auto` - Ctrl-C to abort is OK.")
364 git.run('gc', '--auto')
365
366 return retcode
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000367
368
369if __name__ == '__main__': # pragma: no cover
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000370 try:
371 sys.exit(main())
372 except KeyboardInterrupt:
373 sys.stderr.write('interrupted\n')
374 sys.exit(1)