blob: a61e53a3ab5b5b94e482e0eef9e71fd82ad9f2c6 [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
15
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
21
22STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch'
23
24
25def find_return_branch():
26 """Finds the branch which we should return to after rebase-update completes.
27
28 This value may persist across multiple invocations of rebase-update, if
29 rebase-update runs into a conflict mid-way.
30 """
31 return_branch = git.config(STARTING_BRANCH_KEY)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +000032 if not return_branch:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000033 return_branch = git.current_branch()
34 if return_branch != 'HEAD':
35 git.set_config(STARTING_BRANCH_KEY, return_branch)
36
37 return return_branch
38
39
40def fetch_remotes(branch_tree):
41 """Fetches all remotes which are needed to update |branch_tree|."""
42 fetch_tags = False
43 remotes = set()
44 tag_set = git.tags()
szager@chromium.org937159d2014-09-24 17:25:45 +000045 fetchspec_map = {}
46 all_fetchspec_configs = git.run(
asanka@chromium.org4d2a66e2014-09-24 20:11:17 +000047 'config', '--get-regexp', r'^remote\..*\.fetch').strip()
szager@chromium.org937159d2014-09-24 17:25:45 +000048 for fetchspec_config in all_fetchspec_configs.splitlines():
49 key, _, fetchspec = fetchspec_config.partition(' ')
50 dest_spec = fetchspec.partition(':')[2]
51 remote_name = key.split('.')[1]
52 fetchspec_map[dest_spec] = remote_name
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000053 for parent in branch_tree.itervalues():
54 if parent in tag_set:
55 fetch_tags = True
56 else:
57 full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
szager@chromium.org937159d2014-09-24 17:25:45 +000058 for dest_spec, remote_name in fetchspec_map.iteritems():
59 if fnmatch(full_ref, dest_spec):
60 remotes.add(remote_name)
61 break
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000062
63 fetch_args = []
64 if fetch_tags:
65 # Need to fetch all because we don't know what remote the tag comes from :(
66 # TODO(iannucci): assert that the tags are in the remote fetch refspec
67 fetch_args = ['--all']
68 else:
69 fetch_args.append('--multiple')
70 fetch_args.extend(remotes)
71 # TODO(iannucci): Should we fetch git-svn?
72
73 if not fetch_args: # pragma: no cover
74 print 'Nothing to fetch.'
75 else:
iannucci@chromium.org43f4ecc2014-05-08 19:22:47 +000076 git.run_with_stderr('fetch', *fetch_args, stdout=sys.stdout,
77 stderr=sys.stderr)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000078
79
80def remove_empty_branches(branch_tree):
81 tag_set = git.tags()
82 ensure_root_checkout = git.once(lambda: git.run('checkout', git.root()))
83
iannucci@chromium.org512d97d2014-03-31 23:36:10 +000084 deletions = set()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000085 downstreams = collections.defaultdict(list)
86 for branch, parent in git.topo_iter(branch_tree, top_down=False):
87 downstreams[parent].append(branch)
88
89 if git.hash_one(branch) == git.hash_one(parent):
90 ensure_root_checkout()
91
92 logging.debug('branch %s merged to %s', branch, parent)
93
94 for down in downstreams[branch]:
iannucci@chromium.org512d97d2014-03-31 23:36:10 +000095 if down in deletions:
96 continue
97
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000098 if parent in tag_set:
99 git.set_branch_config(down, 'remote', '.')
100 git.set_branch_config(down, 'merge', 'refs/tags/%s' % parent)
101 print ('Reparented %s to track %s [tag] (was tracking %s)'
102 % (down, parent, branch))
103 else:
104 git.run('branch', '--set-upstream-to', parent, down)
105 print ('Reparented %s to track %s (was tracking %s)'
106 % (down, parent, branch))
107
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000108 deletions.add(branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000109 print git.run('branch', '-d', branch)
110
111
112def rebase_branch(branch, parent, start_hash):
113 logging.debug('considering %s(%s) -> %s(%s) : %s',
114 branch, git.hash_one(branch), parent, git.hash_one(parent),
115 start_hash)
116
117 # If parent has FROZEN commits, don't base branch on top of them. Instead,
118 # base branch on top of whatever commit is before them.
119 back_ups = 0
120 orig_parent = parent
121 while git.run('log', '-n1', '--format=%s',
122 parent, '--').startswith(git.FREEZE):
123 back_ups += 1
124 parent = git.run('rev-parse', parent+'~')
125
126 if back_ups:
127 logging.debug('Backed parent up by %d from %s to %s',
128 back_ups, orig_parent, parent)
129
130 if git.hash_one(parent) != start_hash:
131 # Try a plain rebase first
132 print 'Rebasing:', branch
sbc@chromium.org384039b2014-10-13 21:01:00 +0000133 rebase_ret = git.rebase(parent, start_hash, branch, abort=True)
134 if not rebase_ret.success:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000135 # TODO(iannucci): Find collapsible branches in a smarter way?
136 print "Failed! Attempting to squash", branch, "...",
137 squash_branch = branch+"_squash_attempt"
138 git.run('checkout', '-b', squash_branch)
139 git.squash_current_branch(merge_base=start_hash)
140
141 # Try to rebase the branch_squash_attempt branch to see if it's empty.
142 squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
143 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
144 git.run('checkout', branch)
145 git.run('branch', '-D', squash_branch)
146 if squash_ret.success and empty_rebase:
147 print 'Success!'
148 git.squash_current_branch(merge_base=start_hash)
149 git.rebase(parent, start_hash, branch)
150 else:
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000151 print "Failed!"
152 print
153
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000154 # rebase and leave in mid-rebase state.
sbc@chromium.org384039b2014-10-13 21:01:00 +0000155 # This second rebase attempt should always fail in the same
156 # way that the first one does. If it magically succeeds then
157 # something very strange has happened.
158 second_rebase_ret = git.rebase(parent, start_hash, branch)
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000159 if second_rebase_ret.success: # pragma: no cover
160 print "Second rebase succeeded unexpectedly!"
161 print "Please see: http://crbug.com/425696"
162 print "First rebased failed with:"
163 print rebase_ret.stderr
164 else:
165 print "Here's what git-rebase (squashed) had to say:"
166 print
167 print squash_ret.stdout
168 print squash_ret.stderr
169 print textwrap.dedent(
170 """\
171 Squashing failed. You probably have a real merge conflict.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000172
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000173 Your working copy is in mid-rebase. Either:
174 * completely resolve like a normal git-rebase; OR
175 * abort the rebase and mark this branch as dormant:
176 git config branch.%s.dormant true
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000177
sbc@chromium.org8b4900e2014-10-27 20:26:04 +0000178 And then run `git rebase-update` again to resume.
179 """ % branch)
180 return False
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000181 else:
182 print '%s up-to-date' % branch
183
184 git.remove_merge_base(branch)
185 git.get_or_create_merge_base(branch)
186
187 return True
188
189
190def main(args=()):
191 parser = argparse.ArgumentParser()
192 parser.add_argument('--verbose', '-v', action='store_true')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000193 parser.add_argument('--no_fetch', '--no-fetch', '-n',
194 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000195 help='Skip fetching remotes.')
196 opts = parser.parse_args(args)
197
198 if opts.verbose: # pragma: no cover
199 logging.getLogger().setLevel(logging.DEBUG)
200
201 # TODO(iannucci): snapshot all branches somehow, so we can implement
202 # `git rebase-update --undo`.
203 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
204 # * commit them to a secret ref?
205 # * Then we could view a summary of each run as a
206 # `diff --stat` on that secret ref.
207
208 if git.in_rebase():
209 # TODO(iannucci): Be able to resume rebase with flags like --continue,
210 # etc.
211 print (
212 'Rebase in progress. Please complete the rebase before running '
213 '`git rebase-update`.'
214 )
215 return 1
216
217 return_branch = find_return_branch()
218
219 if git.current_branch() == 'HEAD':
220 if git.run('status', '--porcelain'):
221 print 'Cannot rebase-update with detached head + uncommitted changes.'
222 return 1
223 else:
224 git.freeze() # just in case there are any local changes.
225
226 skipped, branch_tree = git.get_branch_tree()
227 for branch in skipped:
228 print 'Skipping %s: No upstream specified' % branch
229
230 if not opts.no_fetch:
231 fetch_remotes(branch_tree)
232
233 merge_base = {}
234 for branch, parent in branch_tree.iteritems():
235 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
236
237 logging.debug('branch_tree: %s' % pformat(branch_tree))
238 logging.debug('merge_base: %s' % pformat(merge_base))
239
240 retcode = 0
241 # Rebase each branch starting with the root-most branches and working
242 # towards the leaves.
243 for branch, parent in git.topo_iter(branch_tree):
244 if git.is_dormant(branch):
245 print 'Skipping dormant branch', branch
246 else:
247 ret = rebase_branch(branch, parent, merge_base[branch])
248 if not ret:
249 retcode = 1
250 break
251
252 if not retcode:
253 remove_empty_branches(branch_tree)
254
255 # return_branch may not be there any more.
256 if return_branch in git.branches():
257 git.run('checkout', return_branch)
258 git.thaw()
259 else:
260 root_branch = git.root()
261 if return_branch != 'HEAD':
262 print (
263 "%r was merged with its parent, checking out %r instead."
264 % (return_branch, root_branch)
265 )
266 git.run('checkout', root_branch)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000267 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000268
269 return retcode
270
271
272if __name__ == '__main__': # pragma: no cover
273 sys.exit(main(sys.argv[1:]))