cit.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python
  2. # Copyright (c) 2015 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. """Wrapper for updating and calling infra.git tools.
  6. This tool does a two things:
  7. * Maintains a infra.git checkout pinned at "deployed" in the home dir
  8. * Acts as an alias to infra.tools.*
  9. * Acts as an alias to infra.git/cipd/<executable>
  10. """
  11. # TODO(hinoka,iannucci): Pre-pack infra tools in cipd package with vpython spec.
  12. from __future__ import print_function
  13. import argparse
  14. import sys
  15. import os
  16. import re
  17. import subprocess2 as subprocess
  18. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  19. GCLIENT = os.path.join(SCRIPT_DIR, 'gclient.py')
  20. TARGET_DIR = os.path.expanduser(os.path.join('~', '.chrome-infra'))
  21. INFRA_DIR = os.path.join(TARGET_DIR, 'infra')
  22. def get_git_rev(target, branch):
  23. return subprocess.check_output(
  24. ['git', 'log', '--format=%B', '-n1', branch], cwd=target)
  25. def need_to_update(branch):
  26. """Checks to see if we need to update the ~/.chrome-infra/infra checkout."""
  27. try:
  28. cmd = [sys.executable, GCLIENT, 'revinfo']
  29. subprocess.check_call(
  30. cmd, cwd=os.path.join(TARGET_DIR), stdout=subprocess.VOID)
  31. except subprocess.CalledProcessError:
  32. return True # Gclient failed, definitely need to update.
  33. except OSError:
  34. return True # Gclient failed, definitely need to update.
  35. if not os.path.isdir(INFRA_DIR):
  36. return True
  37. local_rev = get_git_rev(INFRA_DIR, 'HEAD')
  38. subprocess.check_call(
  39. ['git', 'fetch', 'origin'], cwd=INFRA_DIR,
  40. stdout=subprocess.VOID, stderr=subprocess.STDOUT)
  41. origin_rev = get_git_rev(INFRA_DIR, 'origin/%s' % (branch,))
  42. return origin_rev != local_rev
  43. def ensure_infra(branch):
  44. """Ensures that infra.git is present in ~/.chrome-infra."""
  45. sys.stderr.write(
  46. 'Fetching infra@%s into %s, may take a couple of minutes...' % (
  47. branch, TARGET_DIR))
  48. sys.stderr.flush()
  49. if not os.path.isdir(TARGET_DIR):
  50. os.mkdir(TARGET_DIR)
  51. if not os.path.exists(os.path.join(TARGET_DIR, '.gclient')):
  52. subprocess.check_call(
  53. [sys.executable, os.path.join(SCRIPT_DIR, 'fetch.py'), 'infra'],
  54. cwd=TARGET_DIR,
  55. stdout=subprocess.VOID)
  56. subprocess.check_call(
  57. [sys.executable, GCLIENT, 'sync', '--revision', 'origin/%s' % (branch,)],
  58. cwd=TARGET_DIR,
  59. stdout=subprocess.VOID)
  60. sys.stderr.write(' done.\n')
  61. sys.stderr.flush()
  62. def is_exe(filename):
  63. """Given a full filepath, return true if the file is an executable."""
  64. if sys.platform.startswith('win'):
  65. return filename.endswith('.exe')
  66. else:
  67. return os.path.isfile(filename) and os.access(filename, os.X_OK)
  68. def get_available_tools():
  69. """Returns a tuple of (list of infra tools, list of cipd tools)"""
  70. infra_tools = []
  71. cipd_tools = []
  72. starting = os.path.join(TARGET_DIR, 'infra', 'infra', 'tools')
  73. for root, _, files in os.walk(starting):
  74. if '__main__.py' in files:
  75. infra_tools.append(root[len(starting)+1:].replace(os.path.sep, '.'))
  76. cipd = os.path.join(TARGET_DIR, 'infra', 'cipd')
  77. for fn in os.listdir(cipd):
  78. if is_exe(os.path.join(cipd, fn)):
  79. cipd_tools.append(fn)
  80. return (sorted(infra_tools), sorted(cipd_tools))
  81. def usage():
  82. infra_tools, cipd_tools = get_available_tools()
  83. print("""usage: cit.py <name of tool> [args for tool]
  84. Wrapper for maintaining and calling tools in:
  85. "infra.git/run.py infra.tools.*"
  86. "infra.git/cipd/*"
  87. Available infra tools are:""")
  88. for tool in infra_tools:
  89. print(' * %s' % tool)
  90. print("""
  91. Available cipd tools are:""")
  92. for tool in cipd_tools:
  93. print(' * %s' % tool)
  94. def run(args):
  95. if not args:
  96. return usage()
  97. tool_name = args[0]
  98. # Check to see if it is a infra tool first.
  99. infra_dir = os.path.join(
  100. TARGET_DIR, 'infra', 'infra', 'tools', *tool_name.split('.'))
  101. cipd_file = os.path.join(TARGET_DIR, 'infra', 'cipd', tool_name)
  102. if sys.platform.startswith('win'):
  103. cipd_file += '.exe'
  104. if (os.path.isdir(infra_dir)
  105. and os.path.isfile(os.path.join(infra_dir, '__main__.py'))):
  106. cmd = [
  107. sys.executable, os.path.join(TARGET_DIR, 'infra', 'run.py'),
  108. 'infra.tools.%s' % tool_name]
  109. elif os.path.isfile(cipd_file) and is_exe(cipd_file):
  110. cmd = [cipd_file]
  111. else:
  112. print('Unknown tool "%s"' % tool_name, file=sys.stderr)
  113. return usage()
  114. # Add the remaining arguments.
  115. cmd.extend(args[1:])
  116. return subprocess.call(cmd)
  117. def main():
  118. parser = argparse.ArgumentParser("Chrome Infrastructure CLI.")
  119. parser.add_argument('-b', '--infra-branch', default='cit',
  120. help="The name of the 'infra' branch to use (default is %(default)s).")
  121. parser.add_argument('args', nargs=argparse.REMAINDER)
  122. args, extras = parser.parse_known_args()
  123. if args.args and args.args[0] == '--':
  124. args.args.pop(0)
  125. if extras:
  126. args.args = extras + args.args
  127. if need_to_update(args.infra_branch):
  128. ensure_infra(args.infra_branch)
  129. return run(args.args)
  130. if __name__ == '__main__':
  131. sys.exit(main())