blob: 2b89675e965dd7f38652589f69828b6eccd190eb [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)
99 self.run_git(
100 'submodule', 'foreach',
101 'git config -f $toplevel/.git/config submodule.$name.ignore all',
102 cwd=wd)
103 self.run_git('config', 'diff.ignoreSubmodules', 'all', cwd=wd)
104
105 # Configure git-svn.
106 self.run_git('svn', 'init', '--prefix=origin/', '-T',
107 self.spec['svn_branch'], self.spec['svn_url'], cwd=wd)
108 self.run_git('config', 'svn-remote.svn.fetch', self.spec['svn_branch'] +
109 ':refs/remotes/origin/' + self.spec['svn_ref'], cwd=wd)
110 self.run_git('svn', 'fetch', cwd=wd)
111
112 # Configure git-svn submodules, if any.
113 submodules = json.loads(self.spec.get('submodule_git_svn_spec', '{}'))
114 for path, subspec in submodules.iteritems():
115 subspec = submodules[path]
116 ospath = os.path.join(*path.split('/'))
117 wd = os.path.join(self.base, self.root, ospath)
118 self.run_git('svn', 'init', '--prefix=origin/', '-T',
119 subspec['svn_branch'], subspec['svn_url'], cwd=wd)
120 self.run_git('config', '--replace', 'svn-remote.svn.fetch',
121 subspec['svn_branch'] + ':refs/remotes/origin/' +
122 subspec['svn_ref'], cwd=wd)
123 self.run_git('svn', 'fetch', cwd=wd)
124
125
126CHECKOUT_TYPE_MAP = {
127 'gclient': GclientCheckout,
128 'gclient_git_svn': GclientGitSvnCheckout,
129 'git': GitCheckout,
130}
131
132
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000133def CheckoutFactory(type_name, dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000134 """Factory to build Checkout class instances."""
135 class_ = CHECKOUT_TYPE_MAP.get(type_name)
136 if not class_:
137 raise KeyError('unrecognized checkout type: %s' % type_name)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000138 return class_(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000139
140
141#################################################
142# Utility function and file entry point.
143#################################################
144def usage(msg=None):
145 """Print help and exit."""
146 if msg:
147 print 'Error:', msg
148
149 print (
150"""
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000151usage: %s [-n|--dry-run] <recipe> [--property=value [--property2=value2 ...]]
agable@chromium.orgcc023502013-04-03 20:24:21 +0000152""" % os.path.basename(sys.argv[0]))
153 sys.exit(bool(msg))
154
155
156def handle_args(argv):
157 """Gets the recipe name from the command line arguments."""
158 if len(argv) <= 1:
159 usage('Must specify a recipe.')
dpranke@chromium.orge3d147d2013-04-03 20:31:27 +0000160 if argv[1] in ('-h', '--help', 'help'):
161 usage()
agable@chromium.orgcc023502013-04-03 20:24:21 +0000162
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000163 if argv[1] in ('-n', '--dry-run'):
164 dryrun = True
165 argv.pop(1)
166
agable@chromium.orgcc023502013-04-03 20:24:21 +0000167 def looks_like_arg(arg):
168 return arg.startswith('--') and arg.count('=') == 1
169
170 bad_parms = [x for x in argv[2:] if not looks_like_arg(x)]
171 if bad_parms:
172 usage('Got bad arguments %s' % bad_parms)
173
174 recipe = argv[1]
175 props = argv[2:]
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000176 return dryrun, recipe, props
agable@chromium.orgcc023502013-04-03 20:24:21 +0000177
178
179def run_recipe_fetch(recipe, props, aliased=False):
180 """Invoke a recipe's fetch method with the passed-through args
181 and return its json output as a python object."""
182 recipe_path = os.path.abspath(os.path.join(SCRIPT_PATH, 'recipes', recipe))
183 cmd = [sys.executable, recipe_path + '.py', 'fetch'] + props
184 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
185 spec = json.loads(result)
186 if 'alias' in spec:
187 assert not aliased
188 return run_recipe_fetch(
189 spec['alias']['recipe'], spec['alias']['props'] + props, aliased=True)
190 cmd = [sys.executable, recipe_path + '.py', 'root']
191 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
192 root = json.loads(result)
193 return spec, root
194
195
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000196def run(dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000197 """Perform a checkout with the given type and configuration.
198
199 Args:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000200 dryrun: if True, don't actually execute the commands
agable@chromium.orgcc023502013-04-03 20:24:21 +0000201 spec: Checkout configuration returned by the the recipe's fetch_spec
202 method (checkout type, repository url, etc.).
203 root: The directory into which the repo expects to be checkout out.
204 """
205 assert 'type' in spec
206 checkout_type = spec['type']
207 checkout_spec = spec['%s_spec' % checkout_type]
208 try:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000209 checkout = CheckoutFactory(checkout_type, dryrun, checkout_spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000210 except KeyError:
211 return 1
212 if checkout.exists():
213 print 'You appear to already have this checkout.'
214 print 'Aborting to avoid clobbering your work.'
215 return 1
216 checkout.init()
217 return 0
218
219
220def main():
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000221 dryrun, recipe, props = handle_args(sys.argv)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000222 spec, root = run_recipe_fetch(recipe, props)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000223 return run(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000224
225
226if __name__ == '__main__':
227 sys.exit(main())