blob: 80dcce9a2f13a0e7aeefaf8871298a7737154af3 [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
dpranke@chromium.org8623da32013-04-04 17:36:01 +0000113 # TODO(dpranke): Work around issues w/ delta compression on big repos.
114 self.run_git('config', '--global', 'core.deltaBaseCacheLimit', '1G')
115
agable@chromium.orgcc023502013-04-03 20:24:21 +0000116 # Configure and do the gclient checkout.
117 self.run_gclient('config', '--spec', self.spec['gclient_spec'])
118 self.run_gclient('sync')
119
120 # Configure git.
121 wd = os.path.join(self.base, self.root)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +0000122 if self.dryrun:
agable@chromium.org2560ea72013-04-04 01:22:38 +0000123 print 'cd %s' % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000124 self.run_git(
125 'submodule', 'foreach',
126 'git config -f $toplevel/.git/config submodule.$name.ignore all',
127 cwd=wd)
128 self.run_git('config', 'diff.ignoreSubmodules', 'all', cwd=wd)
129
130 # Configure git-svn.
agable@chromium.org2560ea72013-04-04 01:22:38 +0000131 for path, svn_spec in git_svn_dirs.iteritems():
132 real_path = os.path.join(*path.split('/'))
133 if real_path != self.root:
134 real_path = os.path.join(self.root, real_path)
135 wd = os.path.join(self.base, real_path)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +0000136 if self.dryrun:
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('svn', 'init', '--prefix=origin/', '-T',
agable@chromium.org2560ea72013-04-04 01:22:38 +0000139 svn_spec['svn_branch'], svn_spec['svn_url'], cwd=wd)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000140 self.run_git('config', '--replace', 'svn-remote.svn.fetch',
agable@chromium.org2560ea72013-04-04 01:22:38 +0000141 svn_spec['svn_branch'] + ':refs/remotes/origin/' +
142 svn_spec['svn_ref'], cwd=wd)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000143 self.run_git('svn', 'fetch', cwd=wd)
144
145
agable@chromium.org2560ea72013-04-04 01:22:38 +0000146
agable@chromium.orgcc023502013-04-03 20:24:21 +0000147CHECKOUT_TYPE_MAP = {
148 'gclient': GclientCheckout,
149 'gclient_git_svn': GclientGitSvnCheckout,
150 'git': GitCheckout,
151}
152
153
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000154def CheckoutFactory(type_name, dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000155 """Factory to build Checkout class instances."""
156 class_ = CHECKOUT_TYPE_MAP.get(type_name)
157 if not class_:
158 raise KeyError('unrecognized checkout type: %s' % type_name)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000159 return class_(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000160
161
162#################################################
163# Utility function and file entry point.
164#################################################
165def usage(msg=None):
166 """Print help and exit."""
167 if msg:
168 print 'Error:', msg
169
170 print (
171"""
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000172usage: %s [-n|--dry-run] <recipe> [--property=value [--property2=value2 ...]]
agable@chromium.orgcc023502013-04-03 20:24:21 +0000173""" % os.path.basename(sys.argv[0]))
174 sys.exit(bool(msg))
175
176
177def handle_args(argv):
178 """Gets the recipe name from the command line arguments."""
179 if len(argv) <= 1:
180 usage('Must specify a recipe.')
dpranke@chromium.orge3d147d2013-04-03 20:31:27 +0000181 if argv[1] in ('-h', '--help', 'help'):
182 usage()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000183
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000184 dryrun = False
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000185 if argv[1] in ('-n', '--dry-run'):
186 dryrun = True
187 argv.pop(1)
188
agable@chromium.orgcc023502013-04-03 20:24:21 +0000189 def looks_like_arg(arg):
190 return arg.startswith('--') and arg.count('=') == 1
191
192 bad_parms = [x for x in argv[2:] if not looks_like_arg(x)]
193 if bad_parms:
194 usage('Got bad arguments %s' % bad_parms)
195
196 recipe = argv[1]
197 props = argv[2:]
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000198 return dryrun, recipe, props
agable@chromium.orgcc023502013-04-03 20:24:21 +0000199
200
201def run_recipe_fetch(recipe, props, aliased=False):
202 """Invoke a recipe's fetch method with the passed-through args
203 and return its json output as a python object."""
204 recipe_path = os.path.abspath(os.path.join(SCRIPT_PATH, 'recipes', recipe))
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000205 if not os.path.exists(recipe_path + '.py'):
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000206 print "Could not find a recipe for %s" % recipe
207 sys.exit(1)
208
agable@chromium.orgcc023502013-04-03 20:24:21 +0000209 cmd = [sys.executable, recipe_path + '.py', 'fetch'] + props
210 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000211
agable@chromium.orgcc023502013-04-03 20:24:21 +0000212 spec = json.loads(result)
213 if 'alias' in spec:
214 assert not aliased
215 return run_recipe_fetch(
216 spec['alias']['recipe'], spec['alias']['props'] + props, aliased=True)
217 cmd = [sys.executable, recipe_path + '.py', 'root']
218 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
219 root = json.loads(result)
220 return spec, root
221
222
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000223def run(dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000224 """Perform a checkout with the given type and configuration.
225
226 Args:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000227 dryrun: if True, don't actually execute the commands
agable@chromium.orgcc023502013-04-03 20:24:21 +0000228 spec: Checkout configuration returned by the the recipe's fetch_spec
229 method (checkout type, repository url, etc.).
230 root: The directory into which the repo expects to be checkout out.
231 """
232 assert 'type' in spec
233 checkout_type = spec['type']
234 checkout_spec = spec['%s_spec' % checkout_type]
235 try:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000236 checkout = CheckoutFactory(checkout_type, dryrun, checkout_spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000237 except KeyError:
238 return 1
239 if checkout.exists():
240 print 'You appear to already have this checkout.'
241 print 'Aborting to avoid clobbering your work.'
242 return 1
agable@chromium.org2560ea72013-04-04 01:22:38 +0000243 return checkout.init()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000244
245
246def main():
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000247 dryrun, recipe, props = handle_args(sys.argv)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000248 spec, root = run_recipe_fetch(recipe, props)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000249 return run(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000250
251
252if __name__ == '__main__':
253 sys.exit(main())