blob: 71e62190d62889ee7f70845b8594342f140e8a7f [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:
10 fetch <recipe> [--property=value [--property2=value2 ...]]
11
12This script is a wrapper around various version control and repository
13checkout commands. It requires a |recipe| name, fetches data from that
14recipe in depot_tools/recipes, and then performs all necessary inits,
15checkouts, pulls, fetches, etc.
16
17Optional arguments may be passed on the command line in key-value pairs.
18These parameters will be passed through to the recipe's main method.
19"""
20
21import json
22import os
23import subprocess
24import sys
25import pipes
26
27
28SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
29
30
31#################################################
32# Checkout class definitions.
33#################################################
34class Checkout(object):
35 """Base class for implementing different types of checkouts.
36
37 Attributes:
38 |base|: the absolute path of the directory in which this script is run.
39 |spec|: the spec for this checkout as returned by the recipe. Different
40 subclasses will expect different keys in this dictionary.
41 |root|: the directory into which the checkout will be performed, as returned
42 by the recipe. This is a relative path from |base|.
43 """
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000044 def __init__(self, dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +000045 self.base = os.getcwd()
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000046 self.dryrun = dryrun
agable@chromium.orgcc023502013-04-03 20:24:21 +000047 self.spec = spec
48 self.root = root
49
50 def exists(self):
51 pass
52
53 def init(self):
54 pass
55
56 def sync(self):
57 pass
58
59
60class GclientCheckout(Checkout):
61
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000062 def run_gclient(self, *cmd, **kwargs):
agable@chromium.orgcc023502013-04-03 20:24:21 +000063 print 'Running: gclient %s' % ' '.join(pipes.quote(x) for x in cmd)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000064 if not self.dryrun:
dpranke@chromium.org6b8c91a2013-04-03 22:05:06 +000065 return subprocess.check_call(
66 (sys.executable, os.path.join(SCRIPT_PATH, 'gclient.py')) + cmd,
67 **kwargs)
agable@chromium.orgcc023502013-04-03 20:24:21 +000068
69
70class GitCheckout(Checkout):
71
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000072 def run_git(self, *cmd, **kwargs):
agable@chromium.orgcc023502013-04-03 20:24:21 +000073 print 'Running: git %s' % ' '.join(pipes.quote(x) for x in cmd)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000074 if not self.dryrun:
75 return subprocess.check_call(('git',) + cmd, **kwargs)
agable@chromium.orgcc023502013-04-03 20:24:21 +000076
77
agable@chromium.org2560ea72013-04-04 01:22:38 +000078class SvnCheckout(Checkout):
79
80 def run_svn(self, *cmd, **kwargs):
81 print 'Running: svn %s' % ' '.join(pipes.quote(x) for x in cmd)
82 if not self.dryrun:
83 return subprocess.check_call(('svn',) + cmd, **kwargs)
84
85
86class GclientGitSvnCheckout(GclientCheckout, GitCheckout, SvnCheckout):
agable@chromium.orgcc023502013-04-03 20:24:21 +000087
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000088 def __init__(self, dryrun, spec, root):
89 super(GclientGitSvnCheckout, self).__init__(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +000090 assert 'solutions' in self.spec
91 keys = ['solutions', 'target_os', 'target_os_only']
92 gclient_spec = '\n'.join('%s = %s' % (key, self.spec[key])
93 for key in self.spec if key in keys)
94 self.spec['gclient_spec'] = gclient_spec
95 assert 'svn_url' in self.spec
96 assert 'svn_branch' in self.spec
97 assert 'svn_ref' in self.spec
98
99 def exists(self):
100 return os.path.exists(os.path.join(os.getcwd(), self.root))
101
102 def init(self):
agable@chromium.org2560ea72013-04-04 01:22:38 +0000103 # Ensure we are authenticated with subversion for all submodules.
104 git_svn_dirs = json.loads(self.spec.get('submodule_git_svn_spec', '{}'))
105 git_svn_dirs.update({self.root: self.spec})
106 for _, svn_spec in git_svn_dirs.iteritems():
107 try:
108 self.run_svn('ls', '--non-interactive', svn_spec['svn_url'])
109 except subprocess.CalledProcessError:
110 print 'Please run `svn ls %s`' % svn_spec['svn_url']
111 return 1
112
agable@chromium.orgcc023502013-04-03 20:24:21 +0000113 # Configure and do the gclient checkout.
114 self.run_gclient('config', '--spec', self.spec['gclient_spec'])
115 self.run_gclient('sync')
116
117 # Configure git.
118 wd = os.path.join(self.base, self.root)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +0000119 if self.dryrun:
agable@chromium.org2560ea72013-04-04 01:22:38 +0000120 print 'cd %s' % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000121 self.run_git(
122 'submodule', 'foreach',
123 'git config -f $toplevel/.git/config submodule.$name.ignore all',
124 cwd=wd)
125 self.run_git('config', 'diff.ignoreSubmodules', 'all', cwd=wd)
126
127 # Configure git-svn.
agable@chromium.org2560ea72013-04-04 01:22:38 +0000128 for path, svn_spec in git_svn_dirs.iteritems():
129 real_path = os.path.join(*path.split('/'))
130 if real_path != self.root:
131 real_path = os.path.join(self.root, real_path)
132 wd = os.path.join(self.base, real_path)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +0000133 if self.dryrun:
agable@chromium.org2560ea72013-04-04 01:22:38 +0000134 print 'cd %s' % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000135 self.run_git('svn', 'init', '--prefix=origin/', '-T',
agable@chromium.org2560ea72013-04-04 01:22:38 +0000136 svn_spec['svn_branch'], svn_spec['svn_url'], cwd=wd)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000137 self.run_git('config', '--replace', 'svn-remote.svn.fetch',
agable@chromium.org2560ea72013-04-04 01:22:38 +0000138 svn_spec['svn_branch'] + ':refs/remotes/origin/' +
139 svn_spec['svn_ref'], cwd=wd)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000140 self.run_git('svn', 'fetch', cwd=wd)
141
142
agable@chromium.org2560ea72013-04-04 01:22:38 +0000143
agable@chromium.orgcc023502013-04-03 20:24:21 +0000144CHECKOUT_TYPE_MAP = {
145 'gclient': GclientCheckout,
146 'gclient_git_svn': GclientGitSvnCheckout,
147 'git': GitCheckout,
148}
149
150
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000151def CheckoutFactory(type_name, dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000152 """Factory to build Checkout class instances."""
153 class_ = CHECKOUT_TYPE_MAP.get(type_name)
154 if not class_:
155 raise KeyError('unrecognized checkout type: %s' % type_name)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000156 return class_(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000157
158
159#################################################
160# Utility function and file entry point.
161#################################################
162def usage(msg=None):
163 """Print help and exit."""
164 if msg:
165 print 'Error:', msg
166
167 print (
168"""
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000169usage: %s [-n|--dry-run] <recipe> [--property=value [--property2=value2 ...]]
agable@chromium.orgcc023502013-04-03 20:24:21 +0000170""" % os.path.basename(sys.argv[0]))
171 sys.exit(bool(msg))
172
173
174def handle_args(argv):
175 """Gets the recipe name from the command line arguments."""
176 if len(argv) <= 1:
177 usage('Must specify a recipe.')
dpranke@chromium.orge3d147d2013-04-03 20:31:27 +0000178 if argv[1] in ('-h', '--help', 'help'):
179 usage()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000180
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000181 dryrun = False
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000182 if argv[1] in ('-n', '--dry-run'):
183 dryrun = True
184 argv.pop(1)
185
agable@chromium.orgcc023502013-04-03 20:24:21 +0000186 def looks_like_arg(arg):
187 return arg.startswith('--') and arg.count('=') == 1
188
189 bad_parms = [x for x in argv[2:] if not looks_like_arg(x)]
190 if bad_parms:
191 usage('Got bad arguments %s' % bad_parms)
192
193 recipe = argv[1]
194 props = argv[2:]
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000195 return dryrun, recipe, props
agable@chromium.orgcc023502013-04-03 20:24:21 +0000196
197
198def run_recipe_fetch(recipe, props, aliased=False):
199 """Invoke a recipe's fetch method with the passed-through args
200 and return its json output as a python object."""
201 recipe_path = os.path.abspath(os.path.join(SCRIPT_PATH, 'recipes', recipe))
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000202 if not os.path.exists(recipe_path + '.py'):
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000203 print "Could not find a recipe for %s" % recipe
204 sys.exit(1)
205
agable@chromium.orgcc023502013-04-03 20:24:21 +0000206 cmd = [sys.executable, recipe_path + '.py', 'fetch'] + props
207 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000208
agable@chromium.orgcc023502013-04-03 20:24:21 +0000209 spec = json.loads(result)
210 if 'alias' in spec:
211 assert not aliased
212 return run_recipe_fetch(
213 spec['alias']['recipe'], spec['alias']['props'] + props, aliased=True)
214 cmd = [sys.executable, recipe_path + '.py', 'root']
215 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
216 root = json.loads(result)
217 return spec, root
218
219
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000220def run(dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000221 """Perform a checkout with the given type and configuration.
222
223 Args:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000224 dryrun: if True, don't actually execute the commands
agable@chromium.orgcc023502013-04-03 20:24:21 +0000225 spec: Checkout configuration returned by the the recipe's fetch_spec
226 method (checkout type, repository url, etc.).
227 root: The directory into which the repo expects to be checkout out.
228 """
229 assert 'type' in spec
230 checkout_type = spec['type']
231 checkout_spec = spec['%s_spec' % checkout_type]
232 try:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000233 checkout = CheckoutFactory(checkout_type, dryrun, checkout_spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000234 except KeyError:
235 return 1
236 if checkout.exists():
237 print 'You appear to already have this checkout.'
238 print 'Aborting to avoid clobbering your work.'
239 return 1
agable@chromium.org2560ea72013-04-04 01:22:38 +0000240 return checkout.init()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000241
242
243def main():
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000244 dryrun, recipe, props = handle_args(sys.argv)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000245 spec, root = run_recipe_fetch(recipe, props)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000246 return run(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000247
248
249if __name__ == '__main__':
250 sys.exit(main())