blob: ae50ee0cfcafd1f777418a2b24f138d44625141d [file] [log] [blame]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +02001# Copyright 2017 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import ast
Edward Lesmes6f64a052018-03-20 17:35:49 -04006import cStringIO
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +02007import collections
Edward Lemur16f4bad2018-05-16 16:53:49 -04008import logging
Edward Lesmes6f64a052018-03-20 17:35:49 -04009import tokenize
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +020010
Edward Lemur16f4bad2018-05-16 16:53:49 -040011import gclient_utils
12
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020013from third_party import schema
14
15
Edward Lesmes6f64a052018-03-20 17:35:49 -040016class _NodeDict(collections.MutableMapping):
17 """Dict-like type that also stores information on AST nodes and tokens."""
18 def __init__(self, data, tokens=None):
19 self.data = collections.OrderedDict(data)
20 self.tokens = tokens
21
22 def __str__(self):
23 return str({k: v[0] for k, v in self.data.iteritems()})
24
25 def __getitem__(self, key):
26 return self.data[key][0]
27
28 def __setitem__(self, key, value):
29 self.data[key] = (value, None)
30
31 def __delitem__(self, key):
32 del self.data[key]
33
34 def __iter__(self):
35 return iter(self.data)
36
37 def __len__(self):
38 return len(self.data)
39
Edward Lesmes3d993812018-04-02 12:52:49 -040040 def MoveTokens(self, origin, delta):
41 if self.tokens:
42 new_tokens = {}
43 for pos, token in self.tokens.iteritems():
44 if pos[0] >= origin:
45 pos = (pos[0] + delta, pos[1])
46 token = token[:2] + (pos,) + token[3:]
47 new_tokens[pos] = token
48
49 for value, node in self.data.values():
50 if node.lineno >= origin:
51 node.lineno += delta
52 if isinstance(value, _NodeDict):
53 value.MoveTokens(origin, delta)
54
Edward Lesmes6f64a052018-03-20 17:35:49 -040055 def GetNode(self, key):
56 return self.data[key][1]
57
Edward Lesmes6c24d372018-03-28 12:52:29 -040058 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040059 self.data[key] = (value, node)
60
61
62def _NodeDictSchema(dict_schema):
63 """Validate dict_schema after converting _NodeDict to a regular dict."""
64 def validate(d):
65 schema.Schema(dict_schema).validate(dict(d))
66 return True
67 return validate
68
69
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020070# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -040071_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020072 schema.Optional(basestring): schema.Or(
73 None,
74 basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040075 _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020076 # Repo and revision to check out under the path
77 # (same as if no dict was used).
Michael Moss012013e2018-03-30 17:03:19 -070078 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020079
80 # Optional condition string. The dep will only be processed
81 # if the condition evaluates to True.
82 schema.Optional('condition'): basestring,
John Budorick0f7b2002018-01-19 15:46:17 -080083
84 schema.Optional('dep_type', default='git'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040085 }),
John Budorick0f7b2002018-01-19 15:46:17 -080086 # CIPD package.
Edward Lesmes6f64a052018-03-20 17:35:49 -040087 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080088 'packages': [
Edward Lesmes6f64a052018-03-20 17:35:49 -040089 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080090 'package': basestring,
91
92 'version': basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040093 })
John Budorick0f7b2002018-01-19 15:46:17 -080094 ],
95
96 schema.Optional('condition'): basestring,
97
98 schema.Optional('dep_type', default='cipd'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040099 }),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200100 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400101})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200102
Edward Lesmes6f64a052018-03-20 17:35:49 -0400103_GCLIENT_HOOKS_SCHEMA = [_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200104 # Hook action: list of command-line arguments to invoke.
105 'action': [basestring],
106
107 # Name of the hook. Doesn't affect operation.
108 schema.Optional('name'): basestring,
109
110 # Hook pattern (regex). Originally intended to limit some hooks to run
111 # only when files matching the pattern have changed. In practice, with git,
112 # gclient runs all the hooks regardless of this field.
113 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200114
115 # Working directory where to execute the hook.
116 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200117
118 # Optional condition string. The hook will only be run
119 # if the condition evaluates to True.
120 schema.Optional('condition'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400121})]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200122
Edward Lesmes6f64a052018-03-20 17:35:49 -0400123_GCLIENT_SCHEMA = schema.Schema(_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200124 # List of host names from which dependencies are allowed (whitelist).
125 # NOTE: when not present, all hosts are allowed.
126 # NOTE: scoped to current DEPS file, not recursive.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200127 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200128
129 # Mapping from paths to repo and revision to check out under that path.
130 # Applying this mapping to the on-disk checkout is the main purpose
131 # of gclient, and also why the config file is called DEPS.
132 #
133 # The following functions are allowed:
134 #
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200135 # Var(): allows variable substitution (either from 'vars' dict below,
136 # or command-line override)
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200137 schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200138
139 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200140 # Also see 'target_os'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400141 schema.Optional('deps_os'): _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200142 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400143 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200144
Michael Moss848c86e2018-05-03 16:05:50 -0700145 # Dependency to get gclient_gn_args* settings from. This allows these values
146 # to be set in a recursedeps file, rather than requiring that they exist in
147 # the top-level solution.
148 schema.Optional('gclient_gn_args_from'): basestring,
149
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200150 # Path to GN args file to write selected variables.
151 schema.Optional('gclient_gn_args_file'): basestring,
152
153 # Subset of variables to write to the GN args file (see above).
154 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
155
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200156 # Hooks executed after gclient sync (unless suppressed), or explicitly
157 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
158 # Also see 'pre_deps_hooks'.
159 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
160
Scott Grahamc4826742017-05-11 16:59:23 -0700161 # Similar to 'hooks', also keyed by OS.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400162 schema.Optional('hooks_os'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200163 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
Edward Lesmes6f64a052018-03-20 17:35:49 -0400164 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700165
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200166 # Rules which #includes are allowed in the directory.
167 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200168 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200169
170 # Hooks executed before processing DEPS. See 'hooks' for more details.
171 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
172
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200173 # Recursion limit for nested DEPS.
174 schema.Optional('recursion'): int,
175
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200176 # Whitelists deps for which recursion should be enabled.
177 schema.Optional('recursedeps'): [
Paweł Hajdan, Jr05fec032017-05-30 23:04:23 +0200178 schema.Optional(schema.Or(
179 basestring,
180 (basestring, basestring),
181 [basestring, basestring]
182 )),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200183 ],
184
185 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200186 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200187
188 # Mapping from paths to include rules specific for that path.
189 # See 'include_rules' for more details.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400190 schema.Optional('specific_include_rules'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200191 schema.Optional(basestring): [basestring]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400192 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200193
194 # List of additional OS names to consider when selecting dependencies
195 # from deps_os.
196 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200197
198 # For recursed-upon sub-dependencies, check out their own dependencies
199 # relative to the paren't path, rather than relative to the .gclient file.
200 schema.Optional('use_relative_paths'): bool,
201
202 # Variables that can be referenced using Var() - see 'deps'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400203 schema.Optional('vars'): _NodeDictSchema({
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200204 schema.Optional(basestring): schema.Or(basestring, bool),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400205 }),
206}))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200207
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200208
Edward Lemura32f98e2018-06-04 16:07:16 -0400209def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200210 """Safely evaluates a single expression. Returns the result."""
Edward Lemura32f98e2018-06-04 16:07:16 -0400211 vars_dict = vars_dict or {}
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200212 _allowed_names = {'None': None, 'True': True, 'False': False}
213 if isinstance(node_or_string, basestring):
214 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
215 if isinstance(node_or_string, ast.Expression):
216 node_or_string = node_or_string.body
217 def _convert(node):
218 if isinstance(node, ast.Str):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400219 try:
220 return node.s.format(**vars_dict)
221 except KeyError as e:
222 raise ValueError(
223 '%s was used as a variable, but was not declared in the vars dict '
224 '(file %r, line %s)' % (
225 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200226 elif isinstance(node, ast.Num):
227 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200228 elif isinstance(node, ast.Tuple):
229 return tuple(map(_convert, node.elts))
230 elif isinstance(node, ast.List):
231 return list(map(_convert, node.elts))
232 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400233 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200234 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200235 elif isinstance(node, ast.Name):
236 if node.id not in _allowed_names:
237 raise ValueError(
238 'invalid name %r (file %r, line %s)' % (
239 node.id, filename, getattr(node, 'lineno', '<unknown>')))
240 return _allowed_names[node.id]
241 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400242 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200243 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400244 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200245 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400246 if node.keywords or node.starargs or node.kwargs or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200247 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400248 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200249 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400250 arg = _convert(node.args[0])
251 if not isinstance(arg, basestring):
252 raise ValueError(
253 'Var\'s argument must be a variable name (file %r, line %s)' % (
254 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400255 if vars_dict is None:
256 raise ValueError(
257 'vars must be declared before Var can be used (file %r, line %s)'
258 % (filename, getattr(node, 'lineno', '<unknown>')))
259 if arg not in vars_dict:
260 raise ValueError(
261 '%s was used as a variable, but was not declared in the vars dict '
262 '(file %r, line %s)' % (
263 arg, filename, getattr(node, 'lineno', '<unknown>')))
264 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200265 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
266 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200267 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
268 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200269 else:
270 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200271 'unexpected AST node: %s %s (file %r, line %s)' % (
272 node, ast.dump(node), filename,
273 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200274 return _convert(node_or_string)
275
276
Edward Lemura32f98e2018-06-04 16:07:16 -0400277def Exec(content, filename='<unknown>', vars_override=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400278 """Safely execs a set of assignments."""
279 def _validate_statement(node, local_scope):
280 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200281 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200282 'unexpected AST node: %s %s (file %r, line %s)' % (
283 node, ast.dump(node), filename,
284 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200285
Edward Lesmes6c24d372018-03-28 12:52:29 -0400286 if len(node.targets) != 1:
287 raise ValueError(
288 'invalid assignment: use exactly one target (file %r, line %s)' % (
289 filename, getattr(node, 'lineno', '<unknown>')))
290
291 target = node.targets[0]
292 if not isinstance(target, ast.Name):
293 raise ValueError(
294 'invalid assignment: target should be a name (file %r, line %s)' % (
295 filename, getattr(node, 'lineno', '<unknown>')))
296 if target.id in local_scope:
297 raise ValueError(
298 'invalid assignment: overrides var %r (file %r, line %s)' % (
299 target.id, filename, getattr(node, 'lineno', '<unknown>')))
300
301 node_or_string = ast.parse(content, filename=filename, mode='exec')
302 if isinstance(node_or_string, ast.Expression):
303 node_or_string = node_or_string.body
304
305 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200306 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200307 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200308 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200309 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200310 filename,
311 getattr(node_or_string, 'lineno', '<unknown>')))
312
Edward Lesmes6c24d372018-03-28 12:52:29 -0400313 statements = {}
314 for statement in node_or_string.body:
315 _validate_statement(statement, statements)
316 statements[statement.targets[0].id] = statement.value
317
318 tokens = {
319 token[2]: list(token)
320 for token in tokenize.generate_tokens(
321 cStringIO.StringIO(content).readline)
322 }
323 local_scope = _NodeDict({}, tokens)
324
325 # Process vars first, so we can expand variables in the rest of the DEPS file.
326 vars_dict = {}
327 if 'vars' in statements:
328 vars_statement = statements['vars']
Edward Lemura32f98e2018-06-04 16:07:16 -0400329 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400330 local_scope.SetNode('vars', value, vars_statement)
331 # Update the parsed vars with the overrides, but only if they are already
332 # present (overrides do not introduce new variables).
333 vars_dict.update(value)
334 if vars_override:
335 vars_dict.update({
336 k: v
337 for k, v in vars_override.iteritems()
338 if k in vars_dict})
339
340 for name, node in statements.iteritems():
Edward Lemura32f98e2018-06-04 16:07:16 -0400341 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400342 local_scope.SetNode(name, value, node)
343
John Budorick0f7b2002018-01-19 15:46:17 -0800344 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200345
346
Edward Lemura32f98e2018-06-04 16:07:16 -0400347def ExecLegacy(content, filename='<unknown>', vars_override=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400348 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400349 local_scope = {}
350 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
351
352 # If we use 'exec' directly, it complains that 'Parse' contains a nested
353 # function with free variables.
354 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
355 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
356 eval(compile(content, filename, 'exec'), global_scope, local_scope)
357
Edward Lemura32f98e2018-06-04 16:07:16 -0400358 if 'vars' not in local_scope:
Edward Lesmes6c24d372018-03-28 12:52:29 -0400359 return local_scope
360
361 vars_dict = {}
362 vars_dict.update(local_scope['vars'])
363 if vars_override:
364 vars_dict.update({
365 k: v
366 for k, v in vars_override.iteritems()
367 if k in vars_dict
368 })
369
370 def _DeepFormat(node):
371 if isinstance(node, basestring):
372 return node.format(**vars_dict)
373 elif isinstance(node, dict):
374 return {
375 k.format(**vars_dict): _DeepFormat(v)
376 for k, v in node.iteritems()
377 }
378 elif isinstance(node, list):
379 return [_DeepFormat(elem) for elem in node]
380 elif isinstance(node, tuple):
381 return tuple(_DeepFormat(elem) for elem in node)
382 else:
383 return node
384
385 return _DeepFormat(local_scope)
386
387
Edward Lemur16f4bad2018-05-16 16:53:49 -0400388def _StandardizeDeps(deps_dict, vars_dict):
389 """"Standardizes the deps_dict.
390
391 For each dependency:
392 - Expands the variable in the dependency name.
393 - Ensures the dependency is a dictionary.
394 - Set's the 'dep_type' to be 'git' by default.
395 """
396 new_deps_dict = {}
397 for dep_name, dep_info in deps_dict.items():
398 dep_name = dep_name.format(**vars_dict)
399 if not isinstance(dep_info, collections.Mapping):
400 dep_info = {'url': dep_info}
401 dep_info.setdefault('dep_type', 'git')
402 new_deps_dict[dep_name] = dep_info
403 return new_deps_dict
404
405
406def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
407 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
408
409 The dependencies in os_deps_dict are transformed into conditional dependencies
410 using |'checkout_' + os_name|.
411 If the dependency is already present, the URL and revision must coincide.
412 """
413 for dep_name, dep_info in os_deps_dict.items():
414 # Make this condition very visible, so it's not a silent failure.
415 # It's unclear how to support None override in deps_os.
416 if dep_info['url'] is None:
417 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
418 continue
419
420 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
421 UpdateCondition(dep_info, 'and', os_condition)
422
423 if dep_name in deps_dict:
424 if deps_dict[dep_name]['url'] != dep_info['url']:
425 raise gclient_utils.Error(
426 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
427 'entry (%r).' % (
428 os_name, dep_name, dep_info, deps_dict[dep_name]))
429
430 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
431
432 deps_dict[dep_name] = dep_info
433
434
435def UpdateCondition(info_dict, op, new_condition):
436 """Updates info_dict's condition with |new_condition|.
437
438 An absent value is treated as implicitly True.
439 """
440 curr_condition = info_dict.get('condition')
441 # Easy case: Both are present.
442 if curr_condition and new_condition:
443 info_dict['condition'] = '(%s) %s (%s)' % (
444 curr_condition, op, new_condition)
445 # If |op| == 'and', and at least one condition is present, then use it.
446 elif op == 'and' and (curr_condition or new_condition):
447 info_dict['condition'] = curr_condition or new_condition
448 # Otherwise, no condition should be set
449 elif curr_condition:
450 del info_dict['condition']
451
452
Edward Lemura32f98e2018-06-04 16:07:16 -0400453def Parse(content, validate_syntax, filename, vars_override=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400454 """Parses DEPS strings.
455
456 Executes the Python-like string stored in content, resulting in a Python
457 dictionary specifyied by the schema above. Supports syntax validation and
458 variable expansion.
459
460 Args:
461 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400462 validate_syntax: bool. Whether syntax should be validated using the schema
463 defined above.
464 filename: str. The name of the DEPS file, or a string describing the source
465 of the content, e.g. '<string>', '<unknown>'.
466 vars_override: dict, optional. A dictionary with overrides for the variables
467 defined by the DEPS file.
468
469 Returns:
470 A Python dict with the parsed contents of the DEPS file, as specified by the
471 schema above.
472 """
473 if validate_syntax:
Edward Lemura32f98e2018-06-04 16:07:16 -0400474 result = Exec(content, filename, vars_override)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400475 else:
Edward Lemura32f98e2018-06-04 16:07:16 -0400476 result = ExecLegacy(content, filename, vars_override)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400477
478 vars_dict = result.get('vars', {})
479 if 'deps' in result:
480 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
481
482 if 'deps_os' in result:
483 deps = result.setdefault('deps', {})
484 for os_name, os_deps in result['deps_os'].iteritems():
485 os_deps = _StandardizeDeps(os_deps, vars_dict)
486 _MergeDepsOs(deps, os_deps, os_name)
487 del result['deps_os']
488
489 if 'hooks_os' in result:
490 hooks = result.setdefault('hooks', [])
491 for os_name, os_hooks in result['hooks_os'].iteritems():
492 for hook in os_hooks:
493 UpdateCondition(hook, 'and', 'checkout_' + os_name)
494 hooks.extend(os_hooks)
495 del result['hooks_os']
496
497 return result
498
499
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200500def EvaluateCondition(condition, variables, referenced_variables=None):
501 """Safely evaluates a boolean condition. Returns the result."""
502 if not referenced_variables:
503 referenced_variables = set()
504 _allowed_names = {'None': None, 'True': True, 'False': False}
505 main_node = ast.parse(condition, mode='eval')
506 if isinstance(main_node, ast.Expression):
507 main_node = main_node.body
508 def _convert(node):
509 if isinstance(node, ast.Str):
510 return node.s
511 elif isinstance(node, ast.Name):
512 if node.id in referenced_variables:
513 raise ValueError(
514 'invalid cyclic reference to %r (inside %r)' % (
515 node.id, condition))
516 elif node.id in _allowed_names:
517 return _allowed_names[node.id]
518 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200519 value = variables[node.id]
520
521 # Allow using "native" types, without wrapping everything in strings.
522 # Note that schema constraints still apply to variables.
523 if not isinstance(value, basestring):
524 return value
525
526 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200527 return EvaluateCondition(
528 variables[node.id],
529 variables,
530 referenced_variables.union([node.id]))
531 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200532 # Implicitly convert unrecognized names to strings.
533 # If we want to change this, we'll need to explicitly distinguish
534 # between arguments for GN to be passed verbatim, and ones to
535 # be evaluated.
536 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200537 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
538 if len(node.values) != 2:
539 raise ValueError(
540 'invalid "or": exactly 2 operands required (inside %r)' % (
541 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200542 left = _convert(node.values[0])
543 right = _convert(node.values[1])
544 if not isinstance(left, bool):
545 raise ValueError(
546 'invalid "or" operand %r (inside %r)' % (left, condition))
547 if not isinstance(right, bool):
548 raise ValueError(
549 'invalid "or" operand %r (inside %r)' % (right, condition))
550 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200551 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
552 if len(node.values) != 2:
553 raise ValueError(
554 'invalid "and": exactly 2 operands required (inside %r)' % (
555 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200556 left = _convert(node.values[0])
557 right = _convert(node.values[1])
558 if not isinstance(left, bool):
559 raise ValueError(
560 'invalid "and" operand %r (inside %r)' % (left, condition))
561 if not isinstance(right, bool):
562 raise ValueError(
563 'invalid "and" operand %r (inside %r)' % (right, condition))
564 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200565 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200566 value = _convert(node.operand)
567 if not isinstance(value, bool):
568 raise ValueError(
569 'invalid "not" operand %r (inside %r)' % (value, condition))
570 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200571 elif isinstance(node, ast.Compare):
572 if len(node.ops) != 1:
573 raise ValueError(
574 'invalid compare: exactly 1 operator required (inside %r)' % (
575 condition))
576 if len(node.comparators) != 1:
577 raise ValueError(
578 'invalid compare: exactly 1 comparator required (inside %r)' % (
579 condition))
580
581 left = _convert(node.left)
582 right = _convert(node.comparators[0])
583
584 if isinstance(node.ops[0], ast.Eq):
585 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700586 if isinstance(node.ops[0], ast.NotEq):
587 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200588
589 raise ValueError(
590 'unexpected operator: %s %s (inside %r)' % (
591 node.ops[0], ast.dump(node), condition))
592 else:
593 raise ValueError(
594 'unexpected AST node: %s %s (inside %r)' % (
595 node, ast.dump(node), condition))
596 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400597
598
599def RenderDEPSFile(gclient_dict):
600 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
601 return tokenize.untokenize(contents)
602
603
604def _UpdateAstString(tokens, node, value):
605 position = node.lineno, node.col_offset
Edward Lesmes62af4e42018-03-30 18:15:44 -0400606 quote_char = tokens[position][1][0]
607 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400608 node.s = value
609
610
Edward Lesmes3d993812018-04-02 12:52:49 -0400611def _ShiftLinesInTokens(tokens, delta, start):
612 new_tokens = {}
613 for token in tokens.values():
614 if token[2][0] >= start:
615 token[2] = token[2][0] + delta, token[2][1]
616 token[3] = token[3][0] + delta, token[3][1]
617 new_tokens[token[2]] = token
618 return new_tokens
619
620
621def AddVar(gclient_dict, var_name, value):
622 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
623 raise ValueError(
624 "Can't use SetVar for the given gclient dict. It contains no "
625 "formatting information.")
626
627 if 'vars' not in gclient_dict:
628 raise KeyError("vars dict is not defined.")
629
630 if var_name in gclient_dict['vars']:
631 raise ValueError(
632 "%s has already been declared in the vars dict. Consider using SetVar "
633 "instead." % var_name)
634
635 if not gclient_dict['vars']:
636 raise ValueError('vars dict is empty. This is not yet supported.')
637
Edward Lesmes8d626572018-04-05 17:53:10 -0400638 # We will attempt to add the var right after 'vars = {'.
639 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400640 if node is None:
641 raise ValueError(
642 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400643 line = node.lineno + 1
644
645 # We will try to match the new var's indentation to the next variable.
646 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400647
648 # We use a minimal Python dictionary, so that ast can parse it.
649 var_content = '{\n%s"%s": "%s",\n}' % (' ' * col, var_name, value)
650 var_ast = ast.parse(var_content).body[0].value
651
652 # Set the ast nodes for the key and value.
653 vars_node = gclient_dict.GetNode('vars')
654
655 var_name_node = var_ast.keys[0]
656 var_name_node.lineno += line - 2
657 vars_node.keys.insert(0, var_name_node)
658
659 value_node = var_ast.values[0]
660 value_node.lineno += line - 2
661 vars_node.values.insert(0, value_node)
662
663 # Update the tokens.
664 var_tokens = list(tokenize.generate_tokens(
665 cStringIO.StringIO(var_content).readline))
666 var_tokens = {
667 token[2]: list(token)
668 # Ignore the tokens corresponding to braces and new lines.
669 for token in var_tokens[2:-2]
670 }
671
672 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
673 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
674
675
Edward Lesmes6f64a052018-03-20 17:35:49 -0400676def SetVar(gclient_dict, var_name, value):
677 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
678 raise ValueError(
679 "Can't use SetVar for the given gclient dict. It contains no "
680 "formatting information.")
681 tokens = gclient_dict.tokens
682
Edward Lesmes3d993812018-04-02 12:52:49 -0400683 if 'vars' not in gclient_dict:
684 raise KeyError("vars dict is not defined.")
685
686 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400687 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400688 "%s has not been declared in the vars dict. Consider using AddVar "
689 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400690
691 node = gclient_dict['vars'].GetNode(var_name)
692 if node is None:
693 raise ValueError(
694 "The vars entry for %s has no formatting information." % var_name)
695
696 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400697 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400698
699
700def SetCIPD(gclient_dict, dep_name, package_name, new_version):
701 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
702 raise ValueError(
703 "Can't use SetCIPD for the given gclient dict. It contains no "
704 "formatting information.")
705 tokens = gclient_dict.tokens
706
707 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400708 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400709 "Could not find any dependency called %s." % dep_name)
710
711 # Find the package with the given name
712 packages = [
713 package
714 for package in gclient_dict['deps'][dep_name]['packages']
715 if package['package'] == package_name
716 ]
717 if len(packages) != 1:
718 raise ValueError(
719 "There must be exactly one package with the given name (%s), "
720 "%s were found." % (package_name, len(packages)))
721
722 # TODO(ehmaldonado): Support Var in package's version.
723 node = packages[0].GetNode('version')
724 if node is None:
725 raise ValueError(
726 "The deps entry for %s:%s has no formatting information." %
727 (dep_name, package_name))
728
729 new_version = 'version:' + new_version
730 _UpdateAstString(tokens, node, new_version)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400731 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400732
733
Edward Lesmes9f531292018-03-20 21:27:15 -0400734def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400735 def _GetVarName(node):
736 if isinstance(node, ast.Call):
737 return node.args[0].s
738 elif node.s.endswith('}'):
739 last_brace = node.s.rfind('{')
740 return node.s[last_brace+1:-1]
741 return None
742
743 def _UpdateRevision(dep_dict, dep_key, new_revision):
744 dep_node = dep_dict.GetNode(dep_key)
745 if dep_node is None:
746 raise ValueError(
747 "The deps entry for %s has no formatting information." % dep_name)
748
749 node = dep_node
750 if isinstance(node, ast.BinOp):
751 node = node.right
752
753 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
754 raise ValueError(
755 "Unsupported dependency revision format. Please file a bug.")
756
757 var_name = _GetVarName(node)
758 if var_name is not None:
759 SetVar(gclient_dict, var_name, new_revision)
760 else:
761 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400762 # '@' is part of the last string, which we want to modify. Discard
763 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400764 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400765 elif '@' not in dep_dict[dep_key]:
766 # '@' is not part of the URL at all. This mean the dependency is
767 # unpinned and we should pin it.
768 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400769 _UpdateAstString(tokens, node, new_revision)
770 dep_dict.SetNode(dep_key, new_revision, node)
771
Edward Lesmes6f64a052018-03-20 17:35:49 -0400772 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
773 raise ValueError(
774 "Can't use SetRevision for the given gclient dict. It contains no "
775 "formatting information.")
776 tokens = gclient_dict.tokens
777
778 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400779 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400780 "Could not find any dependency called %s." % dep_name)
781
Edward Lesmes6f64a052018-03-20 17:35:49 -0400782 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400783 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400784 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400785 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400786
787
788def GetVar(gclient_dict, var_name):
789 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
790 raise KeyError(
791 "Could not find any variable called %s." % var_name)
792
793 return gclient_dict['vars'][var_name]
794
795
796def GetCIPD(gclient_dict, dep_name, package_name):
797 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
798 raise KeyError(
799 "Could not find any dependency called %s." % dep_name)
800
801 # Find the package with the given name
802 packages = [
803 package
804 for package in gclient_dict['deps'][dep_name]['packages']
805 if package['package'] == package_name
806 ]
807 if len(packages) != 1:
808 raise ValueError(
809 "There must be exactly one package with the given name (%s), "
810 "%s were found." % (package_name, len(packages)))
811
812 return packages[0]['version'][len('version:'):]
813
814
815def GetRevision(gclient_dict, dep_name):
816 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
817 raise KeyError(
818 "Could not find any dependency called %s." % dep_name)
819
820 dep = gclient_dict['deps'][dep_name]
821 if dep is None:
822 return None
823 elif isinstance(dep, basestring):
824 _, _, revision = dep.partition('@')
825 return revision or None
826 elif isinstance(dep, collections.Mapping) and 'url' in dep:
827 _, _, revision = dep['url'].partition('@')
828 return revision or None
829 else:
830 raise ValueError(
831 '%s is not a valid git dependency.' % dep_name)