blob: 4e96c69898b6b2905f1977305fea673f4ccd0093 [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
16from pprint import pformat
17
18import git_common as git
19
20
21STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch'
22
23
24def find_return_branch():
25 """Finds the branch which we should return to after rebase-update completes.
26
27 This value may persist across multiple invocations of rebase-update, if
28 rebase-update runs into a conflict mid-way.
29 """
30 return_branch = git.config(STARTING_BRANCH_KEY)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +000031 if not return_branch:
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000032 return_branch = git.current_branch()
33 if return_branch != 'HEAD':
34 git.set_config(STARTING_BRANCH_KEY, return_branch)
35
36 return return_branch
37
38
39def fetch_remotes(branch_tree):
40 """Fetches all remotes which are needed to update |branch_tree|."""
41 fetch_tags = False
42 remotes = set()
43 tag_set = git.tags()
44 for parent in branch_tree.itervalues():
45 if parent in tag_set:
46 fetch_tags = True
47 else:
48 full_ref = git.run('rev-parse', '--symbolic-full-name', parent)
49 if full_ref.startswith('refs/remotes'):
50 parts = full_ref.split('/')
51 remote_name = parts[2]
52 remotes.add(remote_name)
53
54 fetch_args = []
55 if fetch_tags:
56 # Need to fetch all because we don't know what remote the tag comes from :(
57 # TODO(iannucci): assert that the tags are in the remote fetch refspec
58 fetch_args = ['--all']
59 else:
60 fetch_args.append('--multiple')
61 fetch_args.extend(remotes)
62 # TODO(iannucci): Should we fetch git-svn?
63
64 if not fetch_args: # pragma: no cover
65 print 'Nothing to fetch.'
66 else:
67 out, err = git.run_with_stderr('fetch', *fetch_args)
68 for data, stream in zip((out, err), (sys.stdout, sys.stderr)):
69 if data:
70 print >> stream, data
71
72
73def remove_empty_branches(branch_tree):
74 tag_set = git.tags()
75 ensure_root_checkout = git.once(lambda: git.run('checkout', git.root()))
76
iannucci@chromium.org512d97d2014-03-31 23:36:10 +000077 deletions = set()
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000078 downstreams = collections.defaultdict(list)
79 for branch, parent in git.topo_iter(branch_tree, top_down=False):
80 downstreams[parent].append(branch)
81
82 if git.hash_one(branch) == git.hash_one(parent):
83 ensure_root_checkout()
84
85 logging.debug('branch %s merged to %s', branch, parent)
86
87 for down in downstreams[branch]:
iannucci@chromium.org512d97d2014-03-31 23:36:10 +000088 if down in deletions:
89 continue
90
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000091 if parent in tag_set:
92 git.set_branch_config(down, 'remote', '.')
93 git.set_branch_config(down, 'merge', 'refs/tags/%s' % parent)
94 print ('Reparented %s to track %s [tag] (was tracking %s)'
95 % (down, parent, branch))
96 else:
97 git.run('branch', '--set-upstream-to', parent, down)
98 print ('Reparented %s to track %s (was tracking %s)'
99 % (down, parent, branch))
100
iannucci@chromium.org512d97d2014-03-31 23:36:10 +0000101 deletions.add(branch)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000102 print git.run('branch', '-d', branch)
103
104
105def rebase_branch(branch, parent, start_hash):
106 logging.debug('considering %s(%s) -> %s(%s) : %s',
107 branch, git.hash_one(branch), parent, git.hash_one(parent),
108 start_hash)
109
110 # If parent has FROZEN commits, don't base branch on top of them. Instead,
111 # base branch on top of whatever commit is before them.
112 back_ups = 0
113 orig_parent = parent
114 while git.run('log', '-n1', '--format=%s',
115 parent, '--').startswith(git.FREEZE):
116 back_ups += 1
117 parent = git.run('rev-parse', parent+'~')
118
119 if back_ups:
120 logging.debug('Backed parent up by %d from %s to %s',
121 back_ups, orig_parent, parent)
122
123 if git.hash_one(parent) != start_hash:
124 # Try a plain rebase first
125 print 'Rebasing:', branch
126 if not git.rebase(parent, start_hash, branch, abort=True).success:
127 # TODO(iannucci): Find collapsible branches in a smarter way?
128 print "Failed! Attempting to squash", branch, "...",
129 squash_branch = branch+"_squash_attempt"
130 git.run('checkout', '-b', squash_branch)
131 git.squash_current_branch(merge_base=start_hash)
132
133 # Try to rebase the branch_squash_attempt branch to see if it's empty.
134 squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True)
135 empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent)
136 git.run('checkout', branch)
137 git.run('branch', '-D', squash_branch)
138 if squash_ret.success and empty_rebase:
139 print 'Success!'
140 git.squash_current_branch(merge_base=start_hash)
141 git.rebase(parent, start_hash, branch)
142 else:
143 # rebase and leave in mid-rebase state.
144 git.rebase(parent, start_hash, branch)
iannucci@chromium.org56a624a2014-03-26 21:23:09 +0000145 print "Failed!"
146 print
147 print "Here's what git-rebase had to say:"
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000148 print squash_ret.message
149 print
150 print textwrap.dedent(
151 """
152 Squashing failed. You probably have a real merge conflict.
153
154 Your working copy is in mid-rebase. Either:
155 * completely resolve like a normal git-rebase; OR
156 * abort the rebase and mark this branch as dormant:
157 git config branch.%s.dormant true
158
159 And then run `git rebase-update` again to resume.
160 """ % branch)
161 return False
162 else:
163 print '%s up-to-date' % branch
164
165 git.remove_merge_base(branch)
166 git.get_or_create_merge_base(branch)
167
168 return True
169
170
171def main(args=()):
172 parser = argparse.ArgumentParser()
173 parser.add_argument('--verbose', '-v', action='store_true')
174 parser.add_argument('--no_fetch', '-n', action='store_true',
175 help='Skip fetching remotes.')
176 opts = parser.parse_args(args)
177
178 if opts.verbose: # pragma: no cover
179 logging.getLogger().setLevel(logging.DEBUG)
180
181 # TODO(iannucci): snapshot all branches somehow, so we can implement
182 # `git rebase-update --undo`.
183 # * Perhaps just copy packed-refs + refs/ + logs/ to the side?
184 # * commit them to a secret ref?
185 # * Then we could view a summary of each run as a
186 # `diff --stat` on that secret ref.
187
188 if git.in_rebase():
189 # TODO(iannucci): Be able to resume rebase with flags like --continue,
190 # etc.
191 print (
192 'Rebase in progress. Please complete the rebase before running '
193 '`git rebase-update`.'
194 )
195 return 1
196
197 return_branch = find_return_branch()
198
199 if git.current_branch() == 'HEAD':
200 if git.run('status', '--porcelain'):
201 print 'Cannot rebase-update with detached head + uncommitted changes.'
202 return 1
203 else:
204 git.freeze() # just in case there are any local changes.
205
206 skipped, branch_tree = git.get_branch_tree()
207 for branch in skipped:
208 print 'Skipping %s: No upstream specified' % branch
209
210 if not opts.no_fetch:
211 fetch_remotes(branch_tree)
212
213 merge_base = {}
214 for branch, parent in branch_tree.iteritems():
215 merge_base[branch] = git.get_or_create_merge_base(branch, parent)
216
217 logging.debug('branch_tree: %s' % pformat(branch_tree))
218 logging.debug('merge_base: %s' % pformat(merge_base))
219
220 retcode = 0
221 # Rebase each branch starting with the root-most branches and working
222 # towards the leaves.
223 for branch, parent in git.topo_iter(branch_tree):
224 if git.is_dormant(branch):
225 print 'Skipping dormant branch', branch
226 else:
227 ret = rebase_branch(branch, parent, merge_base[branch])
228 if not ret:
229 retcode = 1
230 break
231
232 if not retcode:
233 remove_empty_branches(branch_tree)
234
235 # return_branch may not be there any more.
236 if return_branch in git.branches():
237 git.run('checkout', return_branch)
238 git.thaw()
239 else:
240 root_branch = git.root()
241 if return_branch != 'HEAD':
242 print (
243 "%r was merged with its parent, checking out %r instead."
244 % (return_branch, root_branch)
245 )
246 git.run('checkout', root_branch)
iannucci@chromium.orgbf157b42014-04-12 00:14:41 +0000247 git.set_config(STARTING_BRANCH_KEY, '')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +0000248
249 return retcode
250
251
252if __name__ == '__main__': # pragma: no cover
253 sys.exit(main(sys.argv[1:]))