fetch.py 11 KB

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