blob: 249b50bde1923a0972a22ca7fd0b2b6025cb80e6 [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
78class GclientGitSvnCheckout(GclientCheckout, GitCheckout):
79
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +000080 def __init__(self, dryrun, spec, root):
81 super(GclientGitSvnCheckout, self).__init__(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +000082 assert 'solutions' in self.spec
83 keys = ['solutions', 'target_os', 'target_os_only']
84 gclient_spec = '\n'.join('%s = %s' % (key, self.spec[key])
85 for key in self.spec if key in keys)
86 self.spec['gclient_spec'] = gclient_spec
87 assert 'svn_url' in self.spec
88 assert 'svn_branch' in self.spec
89 assert 'svn_ref' in self.spec
90
91 def exists(self):
92 return os.path.exists(os.path.join(os.getcwd(), self.root))
93
94 def init(self):
95 # Configure and do the gclient checkout.
96 self.run_gclient('config', '--spec', self.spec['gclient_spec'])
97 self.run_gclient('sync')
98
99 # Configure git.
100 wd = os.path.join(self.base, self.root)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +0000101 if self.dryrun:
102 print "cd %s" % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000103 self.run_git(
104 'submodule', 'foreach',
105 'git config -f $toplevel/.git/config submodule.$name.ignore all',
106 cwd=wd)
107 self.run_git('config', 'diff.ignoreSubmodules', 'all', cwd=wd)
108
109 # Configure git-svn.
110 self.run_git('svn', 'init', '--prefix=origin/', '-T',
111 self.spec['svn_branch'], self.spec['svn_url'], cwd=wd)
112 self.run_git('config', 'svn-remote.svn.fetch', self.spec['svn_branch'] +
113 ':refs/remotes/origin/' + self.spec['svn_ref'], cwd=wd)
114 self.run_git('svn', 'fetch', cwd=wd)
115
116 # Configure git-svn submodules, if any.
117 submodules = json.loads(self.spec.get('submodule_git_svn_spec', '{}'))
118 for path, subspec in submodules.iteritems():
119 subspec = submodules[path]
120 ospath = os.path.join(*path.split('/'))
121 wd = os.path.join(self.base, self.root, ospath)
dpranke@chromium.org7ca51b32013-04-03 21:29:50 +0000122 if self.dryrun:
123 print "cd %s" % wd
agable@chromium.orgcc023502013-04-03 20:24:21 +0000124 self.run_git('svn', 'init', '--prefix=origin/', '-T',
125 subspec['svn_branch'], subspec['svn_url'], cwd=wd)
126 self.run_git('config', '--replace', 'svn-remote.svn.fetch',
127 subspec['svn_branch'] + ':refs/remotes/origin/' +
128 subspec['svn_ref'], cwd=wd)
129 self.run_git('svn', 'fetch', cwd=wd)
130
131
132CHECKOUT_TYPE_MAP = {
133 'gclient': GclientCheckout,
134 'gclient_git_svn': GclientGitSvnCheckout,
135 'git': GitCheckout,
136}
137
138
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000139def CheckoutFactory(type_name, dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000140 """Factory to build Checkout class instances."""
141 class_ = CHECKOUT_TYPE_MAP.get(type_name)
142 if not class_:
143 raise KeyError('unrecognized checkout type: %s' % type_name)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000144 return class_(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000145
146
147#################################################
148# Utility function and file entry point.
149#################################################
150def usage(msg=None):
151 """Print help and exit."""
152 if msg:
153 print 'Error:', msg
154
155 print (
156"""
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000157usage: %s [-n|--dry-run] <recipe> [--property=value [--property2=value2 ...]]
agable@chromium.orgcc023502013-04-03 20:24:21 +0000158""" % os.path.basename(sys.argv[0]))
159 sys.exit(bool(msg))
160
161
162def handle_args(argv):
163 """Gets the recipe name from the command line arguments."""
164 if len(argv) <= 1:
165 usage('Must specify a recipe.')
dpranke@chromium.orge3d147d2013-04-03 20:31:27 +0000166 if argv[1] in ('-h', '--help', 'help'):
167 usage()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000168
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000169 dryrun = False
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000170 if argv[1] in ('-n', '--dry-run'):
171 dryrun = True
172 argv.pop(1)
173
agable@chromium.orgcc023502013-04-03 20:24:21 +0000174 def looks_like_arg(arg):
175 return arg.startswith('--') and arg.count('=') == 1
176
177 bad_parms = [x for x in argv[2:] if not looks_like_arg(x)]
178 if bad_parms:
179 usage('Got bad arguments %s' % bad_parms)
180
181 recipe = argv[1]
182 props = argv[2:]
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000183 return dryrun, recipe, props
agable@chromium.orgcc023502013-04-03 20:24:21 +0000184
185
186def run_recipe_fetch(recipe, props, aliased=False):
187 """Invoke a recipe's fetch method with the passed-through args
188 and return its json output as a python object."""
189 recipe_path = os.path.abspath(os.path.join(SCRIPT_PATH, 'recipes', recipe))
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000190 if not os.path.exists(recipe_path + '.py'):
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000191 print "Could not find a recipe for %s" % recipe
192 sys.exit(1)
193
agable@chromium.orgcc023502013-04-03 20:24:21 +0000194 cmd = [sys.executable, recipe_path + '.py', 'fetch'] + props
195 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000196
agable@chromium.orgcc023502013-04-03 20:24:21 +0000197 spec = json.loads(result)
198 if 'alias' in spec:
199 assert not aliased
200 return run_recipe_fetch(
201 spec['alias']['recipe'], spec['alias']['props'] + props, aliased=True)
202 cmd = [sys.executable, recipe_path + '.py', 'root']
203 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
204 root = json.loads(result)
205 return spec, root
206
207
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000208def run(dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000209 """Perform a checkout with the given type and configuration.
210
211 Args:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000212 dryrun: if True, don't actually execute the commands
agable@chromium.orgcc023502013-04-03 20:24:21 +0000213 spec: Checkout configuration returned by the the recipe's fetch_spec
214 method (checkout type, repository url, etc.).
215 root: The directory into which the repo expects to be checkout out.
216 """
217 assert 'type' in spec
218 checkout_type = spec['type']
219 checkout_spec = spec['%s_spec' % checkout_type]
220 try:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000221 checkout = CheckoutFactory(checkout_type, dryrun, checkout_spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000222 except KeyError:
223 return 1
224 if checkout.exists():
225 print 'You appear to already have this checkout.'
226 print 'Aborting to avoid clobbering your work.'
227 return 1
228 checkout.init()
229 return 0
230
231
232def main():
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000233 dryrun, recipe, props = handle_args(sys.argv)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000234 spec, root = run_recipe_fetch(recipe, props)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000235 return run(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000236
237
238if __name__ == '__main__':
239 sys.exit(main())