git_nav_downstream.py 2.2 KB

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