blob: 25f9174d8b971508a36bdc888b1790bd203608f9 [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:
65 return subprocess.check_call(('gclient',) + cmd, **kwargs)
agable@chromium.orgcc023502013-04-03 20:24:21 +000066
67
68class GitCheckout(Checkout):
69
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000070 def run_git(self, *cmd, **kwargs):
agable@chromium.orgcc023502013-04-03 20:24:21 +000071 print 'Running: git %s' % ' '.join(pipes.quote(x) for x in cmd)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000072 if not self.dryrun:
73 return subprocess.check_call(('git',) + cmd, **kwargs)
agable@chromium.orgcc023502013-04-03 20:24:21 +000074
75
76class GclientGitSvnCheckout(GclientCheckout, GitCheckout):
77
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000078 def __init__(self, dryrun, spec, root):
79 super(GclientGitSvnCheckout, self).__init__(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +000080 assert 'solutions' in self.spec
81 keys = ['solutions', 'target_os', 'target_os_only']
82 gclient_spec = '\n'.join('%s = %s' % (key, self.spec[key])
83 for key in self.spec if key in keys)
84 self.spec['gclient_spec'] = gclient_spec
85 assert 'svn_url' in self.spec
86 assert 'svn_branch' in self.spec
87 assert 'svn_ref' in self.spec
88
89 def exists(self):
90 return os.path.exists(os.path.join(os.getcwd(), self.root))
91
92 def init(self):
93 # Configure and do the gclient checkout.
94 self.run_gclient('config', '--spec', self.spec['gclient_spec'])
95 self.run_gclient('sync')
96
97 # Configure git.
98 wd = os.path.join(self.base, self.root)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +000099 if self.dryrun:
100 print "cd %s" % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000101 self.run_git(
102 'submodule', 'foreach',
103 'git config -f $toplevel/.git/config submodule.$name.ignore all',
104 cwd=wd)
105 self.run_git('config', 'diff.ignoreSubmodules', 'all', cwd=wd)
106
107 # Configure git-svn.
108 self.run_git('svn', 'init', '--prefix=origin/', '-T',
109 self.spec['svn_branch'], self.spec['svn_url'], cwd=wd)
110 self.run_git('config', 'svn-remote.svn.fetch', self.spec['svn_branch'] +
111 ':refs/remotes/origin/' + self.spec['svn_ref'], cwd=wd)
112 self.run_git('svn', 'fetch', cwd=wd)
113
114 # Configure git-svn submodules, if any.
115 submodules = json.loads(self.spec.get('submodule_git_svn_spec', '{}'))
116 for path, subspec in submodules.iteritems():
117 subspec = submodules[path]
118 ospath = os.path.join(*path.split('/'))
119 wd = os.path.join(self.base, self.root, ospath)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +0000120 if self.dryrun:
121 print "cd %s" % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000122 self.run_git('svn', 'init', '--prefix=origin/', '-T',
123 subspec['svn_branch'], subspec['svn_url'], cwd=wd)
124 self.run_git('config', '--replace', 'svn-remote.svn.fetch',
125 subspec['svn_branch'] + ':refs/remotes/origin/' +
126 subspec['svn_ref'], cwd=wd)
127 self.run_git('svn', 'fetch', cwd=wd)
128
129
130CHECKOUT_TYPE_MAP = {
131 'gclient': GclientCheckout,
132 'gclient_git_svn': GclientGitSvnCheckout,
133 'git': GitCheckout,
134}
135
136
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000137def CheckoutFactory(type_name, dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000138 """Factory to build Checkout class instances."""
139 class_ = CHECKOUT_TYPE_MAP.get(type_name)
140 if not class_:
141 raise KeyError('unrecognized checkout type: %s' % type_name)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000142 return class_(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000143
144
145#################################################
146# Utility function and file entry point.
147#################################################
148def usage(msg=None):
149 """Print help and exit."""
150 if msg:
151 print 'Error:', msg
152
153 print (
154"""
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000155usage: %s [-n|--dry-run] <recipe> [--property=value [--property2=value2 ...]]
agable@chromium.orgcc023502013-04-03 20:24:21 +0000156""" % os.path.basename(sys.argv[0]))
157 sys.exit(bool(msg))
158
159
160def handle_args(argv):
161 """Gets the recipe name from the command line arguments."""
162 if len(argv) <= 1:
163 usage('Must specify a recipe.')
dpranke@chromium.orge3d147d2013-04-03 20:31:27 +0000164 if argv[1] in ('-h', '--help', 'help'):
165 usage()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000166
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000167 dryrun = False
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000168 if argv[1] in ('-n', '--dry-run'):
169 dryrun = True
170 argv.pop(1)
171
agable@chromium.orgcc023502013-04-03 20:24:21 +0000172 def looks_like_arg(arg):
173 return arg.startswith('--') and arg.count('=') == 1
174
175 bad_parms = [x for x in argv[2:] if not looks_like_arg(x)]
176 if bad_parms:
177 usage('Got bad arguments %s' % bad_parms)
178
179 recipe = argv[1]
180 props = argv[2:]
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000181 return dryrun, recipe, props
agable@chromium.orgcc023502013-04-03 20:24:21 +0000182
183
184def run_recipe_fetch(recipe, props, aliased=False):
185 """Invoke a recipe's fetch method with the passed-through args
186 and return its json output as a python object."""
187 recipe_path = os.path.abspath(os.path.join(SCRIPT_PATH, 'recipes', recipe))
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000188 if not os.path.exists(recipe_path + '.py'):
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000189 print "Could not find a recipe for %s" % recipe
190 sys.exit(1)
191
agable@chromium.orgcc023502013-04-03 20:24:21 +0000192 cmd = [sys.executable, recipe_path + '.py', 'fetch'] + props
193 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000194
agable@chromium.orgcc023502013-04-03 20:24:21 +0000195 spec = json.loads(result)
196 if 'alias' in spec:
197 assert not aliased
198 return run_recipe_fetch(
199 spec['alias']['recipe'], spec['alias']['props'] + props, aliased=True)
200 cmd = [sys.executable, recipe_path + '.py', 'root']
201 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
202 root = json.loads(result)
203 return spec, root
204
205
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000206def run(dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000207 """Perform a checkout with the given type and configuration.
208
209 Args:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000210 dryrun: if True, don't actually execute the commands
agable@chromium.orgcc023502013-04-03 20:24:21 +0000211 spec: Checkout configuration returned by the the recipe's fetch_spec
212 method (checkout type, repository url, etc.).
213 root: The directory into which the repo expects to be checkout out.
214 """
215 assert 'type' in spec
216 checkout_type = spec['type']
217 checkout_spec = spec['%s_spec' % checkout_type]
218 try:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000219 checkout = CheckoutFactory(checkout_type, dryrun, checkout_spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000220 except KeyError:
221 return 1
222 if checkout.exists():
223 print 'You appear to already have this checkout.'
224 print 'Aborting to avoid clobbering your work.'
225 return 1
226 checkout.init()
227 return 0
228
229
230def main():
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000231 dryrun, recipe, props = handle_args(sys.argv)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000232 spec, root = run_recipe_fetch(recipe, props)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000233 return run(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000234
235
236if __name__ == '__main__':
237 sys.exit(main())