blob: a725207a90f2d3944826f5f71cb94b18164226c0 [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 = {}
52 all_fetchspec_configs = git.run(
asanka@chromium.org4d2a66e2014-09-24 20:11:17 +000053 'config', '--get-regexp', r'^remote\..*\.fetch').strip()
szager@chromium.org937159d2014-09-24 17:25:45 +000054 for fetchspec_config in all_fetchspec_configs.splitlines():
55 key, _, fetchspec = fetchspec_config.partition(' ')
56 dest_spec = fetchspec.partition(':')[2]
57 remote_name = key.split('.')[1]
58 fetchspec_map[dest_spec] = remote_name
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000059 for parent in branch_tree.itervalues():
60 if parent in tag_set:
61 fetch_tags = True
62 else:
63 full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
szager@chromium.org937159d2014-09-24 17:25:45 +000064 for dest_spec, remote_name in fetchspec_map.iteritems():
65 if fnmatch(full_ref, dest_spec):
66 remotes.add(remote_name)
67 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000068
69 fetch_args = []
70 if fetch_tags:
71 # Need to fetch all because we don't know what remote the tag comes from :(
72 # TODO(iannucci): assert that the tags are in the remote fetch refspec
73 fetch_args = ['--all']
74 else:
75 fetch_args.append('--multiple')
76 fetch_args.extend(remotes)
77 # TODO(iannucci): Should we fetch git-svn?
78
79 if not fetch_args: # pragma: no cover
80 print 'Nothing to fetch.'
81 else:
iannucci@chromium.org43f4ecc2014-05-08 19:22:47 +000082 git.run_with_stderr('fetch', *fetch_args, stdout=sys.stdout,
83 stderr=sys.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000084
85
86def remove_empty_branches(branch_tree):
87 tag_set = git.tags()
88 ensure_root_checkout = git.once(lambda: git.run('checkout', git.root()))
89
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +000090 deletions = {}
91 reparents = {}
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000092 downstreams = collections.defaultdict(list)
93 for branch, parent in git.topo_iter(branch_tree, top_down=False):
94 downstreams[parent].append(branch)
95
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +000096 # If branch and parent have the same tree, then branch has to be marked
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +000097 # for deletion and its children and grand-children reparented to parent.
iannucci@chromium.orgaa1dfda2015-12-04 19:09:32 +000098 if git.hash_one(branch+":") == git.hash_one(parent+":"):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000099 ensure_root_checkout()
100
101 logging.debug('branch %s merged to %s', branch, parent)
102
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000103 # Mark branch for deletion while remembering the ordering, then add all
104 # its children as grand-children of its parent and record reparenting
105 # information if necessary.
106 deletions[branch] = len(deletions)
107
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000108 for down in downstreams[branch]:
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000109 if down in deletions:
110 continue
111
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000112 # Record the new and old parent for down, or update such a record
113 # if it already exists. Keep track of the ordering so that reparenting
114 # happen in topological order.
115 downstreams[parent].append(down)
116 if down not in reparents:
117 reparents[down] = (len(reparents), parent, branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000118 else:
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000119 order, _, old_parent = reparents[down]
120 reparents[down] = (order, parent, old_parent)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000121
sdefresne@chromium.orgd421f6a2015-12-02 18:13:54 +0000122 # Apply all reparenting recorded, in order.
123 for branch, value in sorted(reparents.iteritems(), key=lambda x:x[1][0]):
124 _, parent, old_parent = value
125 if parent in tag_set:
126 git.set_branch_config(branch, 'remote', '.')
127 git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent)
128 print ('Reparented %s to track %s [tag] (was tracking %s)'
129 % (branch, parent, old_parent))
130 else:
131 git.run('branch', '--set-upstream-to', parent, branch)
132 print ('Reparented %s to track %s (was tracking %s)'
133 % (branch, parent, old_parent))
134
135 # Apply all deletions recorded, in order.
136 for branch, _ in sorted(deletions.iteritems(), key=lambda x: x[1]):
137 print git.run('branch', '-d', branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000138
139
140def rebase_branch(branch, parent, start_hash):
141 logging.debug('considering %s(%s) -> %s(%s) : %s',
142 branch, git.hash_one(branch), parent, git.hash_one(parent),
143 start_hash)
144
145 # If parent has FROZEN commits, don't base branch on top of them. Instead,
146 # base branch on top of whatever commit is before them.
147 back_ups = 0
148 orig_parent = parent
149 while git.run('log', '-n1', '--format=%s',
150 parent, '--').startswith(git.FREEZE):
151 back_ups += 1
152 parent = git.run('rev-parse', parent+'~')
153
154 if back_ups:
155 logging.debug('Backed parent up by %d from %s to %s',
156 back_ups, orig_parent, parent)
157
158 if git.hash_one(parent) != start_hash:
159 # Try a plain rebase first
160 print 'Rebasing:', branch
sbc@chromium.org384039b2014-10-13 21:01:00 +0000161 rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
162 if not rebase_ret.success:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000163 # TODO(iannucci): Find collapsible branches in a smarter way?
164 print "Failed! Attempting to squash", branch, "...",
165 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.')
226 opts = parser.parse_args(args)
227
228 if opts.verbose: # pragma: no cover
229 logging.getLogger().setLevel(logging.DEBUG)
230
231 # TODO(iannucci): snapshot all branches somehow, so we can implement
232 # `git rebase-update --undo`.
233 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
234 # * commit them to a secret ref?
235 # * Then we could view a summary of each run as a
236 # `diff --stat` on that secret ref.
237
238 if git.in_rebase():
239 # TODO(iannucci): Be able to resume rebase with flags like --continue,
240 # etc.
241 print (
242 'Rebase in progress. Please complete the rebase before running '
243 '`git rebase-update`.'
244 )
245 return 1
246
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000247 return_branch, return_workdir = find_return_branch_workdir()
248 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000249
250 if git.current_branch() == 'HEAD':
251 if git.run('status', '--porcelain'):
252 print 'Cannot rebase-update with detached head + uncommitted changes.'
253 return 1
254 else:
255 git.freeze() # just in case there are any local changes.
256
257 skipped, branch_tree = git.get_branch_tree()
258 for branch in skipped:
259 print 'Skipping %s: No upstream specified' % branch
260
261 if not opts.no_fetch:
262 fetch_remotes(branch_tree)
263
264 merge_base = {}
265 for branch, parent in branch_tree.iteritems():
266 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
267
268 logging.debug('branch_tree: %s' % pformat(branch_tree))
269 logging.debug('merge_base: %s' % pformat(merge_base))
270
271 retcode = 0
stip@chromium.org74374f92015-09-10 23:47:24 +0000272 unrebased_branches = []
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000273 # Rebase each branch starting with the root-most branches and working
274 # towards the leaves.
275 for branch, parent in git.topo_iter(branch_tree):
276 if git.is_dormant(branch):
277 print 'Skipping dormant branch', branch
278 else:
279 ret = rebase_branch(branch, parent, merge_base[branch])
280 if not ret:
281 retcode = 1
stip@chromium.org74374f92015-09-10 23:47:24 +0000282
283 if opts.keep_going:
284 print '--keep-going set, continuing with next branch.'
285 unrebased_branches.append(branch)
286 if git.in_rebase():
287 git.run_with_retcode('rebase', '--abort')
288 if git.in_rebase(): # pragma: no cover
289 print 'Failed to abort rebase. Something is really wrong.'
290 break
291 else:
292 break
293
294 if unrebased_branches:
295 print
296 print 'The following branches could not be cleanly rebased:'
297 for branch in unrebased_branches:
298 print ' %s' % branch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000299
300 if not retcode:
301 remove_empty_branches(branch_tree)
302
303 # return_branch may not be there any more.
304 if return_branch in git.branches():
305 git.run('checkout', return_branch)
306 git.thaw()
307 else:
308 root_branch = git.root()
309 if return_branch != 'HEAD':
310 print (
311 "%r was merged with its parent, checking out %r instead."
312 % (return_branch, root_branch)
313 )
314 git.run('checkout', root_branch)
iannucci@chromium.org196809e2015-06-12 02:10:04 +0000315 if return_workdir:
316 os.chdir(return_workdir)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000317 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000318 git.set_config(STARTING_WORKDIR_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000319
320 return retcode
321
322
323if __name__ == '__main__': # pragma: no cover
sbc@chromium.org013731e2015-02-26 18:28:43 +0000324 try:
325 sys.exit(main())
326 except KeyboardInterrupt:
327 sys.stderr.write('interrupted\n')
328 sys.exit(1)