blob: 992bb195dbd2a383d3c606e8e73dfb9d93bbcbc4 [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
iannucci@chromium.org512d97d2014-03-31 23:36:10 +000090 deletions = set()
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
95 if git.hash_one(branch) == git.hash_one(parent):
96 ensure_root_checkout()
97
98 logging.debug('branch %s merged to %s', branch, parent)
99
100 for down in downstreams[branch]:
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000101 if down in deletions:
102 continue
103
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000104 if parent in tag_set:
105 git.set_branch_config(down, 'remote', '.')
106 git.set_branch_config(down, 'merge', 'refs/tags/%s' % parent)
107 print ('Reparented %s to track %s [tag] (was tracking %s)'
108 % (down, parent, branch))
109 else:
110 git.run('branch', '--set-upstream-to', parent, down)
111 print ('Reparented %s to track %s (was tracking %s)'
112 % (down, parent, branch))
113
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000114 deletions.add(branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000115 print git.run('branch', '-d', branch)
116
117
118def rebase_branch(branch, parent, start_hash):
119 logging.debug('considering %s(%s) -> %s(%s) : %s',
120 branch, git.hash_one(branch), parent, git.hash_one(parent),
121 start_hash)
122
123 # If parent has FROZEN commits, don't base branch on top of them. Instead,
124 # base branch on top of whatever commit is before them.
125 back_ups = 0
126 orig_parent = parent
127 while git.run('log', '-n1', '--format=%s',
128 parent, '--').startswith(git.FREEZE):
129 back_ups += 1
130 parent = git.run('rev-parse', parent+'~')
131
132 if back_ups:
133 logging.debug('Backed parent up by %d from %s to %s',
134 back_ups, orig_parent, parent)
135
136 if git.hash_one(parent) != start_hash:
137 # Try a plain rebase first
138 print 'Rebasing:', branch
sbc@chromium.org384039b2014-10-13 21:01:00 +0000139 rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
140 if not rebase_ret.success:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000141 # TODO(iannucci): Find collapsible branches in a smarter way?
142 print "Failed! Attempting to squash", branch, "...",
143 squash_branch = branch+"_squash_attempt"
144 git.run('checkout', '-b', squash_branch)
145 git.squash_current_branch(merge_base=start_hash)
146
147 # Try to rebase the branch_squash_attempt branch to see if it's empty.
148 squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
149 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
150 git.run('checkout', branch)
151 git.run('branch', '-D', squash_branch)
152 if squash_ret.success and empty_rebase:
153 print 'Success!'
154 git.squash_current_branch(merge_base=start_hash)
155 git.rebase(parent, start_hash, branch)
156 else:
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000157 print "Failed!"
158 print
159
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000160 # rebase and leave in mid-rebase state.
sbc@chromium.org384039b2014-10-13 21:01:00 +0000161 # This second rebase attempt should always fail in the same
162 # way that the first one does. If it magically succeeds then
163 # something very strange has happened.
164 second_rebase_ret = git.rebase(parent, start_hash, branch)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000165 if second_rebase_ret.success: # pragma: no cover
166 print "Second rebase succeeded unexpectedly!"
167 print "Please see: http://crbug.com/425696"
168 print "First rebased failed with:"
169 print rebase_ret.stderr
170 else:
171 print "Here's what git-rebase (squashed) had to say:"
172 print
173 print squash_ret.stdout
174 print squash_ret.stderr
175 print textwrap.dedent(
176 """\
177 Squashing failed. You probably have a real merge conflict.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000178
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000179 Your working copy is in mid-rebase. Either:
180 * completely resolve like a normal git-rebase; OR
181 * abort the rebase and mark this branch as dormant:
182 git config branch.%s.dormant true
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000183
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000184 And then run `git rebase-update` again to resume.
185 """ % branch)
186 return False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000187 else:
188 print '%s up-to-date' % branch
189
190 git.remove_merge_base(branch)
191 git.get_or_create_merge_base(branch)
192
193 return True
194
195
sbc@chromium.org013731e2015-02-26 18:28:43 +0000196def main(args=None):
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000197 parser = argparse.ArgumentParser()
198 parser.add_argument('--verbose', '-v', action='store_true')
stip@chromium.org74374f92015-09-10 23:47:24 +0000199 parser.add_argument('--keep-going', '-k', action='store_true',
200 help='Keep processing past failed rebases.')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000201 parser.add_argument('--no_fetch', '--no-fetch', '-n',
202 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000203 help='Skip fetching remotes.')
204 opts = parser.parse_args(args)
205
206 if opts.verbose: # pragma: no cover
207 logging.getLogger().setLevel(logging.DEBUG)
208
209 # TODO(iannucci): snapshot all branches somehow, so we can implement
210 # `git rebase-update --undo`.
211 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
212 # * commit them to a secret ref?
213 # * Then we could view a summary of each run as a
214 # `diff --stat` on that secret ref.
215
216 if git.in_rebase():
217 # TODO(iannucci): Be able to resume rebase with flags like --continue,
218 # etc.
219 print (
220 'Rebase in progress. Please complete the rebase before running '
221 '`git rebase-update`.'
222 )
223 return 1
224
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000225 return_branch, return_workdir = find_return_branch_workdir()
226 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000227
228 if git.current_branch() == 'HEAD':
229 if git.run('status', '--porcelain'):
230 print 'Cannot rebase-update with detached head + uncommitted changes.'
231 return 1
232 else:
233 git.freeze() # just in case there are any local changes.
234
235 skipped, branch_tree = git.get_branch_tree()
236 for branch in skipped:
237 print 'Skipping %s: No upstream specified' % branch
238
239 if not opts.no_fetch:
240 fetch_remotes(branch_tree)
241
242 merge_base = {}
243 for branch, parent in branch_tree.iteritems():
244 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
245
246 logging.debug('branch_tree: %s' % pformat(branch_tree))
247 logging.debug('merge_base: %s' % pformat(merge_base))
248
249 retcode = 0
stip@chromium.org74374f92015-09-10 23:47:24 +0000250 unrebased_branches = []
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000251 # Rebase each branch starting with the root-most branches and working
252 # towards the leaves.
253 for branch, parent in git.topo_iter(branch_tree):
254 if git.is_dormant(branch):
255 print 'Skipping dormant branch', branch
256 else:
257 ret = rebase_branch(branch, parent, merge_base[branch])
258 if not ret:
259 retcode = 1
stip@chromium.org74374f92015-09-10 23:47:24 +0000260
261 if opts.keep_going:
262 print '--keep-going set, continuing with next branch.'
263 unrebased_branches.append(branch)
264 if git.in_rebase():
265 git.run_with_retcode('rebase', '--abort')
266 if git.in_rebase(): # pragma: no cover
267 print 'Failed to abort rebase. Something is really wrong.'
268 break
269 else:
270 break
271
272 if unrebased_branches:
273 print
274 print 'The following branches could not be cleanly rebased:'
275 for branch in unrebased_branches:
276 print ' %s' % branch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000277
278 if not retcode:
279 remove_empty_branches(branch_tree)
280
281 # return_branch may not be there any more.
282 if return_branch in git.branches():
283 git.run('checkout', return_branch)
284 git.thaw()
285 else:
286 root_branch = git.root()
287 if return_branch != 'HEAD':
288 print (
289 "%r was merged with its parent, checking out %r instead."
290 % (return_branch, root_branch)
291 )
292 git.run('checkout', root_branch)
iannucci@chromium.org196809e2015-06-12 02:10:04 +0000293 if return_workdir:
294 os.chdir(return_workdir)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000295 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000296 git.set_config(STARTING_WORKDIR_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000297
298 return retcode
299
300
301if __name__ == '__main__': # pragma: no cover
sbc@chromium.org013731e2015-02-26 18:28:43 +0000302 try:
303 sys.exit(main())
304 except KeyboardInterrupt:
305 sys.stderr.write('interrupted\n')
306 sys.exit(1)