def remove_empty_branches(branch_tree): tag_set = git.tags() ensure_root_checkout = git.once(lambda: git.run("checkout", git.root())) deletions = set() downstreams = collections.defaultdict(list) for branch, parent in git.topo_iter(branch_tree, top_down=False): downstreams[parent].append(branch) if git.hash_one(branch) == git.hash_one(parent): ensure_root_checkout() logging.debug("branch %s merged to %s", branch, parent) for down in downstreams[branch]: if down in deletions: continue if parent in tag_set: git.set_branch_config(down, "remote", ".") git.set_branch_config(down, "merge", "refs/tags/%s" % parent) print ("Reparented %s to track %s [tag] (was tracking %s)" % (down, parent, branch)) else: git.run("branch", "--set-upstream-to", parent, down) print ("Reparented %s to track %s (was tracking %s)" % (down, parent, branch)) deletions.add(branch) print git.run("branch", "-d", branch)
def main(argv): # No command line flags. Just use the parser to prevent people from trying # to pass flags that don't do anything, and to provide 'usage'. parser = argparse.ArgumentParser( description='Automatically set up git-svn for a repo mirrored from svn.' ) parser.parse_args(argv) upstream = root() svn_id = get_footer_svn_id(upstream) assert svn_id, 'No valid git-svn-id footer found on %s.' % upstream print 'Found git-svn-id footer %s on %s' % (svn_id, upstream) parsed_svn = urlparse.urlparse(svn_id) path_components = parsed_svn.path.split('/') svn_repo = None svn_path = None for i in xrange(len(path_components)): try: maybe_repo = '%s://%s%s' % (parsed_svn.scheme, parsed_svn.netloc, '/'.join(path_components[:i + 1])) print 'Checking ', maybe_repo run_svn('info', maybe_repo) svn_repo = maybe_repo svn_path = '/'.join(path_components[i + 1:]) break except subprocess2.CalledProcessError, e: if 'E170001' in str(e): print 'Authentication failed:' print e print( 'Try running "svn ls %s" with the password' ' from https://chromium-access.appspot.com' % maybe_repo) print continue
def main(args): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('branch_name') g = parser.add_mutually_exclusive_group() g.add_argument('--upstream_current', action='store_true', help='set upstream branch to current branch.') g.add_argument('--upstream', metavar='REF', default=root(), help='upstream branch (or tag) to track.') g.add_argument('--lkgr', action='store_const', const='lkgr', dest='upstream', help='set basis ref for new branch to lkgr.') opts = parser.parse_args(args) try: if opts.upstream_current: run('checkout', '--track', '-b', opts.branch_name) else: if opts.upstream in tags(): # TODO(iannucci): ensure that basis_ref is an ancestor of HEAD? run('checkout', '--no-track', '-b', opts.branch_name, hash_one(opts.upstream)) set_config('branch.%s.remote' % opts.branch_name, '.') set_config('branch.%s.merge' % opts.branch_name, opts.upstream) else: # TODO(iannucci): Detect unclean workdir then stash+pop if we need to # teleport to a conflicting portion of history? run('checkout', '--track', opts.upstream, '-b', opts.branch_name) get_or_create_merge_base(opts.branch_name) except subprocess2.CalledProcessError as cpe: sys.stdout.write(cpe.stdout) sys.stderr.write(cpe.stderr) return 1
def main(argv): # No command line flags. Just use the parser to prevent people from trying # to pass flags that don't do anything, and to provide 'usage'. parser = argparse.ArgumentParser( description='Automatically set up git-svn for a repo mirrored from svn.') parser.parse_args(argv) upstream = root() svn_id = get_footer_svn_id(upstream) assert svn_id, 'No valid git-svn-id footer found on %s.' % upstream print 'Found git-svn-id footer %s on %s' % (svn_id, upstream) parsed_svn = urlparse.urlparse(svn_id) path_components = parsed_svn.path.split('/') svn_repo = None svn_path = None for i in xrange(len(path_components)): try: maybe_repo = '%s://%s%s' % ( parsed_svn.scheme, parsed_svn.netloc, '/'.join(path_components[:i+1])) print 'Checking ', maybe_repo run_svn('info', maybe_repo) svn_repo = maybe_repo svn_path = '/'.join(path_components[i+1:]) break except subprocess2.CalledProcessError, e: if 'E170001' in str(e): print 'Authentication failed:' print e print ('Try running "svn ls %s" with the password' ' from https://chromium-access.appspot.com' % maybe_repo) print continue
def remove_empty_branches(branch_tree): tag_set = git.tags() ensure_root_checkout = git.once(lambda: git.run('checkout', git.root())) deletions = set() downstreams = collections.defaultdict(list) for branch, parent in git.topo_iter(branch_tree, top_down=False): downstreams[parent].append(branch) if git.hash_one(branch) == git.hash_one(parent): ensure_root_checkout() logging.debug('branch %s merged to %s', branch, parent) for down in downstreams[branch]: if down in deletions: continue if parent in tag_set: git.set_branch_config(down, 'remote', '.') git.set_branch_config(down, 'merge', 'refs/tags/%s' % parent) print('Reparented %s to track %s [tag] (was tracking %s)' % (down, parent, branch)) else: git.run('branch', '--set-upstream-to', parent, down) print('Reparented %s to track %s (was tracking %s)' % (down, parent, branch)) deletions.add(branch) print git.run('branch', '-d', branch)
def main(args): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=__doc__, ) parser.add_argument('branch_name') g = parser.add_mutually_exclusive_group() g.add_argument('--upstream-current', '--upstream_current', action='store_true', help='set upstream branch to current branch.') g.add_argument('--upstream', metavar='REF', default=root(), help='upstream branch (or tag) to track.') g.add_argument('--inject-current', '--inject_current', action='store_true', help='new branch adopts current branch\'s upstream,' + ' and new branch becomes current branch\'s upstream.') g.add_argument('--lkgr', action='store_const', const='lkgr', dest='upstream', help='set basis ref for new branch to lkgr.') opts = parser.parse_args(args) try: if opts.inject_current: below = current_branch() if below is None: raise Exception('no current branch') above = upstream(below) if above is None: raise Exception('branch %s has no upstream' % (below)) run('checkout', '--track', above, '-b', opts.branch_name) run('branch', '--set-upstream-to', opts.branch_name, below) elif opts.upstream_current: run('checkout', '--track', '-b', opts.branch_name) else: if opts.upstream in tags(): # TODO(iannucci): ensure that basis_ref is an ancestor of HEAD? run('checkout', '--no-track', '-b', opts.branch_name, hash_one(opts.upstream)) set_config('branch.%s.remote' % opts.branch_name, '.') set_config('branch.%s.merge' % opts.branch_name, opts.upstream) else: # TODO(iannucci): Detect unclean workdir then stash+pop if we need to # teleport to a conflicting portion of history? run('checkout', '--track', opts.upstream, '-b', opts.branch_name) get_or_create_merge_base(opts.branch_name) except subprocess2.CalledProcessError as cpe: sys.stdout.write(cpe.stdout) sys.stderr.write(cpe.stderr) return 1 sys.stderr.write('Switched to branch %s.\n' % opts.branch_name) return 0
def main(args): root_ref = root() parser = argparse.ArgumentParser() g = parser.add_mutually_exclusive_group() g.add_argument('new_parent', nargs='?', help='New parent branch (or tag) to reparent to.') g.add_argument('--root', action='store_true', help='Reparent to the configured root branch (%s).' % root_ref) g.add_argument('--lkgr', action='store_true', help='Reparent to the lkgr tag.') opts = parser.parse_args(args) # TODO(iannucci): Allow specification of the branch-to-reparent branch = current_branch() if opts.root: new_parent = root_ref elif opts.lkgr: new_parent = 'lkgr' else: new_parent = opts.new_parent cur_parent = upstream(branch) if branch == 'HEAD' or not branch: parser.error('Must be on the branch you want to reparent') if new_parent == cur_parent: parser.error('Cannot reparent a branch to its existing parent') mbase = get_or_create_merge_base(branch, cur_parent) all_tags = tags() if cur_parent in all_tags: cur_parent += ' [tag]' try: run('show-ref', new_parent) except subprocess2.CalledProcessError: print >> sys.stderr, 'fatal: invalid reference: %s' % new_parent return 1 if new_parent in all_tags: print("Reparenting %s to track %s [tag] (was %s)" % (branch, new_parent, cur_parent)) set_branch_config(branch, 'remote', '.') set_branch_config(branch, 'merge', new_parent) else: print("Reparenting %s to track %s (was %s)" % (branch, new_parent, cur_parent)) run('branch', '--set-upstream-to', new_parent, branch) manual_merge_base(branch, mbase, new_parent) # TODO(iannucci): ONLY rebase-update the branch which moved (and dependants) return git_rebase_update.main(['--no-fetch'])
def main(argv, outbuf): if '-h' in argv or '--help' in argv: _print_help(outbuf) return 0 map_extra = git_common.get_config_list('depot_tools.map_extra') cmd = [ git_common.GIT_EXE, 'log', git_common.root(), '--graph', '--branches', '--tags', '--color=always', '--date=short', '--pretty=format:%H%x00%D%x00%cd%x00%s' ] + map_extra + argv log_proc = subprocess2.Popen(cmd, stdout=subprocess2.PIPE, shell=False) current = git_common.current_branch() all_tags = set(git_common.tags()) all_branches = set(git_common.branches()) if current in all_branches: all_branches.remove(current) merge_base_map = {} for branch in all_branches: merge_base = git_common.get_or_create_merge_base(branch) if merge_base: merge_base_map.setdefault(merge_base, set()).add(branch) for merge_base, branches in merge_base_map.items(): merge_base_map[merge_base] = ', '.join(branches) try: for line in log_proc.stdout: if b'\x00' not in line: outbuf.write(line) continue graph, commit, branch_list, commit_date, subject = _parse_log_line( line) if 'HEAD' in branch_list: graph = graph.replace('*', BLUE_BACK + '*') line = '{graph}{commit}\t{branches}{date} ~ {subject}'.format( graph=graph, commit=BRIGHT_RED + commit[:10] + RESET, branches=_color_branch_list(branch_list, all_branches, all_tags, current), date=YELLOW + commit_date + RESET, subject=subject) if commit in merge_base_map: line += ' <({})'.format(WHITE + merge_base_map[commit] + RESET) line += os.linesep outbuf.write(line.encode('utf-8', 'replace')) except (BrokenPipeError, KeyboardInterrupt): pass return 0
def main(args): root_ref = root() parser = argparse.ArgumentParser() g = parser.add_mutually_exclusive_group() g.add_argument('new_parent', nargs='?', help='New parent branch (or tag) to reparent to.') g.add_argument('--root', action='store_true', help='Reparent to the configured root branch (%s).' % root_ref) g.add_argument('--lkgr', action='store_true', help='Reparent to the lkgr tag.') opts = parser.parse_args(args) # TODO(iannucci): Allow specification of the branch-to-reparent branch = current_branch() if opts.root: new_parent = root_ref elif opts.lkgr: new_parent = 'lkgr' else: if not opts.new_parent: parser.error('Must specify new parent somehow') new_parent = opts.new_parent cur_parent = upstream(branch) if branch == 'HEAD' or not branch: parser.error('Must be on the branch you want to reparent') if new_parent == cur_parent: parser.error('Cannot reparent a branch to its existing parent') mbase = get_or_create_merge_base(branch, cur_parent) all_tags = tags() if cur_parent in all_tags: cur_parent += ' [tag]' try: run('show-ref', new_parent) except subprocess2.CalledProcessError: print >> sys.stderr, 'fatal: invalid reference: %s' % new_parent return 1 if new_parent in all_tags: print ("Reparenting %s to track %s [tag] (was %s)" % (branch, new_parent, cur_parent)) set_branch_config(branch, 'remote', '.') set_branch_config(branch, 'merge', new_parent) else: print ("Reparenting %s to track %s (was %s)" % (branch, new_parent, cur_parent)) run('branch', '--set-upstream-to', new_parent, branch) manual_merge_base(branch, mbase, new_parent) # TODO(iannucci): ONLY rebase-update the branch which moved (and dependants) return git_rebase_update.main(['--no-fetch'])
def remove_empty_branches(branch_tree): tag_set = git.tags() ensure_root_checkout = git.once(lambda: git.run('checkout', git.root())) deletions = {} reparents = {} downstreams = collections.defaultdict(list) for branch, parent in git.topo_iter(branch_tree, top_down=False): if git.is_dormant(branch): continue downstreams[parent].append(branch) # If branch and parent have the same tree, then branch has to be marked # for deletion and its children and grand-children reparented to parent. if git.hash_one(branch + ":") == git.hash_one(parent + ":"): ensure_root_checkout() logging.debug('branch %s merged to %s', branch, parent) # Mark branch for deletion while remembering the ordering, then add all # its children as grand-children of its parent and record reparenting # information if necessary. deletions[branch] = len(deletions) for down in downstreams[branch]: if down in deletions: continue # Record the new and old parent for down, or update such a record # if it already exists. Keep track of the ordering so that reparenting # happen in topological order. downstreams[parent].append(down) if down not in reparents: reparents[down] = (len(reparents), parent, branch) else: order, _, old_parent = reparents[down] reparents[down] = (order, parent, old_parent) # Apply all reparenting recorded, in order. for branch, value in sorted(reparents.items(), key=lambda x: x[1][0]): _, parent, old_parent = value if parent in tag_set: git.set_branch_config(branch, 'remote', '.') git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent) print('Reparented %s to track %s [tag] (was tracking %s)' % (branch, parent, old_parent)) else: git.run('branch', '--set-upstream-to', parent, branch) print('Reparented %s to track %s (was tracking %s)' % (branch, parent, old_parent)) # Apply all deletions recorded, in order. for branch, _ in sorted(deletions.items(), key=lambda x: x[1]): print(git.run('branch', '-d', branch))
def get_footer_svn_id(branch=None): if not branch: branch = git.root() svn_id = None message = git.run('log', '-1', '--format=%B', branch) footers = parse_footers(message) git_svn_id = get_unique(footers, 'git-svn-id') if git_svn_id: match = GIT_SVN_ID_PATTERN.match(git_svn_id) if match: svn_id = match.group(1) return svn_id
def remove_empty_branches(branch_tree): tag_set = git.tags() ensure_root_checkout = git.once(lambda: git.run('checkout', git.root())) deletions = {} reparents = {} downstreams = collections.defaultdict(list) for branch, parent in git.topo_iter(branch_tree, top_down=False): downstreams[parent].append(branch) # If branch and parent have the same tree, then branch has to be marked # for deletion and its children and grand-children reparented to parent. if git.hash_one(branch+":") == git.hash_one(parent+":"): ensure_root_checkout() logging.debug('branch %s merged to %s', branch, parent) # Mark branch for deletion while remembering the ordering, then add all # its children as grand-children of its parent and record reparenting # information if necessary. deletions[branch] = len(deletions) for down in downstreams[branch]: if down in deletions: continue # Record the new and old parent for down, or update such a record # if it already exists. Keep track of the ordering so that reparenting # happen in topological order. downstreams[parent].append(down) if down not in reparents: reparents[down] = (len(reparents), parent, branch) else: order, _, old_parent = reparents[down] reparents[down] = (order, parent, old_parent) # Apply all reparenting recorded, in order. for branch, value in sorted(reparents.iteritems(), key=lambda x:x[1][0]): _, parent, old_parent = value if parent in tag_set: git.set_branch_config(branch, 'remote', '.') git.set_branch_config(branch, 'merge', 'refs/tags/%s' % parent) print ('Reparented %s to track %s [tag] (was tracking %s)' % (branch, parent, old_parent)) else: git.run('branch', '--set-upstream-to', parent, branch) print ('Reparented %s to track %s (was tracking %s)' % (branch, parent, old_parent)) # Apply all deletions recorded, in order. for branch, _ in sorted(deletions.iteritems(), key=lambda x: x[1]): print git.run('branch', '-d', branch)
def main(args): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('branch_name') g = parser.add_mutually_exclusive_group() g.add_argument('--upstream_current', action='store_true', help='set upstream branch to current branch.') g.add_argument('--upstream', metavar='REF', default=root(), help='upstream branch (or tag) to track.') g.add_argument('--lkgr', action='store_const', const='lkgr', dest='upstream', help='set basis ref for new branch to lkgr.') opts = parser.parse_args(args) try: if opts.upstream_current: run('checkout', '--track', '-b', opts.branch_name) else: if opts.upstream in tags(): # TODO(iannucci): ensure that basis_ref is an ancestor of HEAD? run('checkout', '--no-track', '-b', opts.branch_name, hash_one(opts.upstream)) set_config('branch.%s.remote' % opts.branch_name, '.') set_config('branch.%s.merge' % opts.branch_name, opts.upstream) else: # TODO(iannucci): Detect unclean workdir then stash+pop if we need to # teleport to a conflicting portion of history? run('checkout', '--track', opts.upstream, '-b', opts.branch_name) get_or_create_merge_base(opts.branch_name) except subprocess2.CalledProcessError as cpe: sys.stdout.write(cpe.stdout) sys.stderr.write(cpe.stderr) return 1
def main(argv): # No command line flags. Just use the parser to prevent people from trying # to pass flags that don't do anything, and to provide 'usage'. parser = argparse.ArgumentParser( description='Automatically set up git-svn for a repo mirrored from svn.') parser.parse_args(argv[1:]) upstream = root() message = run_git('log', '-1', '--format=%B', upstream) footers = parse_footers(message) git_svn_id = get_unique(footers, 'git-svn-id') match = GIT_SVN_ID_PATTERN.match(git_svn_id) assert match, 'No valid git-svn-id footer found on %s.' % upstream print 'Found git-svn-id footer %s on %s' % (match.group(1), upstream) parsed_svn = urlparse.urlparse(match.group(1)) path_components = parsed_svn.path.split('/') svn_repo = None svn_path = None for i in xrange(len(path_components)): try: maybe_repo = '%s://%s%s' % ( parsed_svn.scheme, parsed_svn.netloc, '/'.join(path_components[:i+1])) print 'Checking ', maybe_repo run_svn('info', maybe_repo) svn_repo = maybe_repo svn_path = '/'.join(path_components[i+1:]) break except subprocess2.CalledProcessError: continue assert svn_repo is not None, 'Unable to find svn repo for %s' % match.group(1) print 'Found upstream svn repo %s and path %s' % (svn_repo, svn_path) prefix = upstream.rsplit('/')[0] run_git('svn', 'init', '--prefix=%s' % prefix, '-T', svn_path, svn_repo) set_config('svn-remote.svn.fetch', '%s:refs/remotes/%s' % (svn_path, upstream)) print 'Configured metadata, running "git svn fetch". This may take some time.' for line in run_git_stream('svn', 'fetch').xreadlines(): print line.strip()
def main(argv): # No command line flags. Just use the parser to prevent people from trying # to pass flags that don't do anything, and to provide 'usage'. parser = argparse.ArgumentParser( description='Automatically set up git-svn for a repo mirrored from svn.') parser.parse_args(argv) upstreams = [] # Always configure the upstream trunk. upstreams.append(root()) # Optionally configure whatever upstream branch might be currently checked # out. This is needed for work on svn-based branches, otherwise git-svn gets # very confused and tries to relate branch commits back to trunk, making a big # mess of the codereview patches, and generating all kinds of spurious errors # about the repo being in some sort of bad state. curr_upstream = get_upstream(current_branch()) # There will be no upstream if the checkout is in detached HEAD. if curr_upstream: upstreams.append(curr_upstream) for upstream in upstreams: config_svn(upstream) return 0
def main(argv): # No command line flags. Just use the parser to prevent people from trying # to pass flags that don't do anything, and to provide 'usage'. parser = argparse.ArgumentParser( description='Automatically set up git-svn for a repo mirrored from svn.' ) parser.parse_args(argv) upstreams = [] # Always configure the upstream trunk. upstreams.append(root()) # Optionally configure whatever upstream branch might be currently checked # out. This is needed for work on svn-based branches, otherwise git-svn gets # very confused and tries to relate branch commits back to trunk, making a big # mess of the codereview patches, and generating all kinds of spurious errors # about the repo being in some sort of bad state. curr_upstream = get_upstream(current_branch()) # There will be no upstream if the checkout is in detached HEAD. if curr_upstream: upstreams.append(curr_upstream) for upstream in upstreams: config_svn(upstream) return 0
def create_new_branch(branch_name, upstream_current=False, upstream=None, inject_current=False): upstream = upstream or git_common.root() try: if inject_current: below = git_common.current_branch() if below is None: raise Exception('no current branch') above = git_common.upstream(below) if above is None: raise Exception('branch %s has no upstream' % (below)) git_common.run('checkout', '--track', above, '-b', branch_name) git_common.run('branch', '--set-upstream-to', branch_name, below) elif upstream_current: git_common.run('checkout', '--track', '-b', branch_name) else: if upstream in git_common.tags(): # TODO(iannucci): ensure that basis_ref is an ancestor of HEAD? git_common.run('checkout', '--no-track', '-b', branch_name, git_common.hash_one(upstream)) git_common.set_config('branch.%s.remote' % branch_name, '.') git_common.set_config('branch.%s.merge' % branch_name, upstream) else: # TODO(iannucci): Detect unclean workdir then stash+pop if we need to # teleport to a conflicting portion of history? git_common.run('checkout', '--track', upstream, '-b', branch_name) git_common.get_or_create_merge_base(branch_name) except subprocess2.CalledProcessError as cpe: sys.stdout.write(cpe.stdout.decode('utf-8', 'replace')) sys.stderr.write(cpe.stderr.decode('utf-8', 'replace')) return 1 sys.stderr.write('Switched to branch %s.\n' % branch_name) return 0
def main(argv): if '-h' in argv: print_help() return 0 map_extra = get_config_list('depot_tools.map_extra') fmt = '%C(red bold)%h%x09%Creset%C(green)%d%Creset %C(yellow)%cd%Creset ~ %s' log_proc = subprocess2.Popen([ GIT_EXE, 'log', '--graph', '--branches', '--tags', root(), '--color=always', '--date=short', ('--pretty=format:' + fmt) ] + map_extra + argv, stdout=subprocess2.PIPE, shell=False) current = current_branch() all_branches = set(branches()) merge_base_map = {b: get_or_create_merge_base(b) for b in all_branches} merge_base_map = {b: v for b, v in merge_base_map.items() if v} if current in all_branches: all_branches.remove(current) all_tags = set(tags()) try: for line in log_proc.stdout.xreadlines(): if merge_base_map: commit = line[line.find(BRIGHT_RED) + len(BRIGHT_RED):line.find('\t')] base_for_branches = set() for branch, sha in merge_base_map.items(): if sha.startswith(commit): base_for_branches.add(branch) if base_for_branches: newline = '\r\n' if line.endswith('\r\n') else '\n' line = line.rstrip(newline) line += ''.join( (BRIGHT, WHITE, ' <(%s)' % (', '.join(base_for_branches)), RESET, newline)) for b in base_for_branches: del merge_base_map[b] start = line.find(GREEN + ' (') end = line.find(')', start) if start != -1 and end != -1: start += len(GREEN) + 2 branch_list = line[start:end].split(', ') branches_str = '' if branch_list: colored_branches = [] head_marker = '' for b in branch_list: if b == "HEAD": head_marker = BLUEBAK + BRIGHT + '*' continue if b == current: colored_branches.append(CYAN + BRIGHT + b + RESET) current = None elif b in all_branches: colored_branches.append(GREEN + BRIGHT + b + RESET) all_branches.remove(b) elif b in all_tags: colored_branches.append(MAGENTA + BRIGHT + b + RESET) elif b.startswith('tag: '): colored_branches.append(MAGENTA + BRIGHT + b[5:] + RESET) else: colored_branches.append(RED + b) branches_str = '(%s) ' % ( (GREEN + ", ").join(colored_branches) + GREEN) line = "%s%s%s" % (line[:start - 1], branches_str, line[end + 5:]) if head_marker: line = line.replace('*', head_marker, 1) sys.stdout.write(line) except (IOError, KeyboardInterrupt): pass finally: sys.stderr.close() sys.stdout.close() return 0
def main(args=None): parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='store_true') parser.add_argument('--keep-going', '-k', action='store_true', help='Keep processing past failed rebases.') parser.add_argument('--no_fetch', '--no-fetch', '-n', action='store_true', help='Skip fetching remotes.') opts = parser.parse_args(args) if opts.verbose: # pragma: no cover logging.getLogger().setLevel(logging.DEBUG) # TODO(iannucci): snapshot all branches somehow, so we can implement # `git rebase-update --undo`. # * Perhaps just copy packed-refs + refs/ + logs/ to the side? # * commit them to a secret ref? # * Then we could view a summary of each run as a # `diff --stat` on that secret ref. if git.in_rebase(): # TODO(iannucci): Be able to resume rebase with flags like --continue, # etc. print ( 'Rebase in progress. Please complete the rebase before running ' '`git rebase-update`.' ) return 1 return_branch, return_workdir = find_return_branch_workdir() os.chdir(git.run('rev-parse', '--show-toplevel')) if git.current_branch() == 'HEAD': if git.run('status', '--porcelain'): print 'Cannot rebase-update with detached head + uncommitted changes.' return 1 else: git.freeze() # just in case there are any local changes. skipped, branch_tree = git.get_branch_tree() for branch in skipped: print 'Skipping %s: No upstream specified' % branch if not opts.no_fetch: fetch_remotes(branch_tree) merge_base = {} for branch, parent in branch_tree.iteritems(): merge_base[branch] = git.get_or_create_merge_base(branch, parent) logging.debug('branch_tree: %s' % pformat(branch_tree)) logging.debug('merge_base: %s' % pformat(merge_base)) retcode = 0 unrebased_branches = [] # Rebase each branch starting with the root-most branches and working # towards the leaves. for branch, parent in git.topo_iter(branch_tree): if git.is_dormant(branch): print 'Skipping dormant branch', branch else: ret = rebase_branch(branch, parent, merge_base[branch]) if not ret: retcode = 1 if opts.keep_going: print '--keep-going set, continuing with next branch.' unrebased_branches.append(branch) if git.in_rebase(): git.run_with_retcode('rebase', '--abort') if git.in_rebase(): # pragma: no cover print 'Failed to abort rebase. Something is really wrong.' break else: break if unrebased_branches: print print 'The following branches could not be cleanly rebased:' for branch in unrebased_branches: print ' %s' % branch if not retcode: remove_empty_branches(branch_tree) # return_branch may not be there any more. if return_branch in git.branches(): git.run('checkout', return_branch) git.thaw() else: root_branch = git.root() if return_branch != 'HEAD': print ( "%r was merged with its parent, checking out %r instead." % (return_branch, root_branch) ) git.run('checkout', root_branch) if return_workdir: os.chdir(return_workdir) git.set_config(STARTING_BRANCH_KEY, '') git.set_config(STARTING_WORKDIR_KEY, '') return retcode
def main(argv): if '-h' in argv: print_help() return 0 map_extra = get_config_list('depot_tools.map_extra') fmt = '%C(red bold)%h%x09%Creset%C(green)%d%Creset %C(yellow)%cd%Creset ~ %s' log_proc = subprocess2.Popen( [GIT_EXE, 'log', '--graph', '--branches', '--tags', root(), '--color=always', '--date=short', ('--pretty=format:' + fmt) ] + map_extra + argv, stdout=subprocess2.PIPE, shell=False) current = current_branch() all_branches = set(branches()) merge_base_map = {b: get_or_create_merge_base(b) for b in all_branches} merge_base_map = {b: v for b, v in merge_base_map.iteritems() if v} if current in all_branches: all_branches.remove(current) all_tags = set(tags()) try: for line in log_proc.stdout.xreadlines(): if merge_base_map: commit = line[line.find(BRIGHT_RED)+len(BRIGHT_RED):line.find('\t')] base_for_branches = set() for branch, sha in merge_base_map.iteritems(): if sha.startswith(commit): base_for_branches.add(branch) if base_for_branches: newline = '\r\n' if line.endswith('\r\n') else '\n' line = line.rstrip(newline) line += ''.join( (BRIGHT, WHITE, ' <(%s)' % (', '.join(base_for_branches)), RESET, newline)) for b in base_for_branches: del merge_base_map[b] start = line.find(GREEN+' (') end = line.find(')', start) if start != -1 and end != -1: start += len(GREEN) + 2 branch_list = line[start:end].split(', ') branches_str = '' if branch_list: colored_branches = [] head_marker = '' for b in branch_list: if b == "HEAD": head_marker = BLUEBAK+BRIGHT+'*' continue if b == current: colored_branches.append(CYAN+BRIGHT+b+RESET) current = None elif b in all_branches: colored_branches.append(GREEN+BRIGHT+b+RESET) all_branches.remove(b) elif b in all_tags: colored_branches.append(MAGENTA+BRIGHT+b+RESET) elif b.startswith('tag: '): colored_branches.append(MAGENTA+BRIGHT+b[5:]+RESET) else: colored_branches.append(RED+b) branches_str = '(%s) ' % ((GREEN+", ").join(colored_branches)+GREEN) line = "%s%s%s" % (line[:start-1], branches_str, line[end+5:]) if head_marker: line = line.replace('*', head_marker, 1) sys.stdout.write(line) except (IOError, KeyboardInterrupt): pass finally: sys.stderr.close() sys.stdout.close() return 0
def main(args=None): parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='store_true') parser.add_argument('--keep-going', '-k', action='store_true', help='Keep processing past failed rebases.') parser.add_argument('--no_fetch', '--no-fetch', '-n', action='store_true', help='Skip fetching remotes.') parser.add_argument( '--current', action='store_true', help='Only rebase the current branch.') parser.add_argument('branches', nargs='*', help='Branches to be rebased. All branches are assumed ' 'if none specified.') opts = parser.parse_args(args) if opts.verbose: # pragma: no cover logging.getLogger().setLevel(logging.DEBUG) # TODO(iannucci): snapshot all branches somehow, so we can implement # `git rebase-update --undo`. # * Perhaps just copy packed-refs + refs/ + logs/ to the side? # * commit them to a secret ref? # * Then we could view a summary of each run as a # `diff --stat` on that secret ref. if git.in_rebase(): # TODO(iannucci): Be able to resume rebase with flags like --continue, # etc. print('Rebase in progress. Please complete the rebase before running ' '`git rebase-update`.') return 1 return_branch, return_workdir = find_return_branch_workdir() os.chdir(git.run('rev-parse', '--show-toplevel')) if git.current_branch() == 'HEAD': if git.run('status', '--porcelain'): print('Cannot rebase-update with detached head + uncommitted changes.') return 1 else: git.freeze() # just in case there are any local changes. branches_to_rebase = set(opts.branches) if opts.current: branches_to_rebase.add(git.current_branch()) skipped, branch_tree = git.get_branch_tree() if branches_to_rebase: skipped = set(skipped).intersection(branches_to_rebase) for branch in skipped: print('Skipping %s: No upstream specified' % branch) if not opts.no_fetch: fetch_remotes(branch_tree) merge_base = {} for branch, parent in branch_tree.items(): merge_base[branch] = git.get_or_create_merge_base(branch, parent) logging.debug('branch_tree: %s' % pformat(branch_tree)) logging.debug('merge_base: %s' % pformat(merge_base)) retcode = 0 unrebased_branches = [] # Rebase each branch starting with the root-most branches and working # towards the leaves. for branch, parent in git.topo_iter(branch_tree): # Only rebase specified branches, unless none specified. if branches_to_rebase and branch not in branches_to_rebase: continue if git.is_dormant(branch): print('Skipping dormant branch', branch) else: ret = rebase_branch(branch, parent, merge_base[branch]) if not ret: retcode = 1 if opts.keep_going: print('--keep-going set, continuing with next branch.') unrebased_branches.append(branch) if git.in_rebase(): git.run_with_retcode('rebase', '--abort') if git.in_rebase(): # pragma: no cover print('Failed to abort rebase. Something is really wrong.') break else: break if unrebased_branches: print() print('The following branches could not be cleanly rebased:') for branch in unrebased_branches: print(' %s' % branch) if not retcode: remove_empty_branches(branch_tree) # return_branch may not be there any more. if return_branch in git.branches(): git.run('checkout', return_branch) git.thaw() else: root_branch = git.root() if return_branch != 'HEAD': print("%s was merged with its parent, checking out %s instead." % (git.unicode_repr(return_branch), git.unicode_repr(root_branch))) git.run('checkout', root_branch) # return_workdir may also not be there any more. if return_workdir: try: os.chdir(return_workdir) except OSError as e: print( "Unable to return to original workdir %r: %s" % (return_workdir, e)) git.set_config(STARTING_BRANCH_KEY, '') git.set_config(STARTING_WORKDIR_KEY, '') return retcode
def main(args=None): parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='store_true') parser.add_argument('--no_fetch', '--no-fetch', '-n', action='store_true', help='Skip fetching remotes.') opts = parser.parse_args(args) if opts.verbose: # pragma: no cover logging.getLogger().setLevel(logging.DEBUG) # TODO(iannucci): snapshot all branches somehow, so we can implement # `git rebase-update --undo`. # * Perhaps just copy packed-refs + refs/ + logs/ to the side? # * commit them to a secret ref? # * Then we could view a summary of each run as a # `diff --stat` on that secret ref. if git.in_rebase(): # TODO(iannucci): Be able to resume rebase with flags like --continue, # etc. print( 'Rebase in progress. Please complete the rebase before running ' '`git rebase-update`.') return 1 return_branch, return_workdir = find_return_branch_workdir() os.chdir(git.run('rev-parse', '--show-toplevel')) if git.current_branch() == 'HEAD': if git.run('status', '--porcelain'): print 'Cannot rebase-update with detached head + uncommitted changes.' return 1 else: git.freeze() # just in case there are any local changes. skipped, branch_tree = git.get_branch_tree() for branch in skipped: print 'Skipping %s: No upstream specified' % branch if not opts.no_fetch: fetch_remotes(branch_tree) merge_base = {} for branch, parent in branch_tree.iteritems(): merge_base[branch] = git.get_or_create_merge_base(branch, parent) logging.debug('branch_tree: %s' % pformat(branch_tree)) logging.debug('merge_base: %s' % pformat(merge_base)) retcode = 0 # Rebase each branch starting with the root-most branches and working # towards the leaves. for branch, parent in git.topo_iter(branch_tree): if git.is_dormant(branch): print 'Skipping dormant branch', branch else: ret = rebase_branch(branch, parent, merge_base[branch]) if not ret: retcode = 1 break if not retcode: remove_empty_branches(branch_tree) # return_branch may not be there any more. if return_branch in git.branches(): git.run('checkout', return_branch) git.thaw() else: root_branch = git.root() if return_branch != 'HEAD': print( "%r was merged with its parent, checking out %r instead." % (return_branch, root_branch)) git.run('checkout', root_branch) if return_workdir: os.chdir(return_workdir) git.set_config(STARTING_BRANCH_KEY, '') git.set_config(STARTING_WORKDIR_KEY, '') return retcode
def main(args): root_ref = root() parser = argparse.ArgumentParser() g = parser.add_mutually_exclusive_group() g.add_argument('new_parent', nargs='?', help='New parent branch (or tag) to reparent to.') g.add_argument('--root', action='store_true', help='Reparent to the configured root branch (%s).' % root_ref) g.add_argument('--lkgr', action='store_true', help='Reparent to the lkgr tag.') opts = parser.parse_args(args) # TODO(iannucci): Allow specification of the branch-to-reparent branch = current_branch() if opts.root: new_parent = root_ref elif opts.lkgr: new_parent = 'lkgr' else: if not opts.new_parent: parser.error('Must specify new parent somehow') new_parent = opts.new_parent cur_parent = upstream(branch) if branch == 'HEAD' or not branch: parser.error('Must be on the branch you want to reparent') if new_parent == cur_parent: parser.error('Cannot reparent a branch to its existing parent') if not cur_parent: msg = ( "Unable to determine %s@{upstream}.\n\nThis can happen if you didn't use " "`git new-branch` to create the branch and haven't used " "`git branch --set-upstream-to` to assign it one.\n\nPlease assign an " "upstream branch and then run this command again." ) print(msg % branch, file=sys.stderr) return 1 mbase = get_or_create_merge_base(branch, cur_parent) all_tags = tags() if cur_parent in all_tags: cur_parent += ' [tag]' try: run('show-ref', new_parent) except subprocess2.CalledProcessError: print('fatal: invalid reference: %s' % new_parent, file=sys.stderr) return 1 if new_parent in all_tags: print("Reparenting %s to track %s [tag] (was %s)" % (branch, new_parent, cur_parent)) set_branch_config(branch, 'remote', '.') set_branch_config(branch, 'merge', new_parent) else: print("Reparenting %s to track %s (was %s)" % (branch, new_parent, cur_parent)) run('branch', '--set-upstream-to', new_parent, branch) manual_merge_base(branch, mbase, new_parent) # ONLY rebase-update the branch which moved (and dependants) _, branch_tree = get_branch_tree() branches = [branch] for branch, parent in topo_iter(branch_tree): if parent in branches: branches.append(branch) return git_rebase_update.main(['--no-fetch'] + branches)