blob: e5b6d424735c35c240ed1a9fa038070c3fa39b45 [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(
47 'config', '--get-regexp', r'remote\..*\.fetch').strip()
48 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
133 if not git.rebase(parent, start_hash, branch, abort=True).success:
134 # TODO(iannucci): Find collapsible branches in a smarter way?
135 print "Failed! Attempting to squash", branch, "...",
136 squash_branch = branch+"_squash_attempt"
137 git.run('checkout', '-b', squash_branch)
138 git.squash_current_branch(merge_base=start_hash)
139
140 # Try to rebase the branch_squash_attempt branch to see if it's empty.
141 squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
142 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
143 git.run('checkout', branch)
144 git.run('branch', '-D', squash_branch)
145 if squash_ret.success and empty_rebase:
146 print 'Success!'
147 git.squash_current_branch(merge_base=start_hash)
148 git.rebase(parent, start_hash, branch)
149 else:
150 # rebase and leave in mid-rebase state.
151 git.rebase(parent, start_hash, branch)
iannucci@chromium.org56a624a2014-03-26 21:23:09 +0000152 print "Failed!"
153 print
154 print "Here's what git-rebase had to say:"
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000155 print squash_ret.message
156 print
157 print textwrap.dedent(
158 """
159 Squashing failed. You probably have a real merge conflict.
160
161 Your working copy is in mid-rebase. Either:
162 * completely resolve like a normal git-rebase; OR
163 * abort the rebase and mark this branch as dormant:
164 git config branch.%s.dormant true
165
166 And then run `git rebase-update` again to resume.
167 """ % branch)
168 return False
169 else:
170 print '%s up-to-date' % branch
171
172 git.remove_merge_base(branch)
173 git.get_or_create_merge_base(branch)
174
175 return True
176
177
178def main(args=()):
179 parser = argparse.ArgumentParser()
180 parser.add_argument('--verbose', '-v', action='store_true')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000181 parser.add_argument('--no_fetch', '--no-fetch', '-n',
182 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000183 help='Skip fetching remotes.')
184 opts = parser.parse_args(args)
185
186 if opts.verbose: # pragma: no cover
187 logging.getLogger().setLevel(logging.DEBUG)
188
189 # TODO(iannucci): snapshot all branches somehow, so we can implement
190 # `git rebase-update --undo`.
191 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
192 # * commit them to a secret ref?
193 # * Then we could view a summary of each run as a
194 # `diff --stat` on that secret ref.
195
196 if git.in_rebase():
197 # TODO(iannucci): Be able to resume rebase with flags like --continue,
198 # etc.
199 print (
200 'Rebase in progress. Please complete the rebase before running '
201 '`git rebase-update`.'
202 )
203 return 1
204
205 return_branch = find_return_branch()
206
207 if git.current_branch() == 'HEAD':
208 if git.run('status', '--porcelain'):
209 print 'Cannot rebase-update with detached head + uncommitted changes.'
210 return 1
211 else:
212 git.freeze() # just in case there are any local changes.
213
214 skipped, branch_tree = git.get_branch_tree()
215 for branch in skipped:
216 print 'Skipping %s: No upstream specified' % branch
217
218 if not opts.no_fetch:
219 fetch_remotes(branch_tree)
220
221 merge_base = {}
222 for branch, parent in branch_tree.iteritems():
223 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
224
225 logging.debug('branch_tree: %s' % pformat(branch_tree))
226 logging.debug('merge_base: %s' % pformat(merge_base))
227
228 retcode = 0
229 # Rebase each branch starting with the root-most branches and working
230 # towards the leaves.
231 for branch, parent in git.topo_iter(branch_tree):
232 if git.is_dormant(branch):
233 print 'Skipping dormant branch', branch
234 else:
235 ret = rebase_branch(branch, parent, merge_base[branch])
236 if not ret:
237 retcode = 1
238 break
239
240 if not retcode:
241 remove_empty_branches(branch_tree)
242
243 # return_branch may not be there any more.
244 if return_branch in git.branches():
245 git.run('checkout', return_branch)
246 git.thaw()
247 else:
248 root_branch = git.root()
249 if return_branch != 'HEAD':
250 print (
251 "%r was merged with its parent, checking out %r instead."
252 % (return_branch, root_branch)
253 )
254 git.run('checkout', root_branch)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000255 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000256
257 return retcode
258
259
260if __name__ == '__main__': # pragma: no cover
261 sys.exit(main(sys.argv[1:]))