fetch.py 10 KB

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