iannucci@chromium.org | 97231b5 | 2014-03-26 06:54:55 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 2 | # 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 | """ |
| 7 | Tool to update all branches to have the latest changes from their upstreams. |
| 8 | """ |
| 9 | |
| 10 | import argparse |
| 11 | import collections |
| 12 | import logging |
| 13 | import sys |
| 14 | import textwrap |
| 15 | |
| 16 | from pprint import pformat |
| 17 | |
| 18 | import git_common as git |
| 19 | |
| 20 | |
| 21 | STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branch' |
| 22 | |
| 23 | |
| 24 | def 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) |
| 31 | if return_branch is None: |
| 32 | 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 | |
| 39 | def 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 | |
| 73 | def remove_empty_branches(branch_tree): |
| 74 | tag_set = git.tags() |
| 75 | ensure_root_checkout = git.once(lambda: git.run('checkout', git.root())) |
| 76 | |
| 77 | downstreams = collections.defaultdict(list) |
| 78 | for branch, parent in git.topo_iter(branch_tree, top_down=False): |
| 79 | downstreams[parent].append(branch) |
| 80 | |
| 81 | if git.hash_one(branch) == git.hash_one(parent): |
| 82 | ensure_root_checkout() |
| 83 | |
| 84 | logging.debug('branch %s merged to %s', branch, parent) |
| 85 | |
| 86 | for down in downstreams[branch]: |
| 87 | if parent in tag_set: |
| 88 | git.set_branch_config(down, 'remote', '.') |
| 89 | git.set_branch_config(down, 'merge', 'refs/tags/%s' % parent) |
| 90 | print ('Reparented %s to track %s [tag] (was tracking %s)' |
| 91 | % (down, parent, branch)) |
| 92 | else: |
| 93 | git.run('branch', '--set-upstream-to', parent, down) |
| 94 | print ('Reparented %s to track %s (was tracking %s)' |
| 95 | % (down, parent, branch)) |
| 96 | |
| 97 | print git.run('branch', '-d', branch) |
| 98 | |
| 99 | |
| 100 | def rebase_branch(branch, parent, start_hash): |
| 101 | logging.debug('considering %s(%s) -> %s(%s) : %s', |
| 102 | branch, git.hash_one(branch), parent, git.hash_one(parent), |
| 103 | start_hash) |
| 104 | |
| 105 | # If parent has FROZEN commits, don't base branch on top of them. Instead, |
| 106 | # base branch on top of whatever commit is before them. |
| 107 | back_ups = 0 |
| 108 | orig_parent = parent |
| 109 | while git.run('log', '-n1', '--format=%s', |
| 110 | parent, '--').startswith(git.FREEZE): |
| 111 | back_ups += 1 |
| 112 | parent = git.run('rev-parse', parent+'~') |
| 113 | |
| 114 | if back_ups: |
| 115 | logging.debug('Backed parent up by %d from %s to %s', |
| 116 | back_ups, orig_parent, parent) |
| 117 | |
| 118 | if git.hash_one(parent) != start_hash: |
| 119 | # Try a plain rebase first |
| 120 | print 'Rebasing:', branch |
| 121 | if not git.rebase(parent, start_hash, branch, abort=True).success: |
| 122 | # TODO(iannucci): Find collapsible branches in a smarter way? |
| 123 | print "Failed! Attempting to squash", branch, "...", |
| 124 | squash_branch = branch+"_squash_attempt" |
| 125 | git.run('checkout', '-b', squash_branch) |
| 126 | git.squash_current_branch(merge_base=start_hash) |
| 127 | |
| 128 | # Try to rebase the branch_squash_attempt branch to see if it's empty. |
| 129 | squash_ret = git.rebase(parent, start_hash, squash_branch, abort=True) |
| 130 | empty_rebase = git.hash_one(squash_branch) == git.hash_one(parent) |
| 131 | git.run('checkout', branch) |
| 132 | git.run('branch', '-D', squash_branch) |
| 133 | if squash_ret.success and empty_rebase: |
| 134 | print 'Success!' |
| 135 | git.squash_current_branch(merge_base=start_hash) |
| 136 | git.rebase(parent, start_hash, branch) |
| 137 | else: |
| 138 | # rebase and leave in mid-rebase state. |
| 139 | git.rebase(parent, start_hash, branch) |
iannucci@chromium.org | 56a624a | 2014-03-26 21:23:09 +0000 | [diff] [blame^] | 140 | print "Failed!" |
| 141 | print |
| 142 | print "Here's what git-rebase had to say:" |
iannucci@chromium.org | c050a5b | 2014-03-26 06:18:50 +0000 | [diff] [blame] | 143 | print squash_ret.message |
| 144 | print |
| 145 | print textwrap.dedent( |
| 146 | """ |
| 147 | Squashing failed. You probably have a real merge conflict. |
| 148 | |
| 149 | Your working copy is in mid-rebase. Either: |
| 150 | * completely resolve like a normal git-rebase; OR |
| 151 | * abort the rebase and mark this branch as dormant: |
| 152 | git config branch.%s.dormant true |
| 153 | |
| 154 | And then run `git rebase-update` again to resume. |
| 155 | """ % branch) |
| 156 | return False |
| 157 | else: |
| 158 | print '%s up-to-date' % branch |
| 159 | |
| 160 | git.remove_merge_base(branch) |
| 161 | git.get_or_create_merge_base(branch) |
| 162 | |
| 163 | return True |
| 164 | |
| 165 | |
| 166 | def main(args=()): |
| 167 | parser = argparse.ArgumentParser() |
| 168 | parser.add_argument('--verbose', '-v', action='store_true') |
| 169 | parser.add_argument('--no_fetch', '-n', action='store_true', |
| 170 | help='Skip fetching remotes.') |
| 171 | opts = parser.parse_args(args) |
| 172 | |
| 173 | if opts.verbose: # pragma: no cover |
| 174 | logging.getLogger().setLevel(logging.DEBUG) |
| 175 | |
| 176 | # TODO(iannucci): snapshot all branches somehow, so we can implement |
| 177 | # `git rebase-update --undo`. |
| 178 | # * Perhaps just copy packed-refs + refs/ + logs/ to the side? |
| 179 | # * commit them to a secret ref? |
| 180 | # * Then we could view a summary of each run as a |
| 181 | # `diff --stat` on that secret ref. |
| 182 | |
| 183 | if git.in_rebase(): |
| 184 | # TODO(iannucci): Be able to resume rebase with flags like --continue, |
| 185 | # etc. |
| 186 | print ( |
| 187 | 'Rebase in progress. Please complete the rebase before running ' |
| 188 | '`git rebase-update`.' |
| 189 | ) |
| 190 | return 1 |
| 191 | |
| 192 | return_branch = find_return_branch() |
| 193 | |
| 194 | if git.current_branch() == 'HEAD': |
| 195 | if git.run('status', '--porcelain'): |
| 196 | print 'Cannot rebase-update with detached head + uncommitted changes.' |
| 197 | return 1 |
| 198 | else: |
| 199 | git.freeze() # just in case there are any local changes. |
| 200 | |
| 201 | skipped, branch_tree = git.get_branch_tree() |
| 202 | for branch in skipped: |
| 203 | print 'Skipping %s: No upstream specified' % branch |
| 204 | |
| 205 | if not opts.no_fetch: |
| 206 | fetch_remotes(branch_tree) |
| 207 | |
| 208 | merge_base = {} |
| 209 | for branch, parent in branch_tree.iteritems(): |
| 210 | merge_base[branch] = git.get_or_create_merge_base(branch, parent) |
| 211 | |
| 212 | logging.debug('branch_tree: %s' % pformat(branch_tree)) |
| 213 | logging.debug('merge_base: %s' % pformat(merge_base)) |
| 214 | |
| 215 | retcode = 0 |
| 216 | # Rebase each branch starting with the root-most branches and working |
| 217 | # towards the leaves. |
| 218 | for branch, parent in git.topo_iter(branch_tree): |
| 219 | if git.is_dormant(branch): |
| 220 | print 'Skipping dormant branch', branch |
| 221 | else: |
| 222 | ret = rebase_branch(branch, parent, merge_base[branch]) |
| 223 | if not ret: |
| 224 | retcode = 1 |
| 225 | break |
| 226 | |
| 227 | if not retcode: |
| 228 | remove_empty_branches(branch_tree) |
| 229 | |
| 230 | # return_branch may not be there any more. |
| 231 | if return_branch in git.branches(): |
| 232 | git.run('checkout', return_branch) |
| 233 | git.thaw() |
| 234 | else: |
| 235 | root_branch = git.root() |
| 236 | if return_branch != 'HEAD': |
| 237 | print ( |
| 238 | "%r was merged with its parent, checking out %r instead." |
| 239 | % (return_branch, root_branch) |
| 240 | ) |
| 241 | git.run('checkout', root_branch) |
| 242 | git.del_config(STARTING_BRANCH_KEY) |
| 243 | |
| 244 | return retcode |
| 245 | |
| 246 | |
| 247 | if __name__ == '__main__': # pragma: no cover |
| 248 | sys.exit(main(sys.argv[1:])) |