blob: 1126c94660b89a28bc6f7e9aca85168c12fe6755 [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 """
34 return_branch = git.config(STARTING_BRANCH_KEY)
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +000035 workdir = git.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 = {}
iannucci@chromium.org0d9e59c2016-01-09 08:08:41 +000052 all_fetchspec_configs = git.config_regexp(r'^remote\..*\.fetch')
53 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, "...",
164 squash_branch = branch+"_squash_attempt"
165 git.run('checkout', '-b', squash_branch)
166 git.squash_current_branch(merge_base=start_hash)
167
168 # Try to rebase the branch_squash_attempt branch to see if it's empty.
169 squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
170 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
171 git.run('checkout', branch)
172 git.run('branch', '-D', squash_branch)
173 if squash_ret.success and empty_rebase:
174 print 'Success!'
175 git.squash_current_branch(merge_base=start_hash)
176 git.rebase(parent, start_hash, branch)
177 else:
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000178 print "Failed!"
179 print
180
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000181 # rebase and leave in mid-rebase state.
sbc@chromium.org384039b2014-10-13 21:01:00 +0000182 # This second rebase attempt should always fail in the same
183 # way that the first one does. If it magically succeeds then
184 # something very strange has happened.
185 second_rebase_ret = git.rebase(parent, start_hash, branch)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000186 if second_rebase_ret.success: # pragma: no cover
187 print "Second rebase succeeded unexpectedly!"
188 print "Please see: http://crbug.com/425696"
189 print "First rebased failed with:"
190 print rebase_ret.stderr
191 else:
192 print "Here's what git-rebase (squashed) had to say:"
193 print
194 print squash_ret.stdout
195 print squash_ret.stderr
196 print textwrap.dedent(
197 """\
198 Squashing failed. You probably have a real merge conflict.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000199
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000200 Your working copy is in mid-rebase. Either:
201 * completely resolve like a normal git-rebase; OR
202 * abort the rebase and mark this branch as dormant:
203 git config branch.%s.dormant true
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000204
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000205 And then run `git rebase-update` again to resume.
206 """ % branch)
207 return False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000208 else:
209 print '%s up-to-date' % branch
210
211 git.remove_merge_base(branch)
212 git.get_or_create_merge_base(branch)
213
214 return True
215
216
sbc@chromium.org013731e2015-02-26 18:28:43 +0000217def main(args=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000218 parser = argparse.ArgumentParser()
219 parser.add_argument('--verbose', '-v', action='store_true')
stip@chromium.org74374f92015-09-10 23:47:24 +0000220 parser.add_argument('--keep-going', '-k', action='store_true',
221 help='Keep processing past failed rebases.')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000222 parser.add_argument('--no_fetch', '--no-fetch', '-n',
223 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000224 help='Skip fetching remotes.')
225 opts = parser.parse_args(args)
226
227 if opts.verbose: # pragma: no cover
228 logging.getLogger().setLevel(logging.DEBUG)
229
230 # TODO(iannucci): snapshot all branches somehow, so we can implement
231 # `git rebase-update --undo`.
232 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
233 # * commit them to a secret ref?
234 # * Then we could view a summary of each run as a
235 # `diff --stat` on that secret ref.
236
237 if git.in_rebase():
238 # TODO(iannucci): Be able to resume rebase with flags like --continue,
239 # etc.
240 print (
241 'Rebase in progress. Please complete the rebase before running '
242 '`git rebase-update`.'
243 )
244 return 1
245
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000246 return_branch, return_workdir = find_return_branch_workdir()
247 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000248
249 if git.current_branch() == 'HEAD':
250 if git.run('status', '--porcelain'):
251 print 'Cannot rebase-update with detached head + uncommitted changes.'
252 return 1
253 else:
254 git.freeze() # just in case there are any local changes.
255
256 skipped, branch_tree = git.get_branch_tree()
257 for branch in skipped:
258 print 'Skipping %s: No upstream specified' % branch
259
260 if not opts.no_fetch:
261 fetch_remotes(branch_tree)
262
263 merge_base = {}
264 for branch, parent in branch_tree.iteritems():
265 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
266
267 logging.debug('branch_tree: %s' % pformat(branch_tree))
268 logging.debug('merge_base: %s' % pformat(merge_base))
269
270 retcode = 0
stip@chromium.org74374f92015-09-10 23:47:24 +0000271 unrebased_branches = []
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000272 # Rebase each branch starting with the root-most branches and working
273 # towards the leaves.
274 for branch, parent in git.topo_iter(branch_tree):
275 if git.is_dormant(branch):
276 print 'Skipping dormant branch', branch
277 else:
278 ret = rebase_branch(branch, parent, merge_base[branch])
279 if not ret:
280 retcode = 1
stip@chromium.org74374f92015-09-10 23:47:24 +0000281
282 if opts.keep_going:
283 print '--keep-going set, continuing with next branch.'
284 unrebased_branches.append(branch)
285 if git.in_rebase():
286 git.run_with_retcode('rebase', '--abort')
287 if git.in_rebase(): # pragma: no cover
288 print 'Failed to abort rebase. Something is really wrong.'
289 break
290 else:
291 break
292
293 if unrebased_branches:
294 print
295 print 'The following branches could not be cleanly rebased:'
296 for branch in unrebased_branches:
297 print ' %s' % branch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000298
299 if not retcode:
300 remove_empty_branches(branch_tree)
301
302 # return_branch may not be there any more.
303 if return_branch in git.branches():
304 git.run('checkout', return_branch)
305 git.thaw()
306 else:
307 root_branch = git.root()
308 if return_branch != 'HEAD':
309 print (
310 "%r was merged with its parent, checking out %r instead."
311 % (return_branch, root_branch)
312 )
313 git.run('checkout', root_branch)
iannucci@chromium.org196809e2015-06-12 02:10:04 +0000314 if return_workdir:
315 os.chdir(return_workdir)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000316 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000317 git.set_config(STARTING_WORKDIR_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000318
319 return retcode
320
321
322if __name__ == '__main__': # pragma: no cover
sbc@chromium.org013731e2015-02-26 18:28:43 +0000323 try:
324 sys.exit(main())
325 except KeyboardInterrupt:
326 sys.stderr.write('interrupted\n')
327 sys.exit(1)