git_rename_branch.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  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. """Rename the current branch while maintaining correct dependencies."""
  6. import argparse
  7. import sys
  8. import subprocess2
  9. from git_common import current_branch, run, set_branch_config, branch_config
  10. from git_common import branch_config_map
  11. def main(args):
  12. current = current_branch()
  13. if current == 'HEAD':
  14. current = None
  15. old_name_help = 'The old branch to rename.'
  16. if current:
  17. old_name_help += ' (default %(default)r)'
  18. parser = argparse.ArgumentParser()
  19. parser.add_argument('old_name',
  20. nargs=('?' if current else 1),
  21. help=old_name_help,
  22. default=current)
  23. parser.add_argument('new_name', help='The new branch name.')
  24. opts = parser.parse_args(args)
  25. # when nargs=1, we get a list :(
  26. if isinstance(opts.old_name, list):
  27. opts.old_name = opts.old_name[0]
  28. try:
  29. run('branch', '-m', opts.old_name, opts.new_name)
  30. # update the downstreams
  31. for branch, merge in branch_config_map('merge').items():
  32. if merge == 'refs/heads/' + opts.old_name:
  33. # Only care about local branches
  34. if branch_config(branch, 'remote') == '.':
  35. set_branch_config(branch, 'merge',
  36. 'refs/heads/' + opts.new_name)
  37. except subprocess2.CalledProcessError as cpe:
  38. sys.stderr.write(cpe.stderr.decode('utf-8', 'replace'))
  39. return 1
  40. return 0
  41. if __name__ == '__main__': # pragma: no cover
  42. try:
  43. sys.exit(main(sys.argv[1:]))
  44. except KeyboardInterrupt:
  45. sys.stderr.write('interrupted\n')
  46. sys.exit(1)