blob: a600eb242762bac037f36adf8debccf9a137c866 [file] [log] [blame]
Josip Sokcevic4de5dea2022-03-23 21:15:14 +00001#!/usr/bin/env python3
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.
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +00005"""Rename the current branch while maintaining correct dependencies."""
6
7import argparse
8import sys
9
10import subprocess2
11
12from git_common import current_branch, run, set_branch_config, branch_config
13from git_common import branch_config_map
14
Mike Frysinger124bb8e2023-09-06 05:48:55 +000015
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000016def main(args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000017 current = current_branch()
18 if current == 'HEAD':
19 current = None
20 old_name_help = 'The old branch to rename.'
21 if current:
22 old_name_help += ' (default %(default)r)'
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000023
Mike Frysinger124bb8e2023-09-06 05:48:55 +000024 parser = argparse.ArgumentParser()
25 parser.add_argument('old_name',
26 nargs=('?' if current else 1),
27 help=old_name_help,
28 default=current)
29 parser.add_argument('new_name', help='The new branch name.')
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000030
Mike Frysinger124bb8e2023-09-06 05:48:55 +000031 opts = parser.parse_args(args)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000032
Mike Frysinger124bb8e2023-09-06 05:48:55 +000033 # when nargs=1, we get a list :(
34 if isinstance(opts.old_name, list):
35 opts.old_name = opts.old_name[0]
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000036
Mike Frysinger124bb8e2023-09-06 05:48:55 +000037 try:
38 run('branch', '-m', opts.old_name, opts.new_name)
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000039
Mike Frysinger124bb8e2023-09-06 05:48:55 +000040 # update the downstreams
41 for branch, merge in branch_config_map('merge').items():
42 if merge == 'refs/heads/' + opts.old_name:
43 # Only care about local branches
44 if branch_config(branch, 'remote') == '.':
45 set_branch_config(branch, 'merge',
46 'refs/heads/' + opts.new_name)
47 except subprocess2.CalledProcessError as cpe:
48 sys.stderr.write(cpe.stderr.decode('utf-8', 'replace'))
49 return 1
50 return 0
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000051
52
53if __name__ == '__main__': # pragma: no cover
Mike Frysinger124bb8e2023-09-06 05:48:55 +000054 try:
55 sys.exit(main(sys.argv[1:]))
56 except KeyboardInterrupt:
57 sys.stderr.write('interrupted\n')
58 sys.exit(1)