git_nav_downstream.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. """
  6. Checks out a downstream branch from the currently checked out branch. If there
  7. is more than one downstream branch, then this script will prompt you to select
  8. which branch.
  9. """
  10. import argparse
  11. import sys
  12. import gclient_utils
  13. from git_common import current_branch, branches, upstream, run, hash_one
  14. import metrics
  15. @metrics.collector.collect_metrics('git nav-downstream')
  16. def main(args):
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('--pick',
  19. help=('The number to pick if this command would '
  20. 'prompt'))
  21. opts = parser.parse_args(args)
  22. upfn = upstream
  23. cur = current_branch()
  24. if cur == 'HEAD':
  25. def _upfn(b):
  26. parent = upstream(b)
  27. if parent:
  28. return hash_one(parent)
  29. upfn = _upfn
  30. cur = hash_one(cur)
  31. downstreams = [b for b in branches() if upfn(b) == cur]
  32. if not downstreams:
  33. print("No downstream branches")
  34. return 1
  35. if len(downstreams) == 1:
  36. run('checkout', downstreams[0], stdout=sys.stdout, stderr=sys.stderr)
  37. else:
  38. high = len(downstreams) - 1
  39. while True:
  40. print("Please select a downstream branch")
  41. for i, b in enumerate(downstreams):
  42. print(" %d. %s" % (i, b))
  43. prompt = "Selection (0-%d)[0]: " % high
  44. r = opts.pick
  45. if r:
  46. print(prompt + r)
  47. else:
  48. r = gclient_utils.AskForData(prompt).strip() or '0'
  49. if not r.isdigit() or (0 > int(r) > high):
  50. print("Invalid choice.")
  51. else:
  52. run('checkout',
  53. downstreams[int(r)],
  54. stdout=sys.stdout,
  55. stderr=sys.stderr)
  56. break
  57. return 0
  58. if __name__ == '__main__':
  59. with metrics.collector.print_notice_and_exit():
  60. sys.exit(main(sys.argv[1:]))