blob: f98b8b2d925cc9dab303e8927c631870bb41b759 [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')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000199 parser.add_argument('--no_fetch', '--no-fetch', '-n',
200 action='store_true',
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000201 help='Skip fetching remotes.')
202 opts = parser.parse_args(args)
203
204 if opts.verbose: # pragma: no cover
205 logging.getLogger().setLevel(logging.DEBUG)
206
207 # TODO(iannucci): snapshot all branches somehow, so we can implement
208 # `git rebase-update --undo`.
209 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
210 # * commit them to a secret ref?
211 # * Then we could view a summary of each run as a
212 # `diff --stat` on that secret ref.
213
214 if git.in_rebase():
215 # TODO(iannucci): Be able to resume rebase with flags like --continue,
216 # etc.
217 print (
218 'Rebase in progress. Please complete the rebase before running '
219 '`git rebase-update`.'
220 )
221 return 1
222
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000223 return_branch, return_workdir = find_return_branch_workdir()
224 os.chdir(git.run('rev-parse', '--show-toplevel'))
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000225
226 if git.current_branch() == 'HEAD':
227 if git.run('status', '--porcelain'):
228 print 'Cannot rebase-update with detached head + uncommitted changes.'
229 return 1
230 else:
231 git.freeze() # just in case there are any local changes.
232
233 skipped, branch_tree = git.get_branch_tree()
234 for branch in skipped:
235 print 'Skipping %s: No upstream specified' % branch
236
237 if not opts.no_fetch:
238 fetch_remotes(branch_tree)
239
240 merge_base = {}
241 for branch, parent in branch_tree.iteritems():
242 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
243
244 logging.debug('branch_tree: %s' % pformat(branch_tree))
245 logging.debug('merge_base: %s' % pformat(merge_base))
246
247 retcode = 0
248 # Rebase each branch starting with the root-most branches and working
249 # towards the leaves.
250 for branch, parent in git.topo_iter(branch_tree):
251 if git.is_dormant(branch):
252 print 'Skipping dormant branch', branch
253 else:
254 ret = rebase_branch(branch, parent, merge_base[branch])
255 if not ret:
256 retcode = 1
257 break
258
259 if not retcode:
260 remove_empty_branches(branch_tree)
261
262 # return_branch may not be there any more.
263 if return_branch in git.branches():
264 git.run('checkout', return_branch)
265 git.thaw()
266 else:
267 root_branch = git.root()
268 if return_branch != 'HEAD':
269 print (
270 "%r was merged with its parent, checking out %r instead."
271 % (return_branch, root_branch)
272 )
273 git.run('checkout', root_branch)
iannucci@chromium.org196809e2015-06-12 02:10:04 +0000274 if return_workdir:
275 os.chdir(return_workdir)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000276 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgdabb78b2015-06-11 23:17:28 +0000277 git.set_config(STARTING_WORKDIR_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000278
279 return retcode
280
281
282if __name__ == '__main__': # pragma: no cover
sbc@chromium.org013731e2015-02-26 18:28:43 +0000283 try:
284 sys.exit(main())
285 except KeyboardInterrupt:
286 sys.stderr.write('interrupted\n')
287 sys.exit(1)