blob: e6cc930be686c1a818bb6fa8a7b88cea5b0c6126 [file] [log] [blame]
iannucci@chromium.org97231b52014-03-26 06:54:55 +00001#!/usr/bin/env python
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
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000058 for parent in branch_tree.itervalues():
59 if parent in tag_set:
60 fetch_tags = True
61 else:
62 full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
szager@chromium.org937159d2014-09-24 17:25:45 +000063 for dest_spec, remote_name in fetchspec_map.iteritems():
64 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
79 print 'Nothing to fetch.'
80 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):
93 downstreams[parent].append(branch)
94
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +000095 # If branch and parent have the same tree, then branch has to be marked
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +000096 # for deletion and its children and grand-children reparented to parent.
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +000097 if git.hash_one(branch+":") == git.hash_one(parent+":"):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000098 ensure_root_checkout()
99
100 logging.debug('branch %s merged to %s', branch, parent)
101
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000102 # Mark branch for deletion while remembering the ordering, then add all
103 # its children as grand-children of its parent and record reparenting
104 # information if necessary.
105 deletions[branch] = len(deletions)
106
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000107 for down in downstreams[branch]:
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000108 if down in deletions:
109 continue
110
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000111 # Record the new and old parent for down, or update such a record
112 # if it already exists. Keep track of the ordering so that reparenting
113 # happen in topological order.
114 downstreams[parent].append(down)
115 if down not in reparents:
116 reparents[down] = (len(reparents), parent, branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000117 else:
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000118 order, _, old_parent = reparents[down]
119 reparents[down] = (order, parent, old_parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000120
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000121 # Apply all reparenting recorded, in order.
122 for branch, value in sorted(reparents.iteritems(), key=lambda x:x[1][0]):
123 _, parent, old_parent = value
124 if parent in tag_set:
125 git.set_branch_config(branch, 'remote', '.')
126 git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent)
127 print ('Reparented %s to track %s [tag] (was tracking %s)'
128 % (branch, parent, old_parent))
129 else:
130 git.run('branch', '--set-upstream-to', parent, branch)
131 print ('Reparented %s to track %s (was tracking %s)'
132 % (branch, parent, old_parent))
133
134 # Apply all deletions recorded, in order.
135 for branch, _ in sorted(deletions.iteritems(), key=lambda x: x[1]):
136 print git.run('branch', '-d', branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000137
138
139def rebase_branch(branch, parent, start_hash):
140 logging.debug('considering %s(%s) -> %s(%s) : %s',
141 branch, git.hash_one(branch), parent, git.hash_one(parent),
142 start_hash)
143
144 # If parent has FROZEN commits, don't base branch on top of them. Instead,
145 # base branch on top of whatever commit is before them.
146 back_ups = 0
147 orig_parent = parent
148 while git.run('log', '-n1', '--format=%s',
149 parent, '--').startswith(git.FREEZE):
150 back_ups += 1
151 parent = git.run('rev-parse', parent+'~')
152
153 if back_ups:
154 logging.debug('Backed parent up by %d from %s to %s',
155 back_ups, orig_parent, parent)
156
157 if git.hash_one(parent) != start_hash:
158 # Try a plain rebase first
159 print 'Rebasing:', branch
sbc@chromium.org384039b2014-10-13 21:01:00 +0000160 rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
161 if not rebase_ret.success:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000162 # TODO(iannucci): Find collapsible branches in a smarter way?
163 print "Failed! Attempting to squash", branch, "...",
Andrew Moylanbfc40822017-10-25 11:23:36 +1100164 sys.stdout.flush()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000165 squash_branch = branch+"_squash_attempt"
166 git.run('checkout', '-b', squash_branch)
167 git.squash_current_branch(merge_base=start_hash)
168
169 # Try to rebase the branch_squash_attempt branch to see if it's empty.
170 squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
171 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
172 git.run('checkout', branch)
173 git.run('branch', '-D', squash_branch)
174 if squash_ret.success and empty_rebase:
175 print 'Success!'
176 git.squash_current_branch(merge_base=start_hash)
177 git.rebase(parent, start_hash, branch)
178 else:
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000179 print "Failed!"
180 print
181
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000182 # rebase and leave in mid-rebase state.
sbc@chromium.org384039b2014-10-13 21:01:00 +0000183 # This second rebase attempt should always fail in the same
184 # way that the first one does. If it magically succeeds then
185 # something very strange has happened.
186 second_rebase_ret = git.rebase(parent, start_hash, branch)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000187 if second_rebase_ret.success: # pragma: no cover
188 print "Second rebase succeeded unexpectedly!"
189 print "Please see: http://crbug.com/425696"
190 print "First rebased failed with:"
191 print rebase_ret.stderr
192 else:
193 print "Here's what git-rebase (squashed) had to say:"
194 print
195 print squash_ret.stdout
196 print squash_ret.stderr
197 print textwrap.dedent(
198 """\
199 Squashing failed. You probably have a real merge conflict.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000200
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000201 Your working copy is in mid-rebase. Either:
202 * completely resolve like a normal git-rebase; OR
203 * abort the rebase and mark this branch as dormant:
204 git config branch.%s.dormant true
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000205
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000206 And then run `git rebase-update` again to resume.
207 """ % branch)
208 return False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000209 else:
210 print '%s up-to-date' % branch
211
212 git.remove_merge_base(branch)
213 git.get_or_create_merge_base(branch)
214
215 return True
216
217
sbc@chromium.org013731e2015-02-26 18:28:43 +0000218def main(args=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000219 parser = argparse.ArgumentParser()
220 parser.add_argument('--verbose', '-v', action='store_true')
stip@chromium.org74374f92015-09-10 23:47:24 +0000221 parser.add_argument('--keep-going', '-k', action='store_true',
222 help='Keep processing past failed rebases.')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000223 parser.add_argument('--no_fetch', '--no-fetch', '-n',
224 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000225 help='Skip fetching remotes.')
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000226 parser.add_argument('branches', nargs='*',
227 help='Branches to be rebased. All branches are assumed '
228 'if none specified.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000229 opts = parser.parse_args(args)
230
231 if opts.verbose: # pragma: no cover
232 logging.getLogger().setLevel(logging.DEBUG)
233
234 # TODO(iannucci): snapshot all branches somehow, so we can implement
235 # `git rebase-update --undo`.
236 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
237 # * commit them to a secret ref?
238 # * Then we could view a summary of each run as a
239 # `diff --stat` on that secret ref.
240
241 if git.in_rebase():
242 # TODO(iannucci): Be able to resume rebase with flags like --continue,
243 # etc.
244 print (
245 'Rebase in progress. Please complete the rebase before running '
246 '`git rebase-update`.'
247 )
248 return 1
249
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000250 return_branch, return_workdir = find_return_branch_workdir()
251 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000252
253 if git.current_branch() == 'HEAD':
254 if git.run('status', '--porcelain'):
255 print 'Cannot rebase-update with detached head + uncommitted changes.'
256 return 1
257 else:
258 git.freeze() # just in case there are any local changes.
259
260 skipped, branch_tree = git.get_branch_tree()
261 for branch in skipped:
262 print 'Skipping %s: No upstream specified' % branch
263
264 if not opts.no_fetch:
265 fetch_remotes(branch_tree)
266
267 merge_base = {}
268 for branch, parent in branch_tree.iteritems():
269 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
270
271 logging.debug('branch_tree: %s' % pformat(branch_tree))
272 logging.debug('merge_base: %s' % pformat(merge_base))
273
274 retcode = 0
stip@chromium.org74374f92015-09-10 23:47:24 +0000275 unrebased_branches = []
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000276 # Rebase each branch starting with the root-most branches and working
277 # towards the leaves.
278 for branch, parent in git.topo_iter(branch_tree):
Sergiy Belozorovb58d4bd2018-12-13 14:08:49 +0000279 # Only rebase specified branches, unless none specified.
280 if opts.branches and branch not in opts.branches:
281 continue
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000282 if git.is_dormant(branch):
283 print 'Skipping dormant branch', branch
284 else:
285 ret = rebase_branch(branch, parent, merge_base[branch])
286 if not ret:
287 retcode = 1
stip@chromium.org74374f92015-09-10 23:47:24 +0000288
289 if opts.keep_going:
290 print '--keep-going set, continuing with next branch.'
291 unrebased_branches.append(branch)
292 if git.in_rebase():
293 git.run_with_retcode('rebase', '--abort')
294 if git.in_rebase(): # pragma: no cover
295 print 'Failed to abort rebase. Something is really wrong.'
296 break
297 else:
298 break
299
300 if unrebased_branches:
301 print
302 print 'The following branches could not be cleanly rebased:'
303 for branch in unrebased_branches:
304 print ' %s' % branch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000305
306 if not retcode:
307 remove_empty_branches(branch_tree)
308
309 # return_branch may not be there any more.
310 if return_branch in git.branches():
311 git.run('checkout', return_branch)
312 git.thaw()
313 else:
314 root_branch = git.root()
315 if return_branch != 'HEAD':
316 print (
317 "%r was merged with its parent, checking out %r instead."
318 % (return_branch, root_branch)
319 )
320 git.run('checkout', root_branch)
Robert Iannuccic87e36a2017-01-23 17:16:54 -0800321
322 # return_workdir may also not be there any more.
iannucci@chromium.org196809e2015-06-12 02:10:04 +0000323 if return_workdir:
Robert Iannuccic87e36a2017-01-23 17:16:54 -0800324 try:
325 os.chdir(return_workdir)
326 except OSError as e:
327 print (
328 "Unable to return to original workdir %r: %s"
329 % (return_workdir, e)
330 )
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000331 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000332 git.set_config(STARTING_WORKDIR_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000333
334 return retcode
335
336
337if __name__ == '__main__': # pragma: no cover
sbc@chromium.org013731e2015-02-26 18:28:43 +0000338 try:
339 sys.exit(main())
340 except KeyboardInterrupt:
341 sys.stderr.write('interrupted\n')
342 sys.exit(1)