git_new_branch.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env python
  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. import argparse
  6. import sys
  7. import subprocess2
  8. from git_common import run, root, set_config, get_or_create_merge_base, tags
  9. from git_common import hash_one
  10. def main(args):
  11. parser = argparse.ArgumentParser(
  12. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  13. )
  14. parser.add_argument('branch_name')
  15. g = parser.add_mutually_exclusive_group()
  16. g.add_argument('--upstream_current', action='store_true',
  17. help='set upstream branch to current branch.')
  18. g.add_argument('--upstream', metavar='REF', default=root(),
  19. help='upstream branch (or tag) to track.')
  20. g.add_argument('--lkgr', action='store_const', const='lkgr', dest='upstream',
  21. help='set basis ref for new branch to lkgr.')
  22. opts = parser.parse_args(args)
  23. try:
  24. if opts.upstream_current:
  25. run('checkout', '--track', '-b', opts.branch_name)
  26. else:
  27. if opts.upstream in tags():
  28. # TODO(iannucci): ensure that basis_ref is an ancestor of HEAD?
  29. run('checkout', '--no-track', '-b', opts.branch_name,
  30. hash_one(opts.upstream))
  31. set_config('branch.%s.remote' % opts.branch_name, '.')
  32. set_config('branch.%s.merge' % opts.branch_name, opts.upstream)
  33. else:
  34. # TODO(iannucci): Detect unclean workdir then stash+pop if we need to
  35. # teleport to a conflicting portion of history?
  36. run('checkout', '--track', opts.upstream, '-b', opts.branch_name)
  37. get_or_create_merge_base(opts.branch_name)
  38. except subprocess2.CalledProcessError as cpe:
  39. sys.stdout.write(cpe.stdout)
  40. sys.stderr.write(cpe.stderr)
  41. return 1
  42. sys.stderr.write('Switched to branch %s.' % opts.branch_name)
  43. if __name__ == '__main__': # pragma: no cover
  44. sys.exit(main(sys.argv[1:]))