blob: 8316ed48e7a85e938e800f2b5ac5a7f1c3011ed3 [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.orga992edb2013-04-03 21:22:20 +0000163 dryrun = False
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000164 if argv[1] in ('-n', '--dry-run'):
165 dryrun = True
166 argv.pop(1)
167
agable@chromium.orgcc023502013-04-03 20:24:21 +0000168 def looks_like_arg(arg):
169 return arg.startswith('--') and arg.count('=') == 1
170
171 bad_parms = [x for x in argv[2:] if not looks_like_arg(x)]
172 if bad_parms:
173 usage('Got bad arguments %s' % bad_parms)
174
175 recipe = argv[1]
176 props = argv[2:]
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000177 return dryrun, recipe, props
agable@chromium.orgcc023502013-04-03 20:24:21 +0000178
179
180def run_recipe_fetch(recipe, props, aliased=False):
181 """Invoke a recipe's fetch method with the passed-through args
182 and return its json output as a python object."""
183 recipe_path = os.path.abspath(os.path.join(SCRIPT_PATH, 'recipes', recipe))
dpranke@chromium.orga992edb2013-04-03 21:22:20 +0000184 if not os.path.exists(recipe_path + '.py'):
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000185 print "Could not find a recipe for %s" % recipe
186 sys.exit(1)
187
agable@chromium.orgcc023502013-04-03 20:24:21 +0000188 cmd = [sys.executable, recipe_path + '.py', 'fetch'] + props
189 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
dpranke@chromium.org2bf328a2013-04-03 21:14:41 +0000190
agable@chromium.orgcc023502013-04-03 20:24:21 +0000191 spec = json.loads(result)
192 if 'alias' in spec:
193 assert not aliased
194 return run_recipe_fetch(
195 spec['alias']['recipe'], spec['alias']['props'] + props, aliased=True)
196 cmd = [sys.executable, recipe_path + '.py', 'root']
197 result = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
198 root = json.loads(result)
199 return spec, root
200
201
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000202def run(dryrun, spec, root):
agable@chromium.orgcc023502013-04-03 20:24:21 +0000203 """Perform a checkout with the given type and configuration.
204
205 Args:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000206 dryrun: if True, don't actually execute the commands
agable@chromium.orgcc023502013-04-03 20:24:21 +0000207 spec: Checkout configuration returned by the the recipe's fetch_spec
208 method (checkout type, repository url, etc.).
209 root: The directory into which the repo expects to be checkout out.
210 """
211 assert 'type' in spec
212 checkout_type = spec['type']
213 checkout_spec = spec['%s_spec' % checkout_type]
214 try:
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000215 checkout = CheckoutFactory(checkout_type, dryrun, checkout_spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000216 except KeyError:
217 return 1
218 if checkout.exists():
219 print 'You appear to already have this checkout.'
220 print 'Aborting to avoid clobbering your work.'
221 return 1
222 checkout.init()
223 return 0
224
225
226def main():
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000227 dryrun, recipe, props = handle_args(sys.argv)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000228 spec, root = run_recipe_fetch(recipe, props)
dpranke@chromium.orgd88d7f52013-04-03 21:09:07 +0000229 return run(dryrun, spec, root)
agable@chromium.orgcc023502013-04-03 20:24:21 +0000230
231
232if __name__ == '__main__':
233 sys.exit(main())