git_rename_branch.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. import gclient_utils
  12. def main(args):
  13. if gclient_utils.IsEnvCog():
  14. print('rename-branch command is not supported in non-git environment.',
  15. file=sys.stderr)
  16. return 1
  17. 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)'
  23. parser = argparse.ArgumentParser()
  24. parser.add_argument('old_name',
  25. nargs=('?' if current else 1),
  26. help=old_name_help,
  27. default=current)
  28. parser.add_argument('new_name', help='The new branch name.')
  29. opts = parser.parse_args(args)
  30. # when nargs=1, we get a list :(
  31. if isinstance(opts.old_name, list):
  32. opts.old_name = opts.old_name[0]
  33. try:
  34. run('branch', '-m', opts.old_name, opts.new_name)
  35. # update the downstreams
  36. for branch, merge in branch_config_map('merge').items():
  37. if merge == 'refs/heads/' + opts.old_name:
  38. # Only care about local branches
  39. if branch_config(branch, 'remote') == '.':
  40. set_branch_config(branch, 'merge',
  41. 'refs/heads/' + opts.new_name)
  42. except subprocess2.CalledProcessError as cpe:
  43. sys.stderr.write(cpe.stderr.decode('utf-8', 'replace'))
  44. return 1
  45. return 0
  46. if __name__ == '__main__': # pragma: no cover
  47. try:
  48. sys.exit(main(sys.argv[1:]))
  49. except KeyboardInterrupt:
  50. sys.stderr.write('interrupted\n')
  51. sys.exit(1)