fetch.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2013 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. Tool to perform checkouts in one easy command line!
  7. Usage:
  8. fetch <config> [--property=value [--property2=value2 ...]]
  9. This script is a wrapper around various version control and repository
  10. checkout commands. It requires a |config| name, fetches data from that
  11. config in depot_tools/fetch_configs, and then performs all necessary inits,
  12. checkouts, pulls, fetches, etc.
  13. Optional arguments may be passed on the command line in key-value pairs.
  14. These parameters will be passed through to the config's main method.
  15. """
  16. from __future__ import print_function
  17. import json
  18. import argparse
  19. import os
  20. import pipes
  21. import re
  22. import subprocess
  23. import sys
  24. import textwrap
  25. import git_common
  26. from distutils import spawn
  27. SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
  28. #################################################
  29. # Checkout class definitions.
  30. #################################################
  31. class Checkout(object):
  32. """Base class for implementing different types of checkouts.
  33. Attributes:
  34. |base|: the absolute path of the directory in which this script is run.
  35. |spec|: the spec for this checkout as returned by the config. Different
  36. subclasses will expect different keys in this dictionary.
  37. |root|: the directory into which the checkout will be performed, as returned
  38. by the config. This is a relative path from |base|.
  39. """
  40. def __init__(self, options, spec, root):
  41. self.base = os.getcwd()
  42. self.options = options
  43. self.spec = spec
  44. self.root = root
  45. def exists(self):
  46. """Check does this checkout already exist on desired location"""
  47. def init(self):
  48. pass
  49. def run(self, cmd, return_stdout=False, **kwargs):
  50. print('Running: %s' % (' '.join(pipes.quote(x) for x in cmd)))
  51. if self.options.dry_run:
  52. return ''
  53. if return_stdout:
  54. return subprocess.check_output(cmd, **kwargs).decode()
  55. try:
  56. subprocess.check_call(cmd, **kwargs)
  57. except subprocess.CalledProcessError as e:
  58. # If the subprocess failed, it likely emitted its own distress message
  59. # already - don't scroll that message off the screen with a stack trace
  60. # from this program as well. Emit a terse message and bail out here;
  61. # otherwise a later step will try doing more work and may hide the
  62. # subprocess message.
  63. print('Subprocess failed with return code %d.' % e.returncode)
  64. sys.exit(e.returncode)
  65. return ''
  66. class GclientCheckout(Checkout):
  67. def run_gclient(self, *cmd, **kwargs):
  68. if not spawn.find_executable('gclient'):
  69. cmd_prefix = (sys.executable, os.path.join(SCRIPT_PATH, 'gclient.py'))
  70. else:
  71. cmd_prefix = ('gclient',)
  72. return self.run(cmd_prefix + cmd, **kwargs)
  73. def exists(self):
  74. try:
  75. gclient_root = self.run_gclient('root', return_stdout=True).strip()
  76. return (os.path.exists(os.path.join(gclient_root, '.gclient')) or
  77. os.path.exists(os.path.join(os.getcwd(), self.root, '.git')))
  78. except subprocess.CalledProcessError:
  79. pass
  80. return os.path.exists(os.path.join(os.getcwd(), self.root))
  81. class GitCheckout(Checkout):
  82. def run_git(self, *cmd, **kwargs):
  83. print('Running: git %s' % (' '.join(pipes.quote(x) for x in cmd)))
  84. if self.options.dry_run:
  85. return ''
  86. return git_common.run(*cmd, **kwargs)
  87. class GclientGitCheckout(GclientCheckout, GitCheckout):
  88. def __init__(self, options, spec, root):
  89. super(GclientGitCheckout, self).__init__(options, spec, root)
  90. assert 'solutions' in self.spec
  91. def _format_spec(self):
  92. def _format_literal(lit):
  93. if isinstance(lit, str) or (sys.version_info.major == 2 and
  94. isinstance(lit, unicode)):
  95. return '"%s"' % lit
  96. if isinstance(lit, list):
  97. return '[%s]' % ', '.join(_format_literal(i) for i in lit)
  98. return '%r' % lit
  99. soln_strings = []
  100. for soln in self.spec['solutions']:
  101. soln_string = '\n'.join(' "%s": %s,' % (key, _format_literal(value))
  102. for key, value in soln.items())
  103. soln_strings.append(' {\n%s\n },' % soln_string)
  104. gclient_spec = 'solutions = [\n%s\n]\n' % '\n'.join(soln_strings)
  105. extra_keys = ['target_os', 'target_os_only', 'cache_dir']
  106. gclient_spec += ''.join('%s = %s\n' % (key, _format_literal(self.spec[key]))
  107. for key in extra_keys if key in self.spec)
  108. return gclient_spec
  109. def init(self):
  110. # Configure and do the gclient checkout.
  111. self.run_gclient('config', '--spec', self._format_spec())
  112. sync_cmd = ['sync']
  113. if self.options.nohooks:
  114. sync_cmd.append('--nohooks')
  115. if self.options.nohistory:
  116. sync_cmd.append('--no-history')
  117. if self.spec.get('with_branch_heads', False):
  118. sync_cmd.append('--with_branch_heads')
  119. self.run_gclient(*sync_cmd)
  120. # Configure git.
  121. wd = os.path.join(self.base, self.root)
  122. if self.options.dry_run:
  123. print('cd %s' % wd)
  124. self.run_git(
  125. 'submodule', 'foreach',
  126. 'git config -f $toplevel/.git/config submodule.$name.ignore all',
  127. cwd=wd)
  128. if not self.options.nohistory:
  129. self.run_git(
  130. 'config', '--add', 'remote.origin.fetch',
  131. '+refs/tags/*:refs/tags/*', cwd=wd)
  132. self.run_git('config', 'diff.ignoreSubmodules', 'all', cwd=wd)
  133. CHECKOUT_TYPE_MAP = {
  134. 'gclient': GclientCheckout,
  135. 'gclient_git': GclientGitCheckout,
  136. 'git': GitCheckout,
  137. }
  138. def CheckoutFactory(type_name, options, spec, root):
  139. """Factory to build Checkout class instances."""
  140. class_ = CHECKOUT_TYPE_MAP.get(type_name)
  141. if not class_:
  142. raise KeyError('unrecognized checkout type: %s' % type_name)
  143. return class_(options, spec, root)
  144. def handle_args(argv):
  145. """Gets the config name from the command line arguments."""
  146. configs_dir = os.path.join(SCRIPT_PATH, 'fetch_configs')
  147. configs = [f[:-3] for f in os.listdir(configs_dir) if f.endswith('.py')]
  148. configs.sort()
  149. parser = argparse.ArgumentParser(
  150. formatter_class=argparse.RawDescriptionHelpFormatter,
  151. description='''
  152. This script can be used to download the Chromium sources. See
  153. http://www.chromium.org/developers/how-tos/get-the-code
  154. for full usage instructions.''',
  155. epilog='Valid fetch configs:\n' + \
  156. '\n'.join(map(lambda s: ' ' + s, configs))
  157. )
  158. parser.add_argument('-n', '--dry-run', action='store_true', default=False,
  159. help='Don\'t run commands, only print them.')
  160. parser.add_argument('--nohooks',
  161. '--no-hooks',
  162. action='store_true',
  163. default=False,
  164. help='Don\'t run hooks after checkout.')
  165. parser.add_argument(
  166. '--nohistory',
  167. '--no-history',
  168. action='store_true',
  169. default=False,
  170. help='Perform shallow clones, don\'t fetch the full git history.')
  171. parser.add_argument('--force', action='store_true', default=False,
  172. help='(dangerous) Don\'t look for existing .gclient file.')
  173. parser.add_argument(
  174. '-p',
  175. '--protocol-override',
  176. type=str,
  177. default=None,
  178. help='Protocol to use to fetch dependencies, defaults to https.')
  179. parser.add_argument('config', type=str,
  180. help="Project to fetch, e.g. chromium.")
  181. parser.add_argument('props', metavar='props', type=str,
  182. nargs=argparse.REMAINDER, default=[])
  183. args = parser.parse_args(argv[1:])
  184. # props passed to config must be of the format --<name>=<value>
  185. looks_like_arg = lambda arg: arg.startswith('--') and arg.count('=') == 1
  186. bad_param = [x for x in args.props if not looks_like_arg(x)]
  187. if bad_param:
  188. print('Error: Got bad arguments %s' % bad_param)
  189. parser.print_help()
  190. sys.exit(1)
  191. return args
  192. def run_config_fetch(config, props, aliased=False):
  193. """Invoke a config's fetch method with the passed-through args
  194. and return its json output as a python object."""
  195. config_path = os.path.abspath(
  196. os.path.join(SCRIPT_PATH, 'fetch_configs', config))
  197. if not os.path.exists(config_path + '.py'):
  198. print("Could not find a config for %s" % config)
  199. sys.exit(1)
  200. cmd = [sys.executable, config_path + '.py', 'fetch'] + props
  201. result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
  202. spec = json.loads(result.decode("utf-8"))
  203. if 'alias' in spec:
  204. assert not aliased
  205. return run_config_fetch(
  206. spec['alias']['config'], spec['alias']['props'] + props, aliased=True)
  207. cmd = [sys.executable, config_path + '.py', 'root']
  208. result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
  209. root = json.loads(result.decode("utf-8"))
  210. return spec, root
  211. def run(options, spec, root):
  212. """Perform a checkout with the given type and configuration.
  213. Args:
  214. options: Options instance.
  215. spec: Checkout configuration returned by the the config's fetch_spec
  216. method (checkout type, repository url, etc.).
  217. root: The directory into which the repo expects to be checkout out.
  218. """
  219. assert 'type' in spec
  220. checkout_type = spec['type']
  221. checkout_spec = spec['%s_spec' % checkout_type]
  222. # Use sso:// by default if the env is cog
  223. if not options.protocol_override and \
  224. (any(os.getcwd().startswith(x) for x in [
  225. '/google/src/cloud', '/google/cog/cloud'])):
  226. options.protocol_override = 'sso'
  227. # Update solutions with protocol_override field
  228. if options.protocol_override is not None:
  229. for solution in checkout_spec['solutions']:
  230. solution['protocol_override'] = options.protocol_override
  231. try:
  232. checkout = CheckoutFactory(checkout_type, options, checkout_spec, root)
  233. except KeyError:
  234. return 1
  235. if not options.force and checkout.exists():
  236. print('Your current directory appears to already contain, or be part of, ')
  237. print('a checkout. "fetch" is used only to get new checkouts. Use ')
  238. print('"gclient sync" to update existing checkouts.')
  239. print()
  240. print('Fetch also does not yet deal with partial checkouts, so if fetch')
  241. print('failed, delete the checkout and start over (crbug.com/230691).')
  242. return 1
  243. return checkout.init()
  244. def main():
  245. args = handle_args(sys.argv)
  246. spec, root = run_config_fetch(args.config, args.props)
  247. return run(args, spec, root)
  248. if __name__ == '__main__':
  249. try:
  250. sys.exit(main())
  251. except KeyboardInterrupt:
  252. sys.stderr.write('interrupted\n')
  253. sys.exit(1)