blob: 53e0287dd4663423a7ab8897df27e6aaa19910b0 [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:
151 # rebase and leave in mid-rebase state.
sbc@chromium.org384039b2014-10-13 21:01:00 +0000152 # This second rebase attempt should always fail in the same
153 # way that the first one does. If it magically succeeds then
154 # something very strange has happened.
155 second_rebase_ret = git.rebase(parent, start_hash, branch)
156 assert(not second_rebase_ret.success)
iannucci@chromium.org56a624a2014-03-26 21:23:09 +0000157 print "Failed!"
158 print
sbc@chromium.org384039b2014-10-13 21:01:00 +0000159 print "Here's what git-rebase (squashed) had to say:"
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000160 print
sbc@chromium.org384039b2014-10-13 21:01:00 +0000161 print squash_ret.stdout
162 print squash_ret.stderr
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000163 print textwrap.dedent(
sbc@chromium.org384039b2014-10-13 21:01:00 +0000164 """\
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000165 Squashing failed. You probably have a real merge conflict.
166
167 Your working copy is in mid-rebase. Either:
168 * completely resolve like a normal git-rebase; OR
169 * abort the rebase and mark this branch as dormant:
170 git config branch.%s.dormant true
171
172 And then run `git rebase-update` again to resume.
173 """ % branch)
174 return False
175 else:
176 print '%s up-to-date' % branch
177
178 git.remove_merge_base(branch)
179 git.get_or_create_merge_base(branch)
180
181 return True
182
183
184def main(args=()):
185 parser = argparse.ArgumentParser()
186 parser.add_argument('--verbose', '-v', action='store_true')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000187 parser.add_argument('--no_fetch', '--no-fetch', '-n',
188 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000189 help='Skip fetching remotes.')
190 opts = parser.parse_args(args)
191
192 if opts.verbose: # pragma: no cover
193 logging.getLogger().setLevel(logging.DEBUG)
194
195 # TODO(iannucci): snapshot all branches somehow, so we can implement
196 # `git rebase-update --undo`.
197 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
198 # * commit them to a secret ref?
199 # * Then we could view a summary of each run as a
200 # `diff --stat` on that secret ref.
201
202 if git.in_rebase():
203 # TODO(iannucci): Be able to resume rebase with flags like --continue,
204 # etc.
205 print (
206 'Rebase in progress. Please complete the rebase before running '
207 '`git rebase-update`.'
208 )
209 return 1
210
211 return_branch = find_return_branch()
212
213 if git.current_branch() == 'HEAD':
214 if git.run('status', '--porcelain'):
215 print 'Cannot rebase-update with detached head + uncommitted changes.'
216 return 1
217 else:
218 git.freeze() # just in case there are any local changes.
219
220 skipped, branch_tree = git.get_branch_tree()
221 for branch in skipped:
222 print 'Skipping %s: No upstream specified' % branch
223
224 if not opts.no_fetch:
225 fetch_remotes(branch_tree)
226
227 merge_base = {}
228 for branch, parent in branch_tree.iteritems():
229 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
230
231 logging.debug('branch_tree: %s' % pformat(branch_tree))
232 logging.debug('merge_base: %s' % pformat(merge_base))
233
234 retcode = 0
235 # Rebase each branch starting with the root-most branches and working
236 # towards the leaves.
237 for branch, parent in git.topo_iter(branch_tree):
238 if git.is_dormant(branch):
239 print 'Skipping dormant branch', branch
240 else:
241 ret = rebase_branch(branch, parent, merge_base[branch])
242 if not ret:
243 retcode = 1
244 break
245
246 if not retcode:
247 remove_empty_branches(branch_tree)
248
249 # return_branch may not be there any more.
250 if return_branch in git.branches():
251 git.run('checkout', return_branch)
252 git.thaw()
253 else:
254 root_branch = git.root()
255 if return_branch != 'HEAD':
256 print (
257 "%r was merged with its parent, checking out %r instead."
258 % (return_branch, root_branch)
259 )
260 git.run('checkout', root_branch)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000261 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000262
263 return retcode
264
265
266if __name__ == '__main__': # pragma: no cover
267 sys.exit(main(sys.argv[1:]))