blob: 7483f48a8671ac73923ce0f8dadc93765df6625a [file] [log] [blame]
agable@chromium.orgcc023502013-04-03 20:24:21 +00001#!/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"""
7Tool to perform checkouts in one easy command line!
8
9Usage:
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +000010 fetch <config> [--property=value [--property2=value2 ...]]
agable@chromium.orgcc023502013-04-03 20:24:21 +000011
12This script is a wrapper around various version control and repository
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +000013checkout commands. It requires a |config| name, fetches data from that
14config in depot_tools/fetch_configs, and then performs all necessary inits,
agable@chromium.orgcc023502013-04-03 20:24:21 +000015checkouts, pulls, fetches, etc.
16
17Optional arguments may be passed on the command line in key-value pairs.
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +000018These parameters will be passed through to the config's main method.
agable@chromium.orgcc023502013-04-03 20:24:21 +000019"""
20
21import json
digit@chromium.org3596d582013-12-13 17:07:33 +000022import optparse
agable@chromium.orgcc023502013-04-03 20:24:21 +000023import os
iannucci@chromium.orgcc2d3e32014-08-06 19:47:54 +000024import pipes
agable@chromium.orgcc023502013-04-03 20:24:21 +000025import subprocess
26import sys
iannucci@chromium.orgcc2d3e32014-08-06 19:47:54 +000027import textwrap
agable@chromium.orgcc023502013-04-03 20:24:21 +000028
dpranke@chromium.org6cc97a12013-04-12 06:15:58 +000029from distutils import spawn
30
agable@chromium.orgcc023502013-04-03 20:24:21 +000031
32SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
33
agable@chromium.orgcc023502013-04-03 20:24:21 +000034#################################################
35# Checkout class definitions.
36#################################################
37class Checkout(object):
38 """Base class for implementing different types of checkouts.
39
40 Attributes:
41 |base|: the absolute path of the directory in which this script is run.
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +000042 |spec|: the spec for this checkout as returned by the config. Different
agable@chromium.orgcc023502013-04-03 20:24:21 +000043 subclasses will expect different keys in this dictionary.
44 |root|: the directory into which the checkout will be performed, as returned
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +000045 by the config. This is a relative path from |base|.
agable@chromium.orgcc023502013-04-03 20:24:21 +000046 """
digit@chromium.org3596d582013-12-13 17:07:33 +000047 def __init__(self, options, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +000048 self.base = os.getcwd()
digit@chromium.org3596d582013-12-13 17:07:33 +000049 self.options = options
agable@chromium.orgcc023502013-04-03 20:24:21 +000050 self.spec = spec
51 self.root = root
52
53 def exists(self):
54 pass
55
56 def init(self):
57 pass
58
59 def sync(self):
60 pass
61
dpranke@chromium.org6cc97a12013-04-12 06:15:58 +000062 def run(self, cmd, **kwargs):
63 print 'Running: %s' % (' '.join(pipes.quote(x) for x in cmd))
wtc@chromium.org38e94612014-02-12 22:19:41 +000064 if self.options.dry_run:
mmoss@chromium.org294c7832015-06-17 16:16:32 +000065 return ''
mmoss@chromium.org5a447762015-06-10 20:01:39 +000066 return subprocess.check_output(cmd, **kwargs)
dpranke@chromium.org6cc97a12013-04-12 06:15:58 +000067
agable@chromium.orgcc023502013-04-03 20:24:21 +000068
69class GclientCheckout(Checkout):
70
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000071 def run_gclient(self, *cmd, **kwargs):
dpranke@chromium.org6cc97a12013-04-12 06:15:58 +000072 if not spawn.find_executable('gclient'):
73 cmd_prefix = (sys.executable, os.path.join(SCRIPT_PATH, 'gclient.py'))
74 else:
75 cmd_prefix = ('gclient',)
76 return self.run(cmd_prefix + cmd, **kwargs)
agable@chromium.orgcc023502013-04-03 20:24:21 +000077
mmoss@chromium.org5a447762015-06-10 20:01:39 +000078 def exists(self):
79 try:
80 gclient_root = self.run_gclient('root').strip()
81 return (os.path.exists(os.path.join(gclient_root, '.gclient')) or
82 os.path.exists(os.path.join(os.getcwd(), self.root)))
83 except subprocess.CalledProcessError:
84 pass
85 return os.path.exists(os.path.join(os.getcwd(), self.root))
86
agable@chromium.orgcc023502013-04-03 20:24:21 +000087
88class GitCheckout(Checkout):
89
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000090 def run_git(self, *cmd, **kwargs):
dpranke@chromium.org6cc97a12013-04-12 06:15:58 +000091 if sys.platform == 'win32' and not spawn.find_executable('git'):
mmoss@chromium.orgcc2b6a12014-02-20 17:42:59 +000092 git_path = os.path.join(SCRIPT_PATH, 'git.bat')
dpranke@chromium.org6cc97a12013-04-12 06:15:58 +000093 else:
94 git_path = 'git'
95 return self.run((git_path,) + cmd, **kwargs)
agable@chromium.orgcc023502013-04-03 20:24:21 +000096
97
jochen@chromium.orgd993e782013-04-11 20:03:13 +000098class GclientGitCheckout(GclientCheckout, GitCheckout):
agable@chromium.orgcc023502013-04-03 20:24:21 +000099
digit@chromium.org3596d582013-12-13 17:07:33 +0000100 def __init__(self, options, spec, root):
101 super(GclientGitCheckout, self).__init__(options, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000102 assert 'solutions' in self.spec
agable@chromium.org5bde64e2014-11-25 22:15:26 +0000103
104 def _format_spec(self):
105 def _format_literal(lit):
106 if isinstance(lit, basestring):
107 return '"%s"' % lit
108 if isinstance(lit, list):
109 return '[%s]' % ', '.join(_format_literal(i) for i in lit)
110 return '%r' % lit
111 soln_strings = []
112 for soln in self.spec['solutions']:
113 soln_string= '\n'.join(' "%s": %s,' % (key, _format_literal(value))
114 for key, value in soln.iteritems())
115 soln_strings.append(' {\n%s\n },' % soln_string)
116 gclient_spec = 'solutions = [\n%s\n]\n' % '\n'.join(soln_strings)
Dr Alex Gouaillarde1dd46f2016-11-28 15:00:04 +0800117 extra_keys = ['target_os', 'target_os_only', 'cache_dir']
agable@chromium.org5bde64e2014-11-25 22:15:26 +0000118 gclient_spec += ''.join('%s = %s\n' % (key, _format_literal(self.spec[key]))
119 for key in extra_keys if key in self.spec)
120 return gclient_spec
agable@chromium.orgcc023502013-04-03 20:24:21 +0000121
agable@chromium.orgcc023502013-04-03 20:24:21 +0000122 def init(self):
123 # Configure and do the gclient checkout.
agable@chromium.org5bde64e2014-11-25 22:15:26 +0000124 self.run_gclient('config', '--spec', self._format_spec())
jochen@chromium.org048da082014-05-06 08:32:40 +0000125 sync_cmd = ['sync']
agable@chromium.orgb98f3f22015-06-15 21:59:09 +0000126 if self.options.nohooks:
jochen@chromium.org048da082014-05-06 08:32:40 +0000127 sync_cmd.append('--nohooks')
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000128 if self.options.no_history:
129 sync_cmd.append('--no-history')
jochen@chromium.org048da082014-05-06 08:32:40 +0000130 if self.spec.get('with_branch_heads', False):
131 sync_cmd.append('--with_branch_heads')
132 self.run_gclient(*sync_cmd)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000133
134 # Configure git.
135 wd = os.path.join(self.base, self.root)
wtc@chromium.org38e94612014-02-12 22:19:41 +0000136 if self.options.dry_run:
agable@chromium.org2560ea72013-04-04 01:22:38 +0000137 print 'cd %s' % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000138 self.run_git(
139 'submodule', 'foreach',
140 'git config -f $toplevel/.git/config submodule.$name.ignore all',
141 cwd=wd)
iannucci@chromium.orgf2fb5e72014-04-03 02:36:44 +0000142 self.run_git(
143 'config', '--add', 'remote.origin.fetch',
144 '+refs/tags/*:refs/tags/*', cwd=wd)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000145 self.run_git('config', 'diff.ignoreSubmodules', 'all', cwd=wd)
146
jochen@chromium.orgd993e782013-04-11 20:03:13 +0000147
agable@chromium.orgcc023502013-04-03 20:24:21 +0000148CHECKOUT_TYPE_MAP = {
149 'gclient': GclientCheckout,
jochen@chromium.orgd993e782013-04-11 20:03:13 +0000150 'gclient_git': GclientGitCheckout,
agable@chromium.orgcc023502013-04-03 20:24:21 +0000151 'git': GitCheckout,
152}
153
154
digit@chromium.org3596d582013-12-13 17:07:33 +0000155def CheckoutFactory(type_name, options, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000156 """Factory to build Checkout class instances."""
157 class_ = CHECKOUT_TYPE_MAP.get(type_name)
158 if not class_:
159 raise KeyError('unrecognized checkout type: %s' % type_name)
digit@chromium.org3596d582013-12-13 17:07:33 +0000160 return class_(options, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000161
162
163#################################################
164# Utility function and file entry point.
165#################################################
166def usage(msg=None):
167 """Print help and exit."""
168 if msg:
169 print 'Error:', msg
170
iannucci@chromium.orgcc2d3e32014-08-06 19:47:54 +0000171 print textwrap.dedent("""\
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000172 usage: %s [options] <config> [--property=value [--property2=value2 ...]]
digit@chromium.org3596d582013-12-13 17:07:33 +0000173
iannucci@chromium.orgcc2d3e32014-08-06 19:47:54 +0000174 This script can be used to download the Chromium sources. See
175 http://www.chromium.org/developers/how-tos/get-the-code
176 for full usage instructions.
digit@chromium.org3596d582013-12-13 17:07:33 +0000177
iannucci@chromium.orgcc2d3e32014-08-06 19:47:54 +0000178 Valid options:
179 -h, --help, help Print this message.
180 --nohooks Don't run hooks after checkout.
iannucci@chromium.org78faf8b2016-05-09 23:26:37 +0000181 --force (dangerous) Don't look for existing .gclient file.
iannucci@chromium.orgcc2d3e32014-08-06 19:47:54 +0000182 -n, --dry-run Don't run commands, only print them.
183 --no-history Perform shallow clones, don't fetch the full git history.
184
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000185 Valid fetch configs:""") % os.path.basename(sys.argv[0])
thestig@chromium.org37103c92015-09-19 20:54:39 +0000186
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000187 configs_dir = os.path.join(SCRIPT_PATH, 'fetch_configs')
188 configs = [f[:-3] for f in os.listdir(configs_dir) if f.endswith('.py')]
189 configs.sort()
190 for fname in configs:
thestig@chromium.org37103c92015-09-19 20:54:39 +0000191 print ' ' + fname
iannucci@chromium.orgcc2d3e32014-08-06 19:47:54 +0000192
agable@chromium.orgcc023502013-04-03 20:24:21 +0000193 sys.exit(bool(msg))
194
195
196def handle_args(argv):
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000197 """Gets the config name from the command line arguments."""
agable@chromium.orgcc023502013-04-03 20:24:21 +0000198 if len(argv) <= 1:
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000199 usage('Must specify a config.')
dpranke@chromium.orge3d147d2013-04-03 20:31:27 +0000200 if argv[1] in ('-h', '--help', 'help'):
201 usage()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000202
wtc@chromium.org38e94612014-02-12 22:19:41 +0000203 dry_run = False
digit@chromium.org3596d582013-12-13 17:07:33 +0000204 nohooks = False
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000205 no_history = False
iannucci@chromium.org78faf8b2016-05-09 23:26:37 +0000206 force = False
digit@chromium.org3596d582013-12-13 17:07:33 +0000207 while len(argv) >= 2:
208 arg = argv[1]
209 if not arg.startswith('-'):
210 break
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000211 argv.pop(1)
digit@chromium.org3596d582013-12-13 17:07:33 +0000212 if arg in ('-n', '--dry-run'):
wtc@chromium.org38e94612014-02-12 22:19:41 +0000213 dry_run = True
digit@chromium.org3596d582013-12-13 17:07:33 +0000214 elif arg == '--nohooks':
215 nohooks = True
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000216 elif arg == '--no-history':
217 no_history = True
iannucci@chromium.org78faf8b2016-05-09 23:26:37 +0000218 elif arg == '--force':
219 force = True
digit@chromium.org3596d582013-12-13 17:07:33 +0000220 else:
221 usage('Invalid option %s.' % arg)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000222
agable@chromium.orgcc023502013-04-03 20:24:21 +0000223 def looks_like_arg(arg):
224 return arg.startswith('--') and arg.count('=') == 1
225
226 bad_parms = [x for x in argv[2:] if not looks_like_arg(x)]
227 if bad_parms:
228 usage('Got bad arguments %s' % bad_parms)
229
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000230 config = argv[1]
agable@chromium.orgcc023502013-04-03 20:24:21 +0000231 props = argv[2:]
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000232 return (
iannucci@chromium.org78faf8b2016-05-09 23:26:37 +0000233 optparse.Values({
234 'dry_run': dry_run,
235 'nohooks': nohooks,
236 'no_history': no_history,
237 'force': force}),
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000238 config,
primiano@chromium.org5439ea52014-08-06 17:18:18 +0000239 props)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000240
241
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000242def run_config_fetch(config, props, aliased=False):
243 """Invoke a config's fetch method with the passed-through args
agable@chromium.orgcc023502013-04-03 20:24:21 +0000244 and return its json output as a python object."""
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000245 config_path = os.path.abspath(
246 os.path.join(SCRIPT_PATH, 'fetch_configs', config))
247 if not os.path.exists(config_path + '.py'):
248 print "Could not find a config for %s" % config
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000249 sys.exit(1)
250
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000251 cmd = [sys.executable, config_path + '.py', 'fetch'] + props
agable@chromium.orgcc023502013-04-03 20:24:21 +0000252 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000253
agable@chromium.orgcc023502013-04-03 20:24:21 +0000254 spec = json.loads(result)
255 if 'alias' in spec:
256 assert not aliased
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000257 return run_config_fetch(
258 spec['alias']['config'], spec['alias']['props'] + props, aliased=True)
259 cmd = [sys.executable, config_path + '.py', 'root']
agable@chromium.orgcc023502013-04-03 20:24:21 +0000260 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
261 root = json.loads(result)
262 return spec, root
263
264
digit@chromium.org3596d582013-12-13 17:07:33 +0000265def run(options, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000266 """Perform a checkout with the given type and configuration.
267
268 Args:
digit@chromium.org3596d582013-12-13 17:07:33 +0000269 options: Options instance.
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000270 spec: Checkout configuration returned by the the config's fetch_spec
agable@chromium.orgcc023502013-04-03 20:24:21 +0000271 method (checkout type, repository url, etc.).
272 root: The directory into which the repo expects to be checkout out.
273 """
274 assert 'type' in spec
275 checkout_type = spec['type']
276 checkout_spec = spec['%s_spec' % checkout_type]
277 try:
digit@chromium.org3596d582013-12-13 17:07:33 +0000278 checkout = CheckoutFactory(checkout_type, options, checkout_spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000279 except KeyError:
280 return 1
iannucci@chromium.org78faf8b2016-05-09 23:26:37 +0000281 if not options.force and checkout.exists():
mmoss@chromium.org5a447762015-06-10 20:01:39 +0000282 print 'Your current directory appears to already contain, or be part of, '
283 print 'a checkout. "fetch" is used only to get new checkouts. Use '
284 print '"gclient sync" to update existing checkouts.'
dpranke@chromium.orgfd79e0d2013-04-12 21:34:32 +0000285 print
286 print 'Fetch also does not yet deal with partial checkouts, so if fetch'
287 print 'failed, delete the checkout and start over (crbug.com/230691).'
agable@chromium.orgcc023502013-04-03 20:24:21 +0000288 return 1
agable@chromium.org2560ea72013-04-04 01:22:38 +0000289 return checkout.init()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000290
291
292def main():
luqui@chromium.orgb371a1c2015-12-04 01:42:48 +0000293 options, config, props = handle_args(sys.argv)
294 spec, root = run_config_fetch(config, props)
digit@chromium.org3596d582013-12-13 17:07:33 +0000295 return run(options, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000296
297
298if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000299 try:
300 sys.exit(main())
301 except KeyboardInterrupt:
302 sys.stderr.write('interrupted\n')
303 sys.exit(1)