fetch.py 11 KB

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