git_new_branch.py 1.9 KB

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