blob: 92a165ff6ba632dbf14b5afefb22fa70f8acdacf [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 Lesmes6f64a052018-03-20 17:35:49 -04008import tokenize
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +02009
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020010from third_party import schema
11
12
Edward Lesmes6f64a052018-03-20 17:35:49 -040013class _NodeDict(collections.MutableMapping):
14 """Dict-like type that also stores information on AST nodes and tokens."""
15 def __init__(self, data, tokens=None):
16 self.data = collections.OrderedDict(data)
17 self.tokens = tokens
18
19 def __str__(self):
20 return str({k: v[0] for k, v in self.data.iteritems()})
21
22 def __getitem__(self, key):
23 return self.data[key][0]
24
25 def __setitem__(self, key, value):
26 self.data[key] = (value, None)
27
28 def __delitem__(self, key):
29 del self.data[key]
30
31 def __iter__(self):
32 return iter(self.data)
33
34 def __len__(self):
35 return len(self.data)
36
37 def GetNode(self, key):
38 return self.data[key][1]
39
Edward Lesmes6c24d372018-03-28 12:52:29 -040040 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040041 self.data[key] = (value, node)
42
43
44def _NodeDictSchema(dict_schema):
45 """Validate dict_schema after converting _NodeDict to a regular dict."""
46 def validate(d):
47 schema.Schema(dict_schema).validate(dict(d))
48 return True
49 return validate
50
51
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020052# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -040053_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020054 schema.Optional(basestring): schema.Or(
55 None,
56 basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040057 _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020058 # Repo and revision to check out under the path
59 # (same as if no dict was used).
Michael Moss012013e2018-03-30 17:03:19 -070060 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020061
62 # Optional condition string. The dep will only be processed
63 # if the condition evaluates to True.
64 schema.Optional('condition'): basestring,
John Budorick0f7b2002018-01-19 15:46:17 -080065
66 schema.Optional('dep_type', default='git'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040067 }),
John Budorick0f7b2002018-01-19 15:46:17 -080068 # CIPD package.
Edward Lesmes6f64a052018-03-20 17:35:49 -040069 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080070 'packages': [
Edward Lesmes6f64a052018-03-20 17:35:49 -040071 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080072 'package': basestring,
73
74 'version': basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040075 })
John Budorick0f7b2002018-01-19 15:46:17 -080076 ],
77
78 schema.Optional('condition'): basestring,
79
80 schema.Optional('dep_type', default='cipd'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040081 }),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020082 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -040083})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020084
Edward Lesmes6f64a052018-03-20 17:35:49 -040085_GCLIENT_HOOKS_SCHEMA = [_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020086 # Hook action: list of command-line arguments to invoke.
87 'action': [basestring],
88
89 # Name of the hook. Doesn't affect operation.
90 schema.Optional('name'): basestring,
91
92 # Hook pattern (regex). Originally intended to limit some hooks to run
93 # only when files matching the pattern have changed. In practice, with git,
94 # gclient runs all the hooks regardless of this field.
95 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +020096
97 # Working directory where to execute the hook.
98 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +020099
100 # Optional condition string. The hook will only be run
101 # if the condition evaluates to True.
102 schema.Optional('condition'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400103})]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200104
Edward Lesmes6f64a052018-03-20 17:35:49 -0400105_GCLIENT_SCHEMA = schema.Schema(_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200106 # List of host names from which dependencies are allowed (whitelist).
107 # NOTE: when not present, all hosts are allowed.
108 # NOTE: scoped to current DEPS file, not recursive.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200109 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200110
111 # Mapping from paths to repo and revision to check out under that path.
112 # Applying this mapping to the on-disk checkout is the main purpose
113 # of gclient, and also why the config file is called DEPS.
114 #
115 # The following functions are allowed:
116 #
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200117 # Var(): allows variable substitution (either from 'vars' dict below,
118 # or command-line override)
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200119 schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200120
121 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200122 # Also see 'target_os'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400123 schema.Optional('deps_os'): _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200124 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400125 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200126
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200127 # Path to GN args file to write selected variables.
128 schema.Optional('gclient_gn_args_file'): basestring,
129
130 # Subset of variables to write to the GN args file (see above).
131 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
132
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200133 # Hooks executed after gclient sync (unless suppressed), or explicitly
134 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
135 # Also see 'pre_deps_hooks'.
136 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
137
Scott Grahamc4826742017-05-11 16:59:23 -0700138 # Similar to 'hooks', also keyed by OS.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400139 schema.Optional('hooks_os'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200140 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
Edward Lesmes6f64a052018-03-20 17:35:49 -0400141 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700142
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200143 # Rules which #includes are allowed in the directory.
144 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200145 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200146
147 # Hooks executed before processing DEPS. See 'hooks' for more details.
148 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
149
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200150 # Recursion limit for nested DEPS.
151 schema.Optional('recursion'): int,
152
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200153 # Whitelists deps for which recursion should be enabled.
154 schema.Optional('recursedeps'): [
Paweł Hajdan, Jr05fec032017-05-30 23:04:23 +0200155 schema.Optional(schema.Or(
156 basestring,
157 (basestring, basestring),
158 [basestring, basestring]
159 )),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200160 ],
161
162 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200163 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200164
165 # Mapping from paths to include rules specific for that path.
166 # See 'include_rules' for more details.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400167 schema.Optional('specific_include_rules'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200168 schema.Optional(basestring): [basestring]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400169 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200170
171 # List of additional OS names to consider when selecting dependencies
172 # from deps_os.
173 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200174
175 # For recursed-upon sub-dependencies, check out their own dependencies
176 # relative to the paren't path, rather than relative to the .gclient file.
177 schema.Optional('use_relative_paths'): bool,
178
179 # Variables that can be referenced using Var() - see 'deps'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400180 schema.Optional('vars'): _NodeDictSchema({
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200181 schema.Optional(basestring): schema.Or(basestring, bool),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400182 }),
183}))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200184
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200185
Edward Lesmes6c24d372018-03-28 12:52:29 -0400186def _gclient_eval(node_or_string, vars_dict=None, expand_vars=False,
187 filename='<unknown>'):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200188 """Safely evaluates a single expression. Returns the result."""
189 _allowed_names = {'None': None, 'True': True, 'False': False}
190 if isinstance(node_or_string, basestring):
191 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
192 if isinstance(node_or_string, ast.Expression):
193 node_or_string = node_or_string.body
194 def _convert(node):
195 if isinstance(node, ast.Str):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400196 if not expand_vars:
197 return node.s
198 try:
199 return node.s.format(**vars_dict)
200 except KeyError as e:
201 raise ValueError(
202 '%s was used as a variable, but was not declared in the vars dict '
203 '(file %r, line %s)' % (
204 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200205 elif isinstance(node, ast.Num):
206 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200207 elif isinstance(node, ast.Tuple):
208 return tuple(map(_convert, node.elts))
209 elif isinstance(node, ast.List):
210 return list(map(_convert, node.elts))
211 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400212 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200213 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200214 elif isinstance(node, ast.Name):
215 if node.id not in _allowed_names:
216 raise ValueError(
217 'invalid name %r (file %r, line %s)' % (
218 node.id, filename, getattr(node, 'lineno', '<unknown>')))
219 return _allowed_names[node.id]
220 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400221 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200222 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400223 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200224 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400225 if node.keywords or node.starargs or node.kwargs or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200226 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400227 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200228 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400229 arg = _convert(node.args[0])
230 if not isinstance(arg, basestring):
231 raise ValueError(
232 'Var\'s argument must be a variable name (file %r, line %s)' % (
233 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400234 if not expand_vars:
235 return '{%s}' % arg
236 if vars_dict is None:
237 raise ValueError(
238 'vars must be declared before Var can be used (file %r, line %s)'
239 % (filename, getattr(node, 'lineno', '<unknown>')))
240 if arg not in vars_dict:
241 raise ValueError(
242 '%s was used as a variable, but was not declared in the vars dict '
243 '(file %r, line %s)' % (
244 arg, filename, getattr(node, 'lineno', '<unknown>')))
245 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200246 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
247 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200248 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
249 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200250 else:
251 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200252 'unexpected AST node: %s %s (file %r, line %s)' % (
253 node, ast.dump(node), filename,
254 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200255 return _convert(node_or_string)
256
257
Edward Lesmes6c24d372018-03-28 12:52:29 -0400258def Exec(content, expand_vars=True, filename='<unknown>', vars_override=None):
259 """Safely execs a set of assignments."""
260 def _validate_statement(node, local_scope):
261 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200262 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200263 'unexpected AST node: %s %s (file %r, line %s)' % (
264 node, ast.dump(node), filename,
265 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200266
Edward Lesmes6c24d372018-03-28 12:52:29 -0400267 if len(node.targets) != 1:
268 raise ValueError(
269 'invalid assignment: use exactly one target (file %r, line %s)' % (
270 filename, getattr(node, 'lineno', '<unknown>')))
271
272 target = node.targets[0]
273 if not isinstance(target, ast.Name):
274 raise ValueError(
275 'invalid assignment: target should be a name (file %r, line %s)' % (
276 filename, getattr(node, 'lineno', '<unknown>')))
277 if target.id in local_scope:
278 raise ValueError(
279 'invalid assignment: overrides var %r (file %r, line %s)' % (
280 target.id, filename, getattr(node, 'lineno', '<unknown>')))
281
282 node_or_string = ast.parse(content, filename=filename, mode='exec')
283 if isinstance(node_or_string, ast.Expression):
284 node_or_string = node_or_string.body
285
286 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200287 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200288 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200289 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200290 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200291 filename,
292 getattr(node_or_string, 'lineno', '<unknown>')))
293
Edward Lesmes6c24d372018-03-28 12:52:29 -0400294 statements = {}
295 for statement in node_or_string.body:
296 _validate_statement(statement, statements)
297 statements[statement.targets[0].id] = statement.value
298
299 tokens = {
300 token[2]: list(token)
301 for token in tokenize.generate_tokens(
302 cStringIO.StringIO(content).readline)
303 }
304 local_scope = _NodeDict({}, tokens)
305
306 # Process vars first, so we can expand variables in the rest of the DEPS file.
307 vars_dict = {}
308 if 'vars' in statements:
309 vars_statement = statements['vars']
310 value = _gclient_eval(vars_statement, None, False, filename)
311 local_scope.SetNode('vars', value, vars_statement)
312 # Update the parsed vars with the overrides, but only if they are already
313 # present (overrides do not introduce new variables).
314 vars_dict.update(value)
315 if vars_override:
316 vars_dict.update({
317 k: v
318 for k, v in vars_override.iteritems()
319 if k in vars_dict})
320
321 for name, node in statements.iteritems():
322 value = _gclient_eval(node, vars_dict, expand_vars, filename)
323 local_scope.SetNode(name, value, node)
324
John Budorick0f7b2002018-01-19 15:46:17 -0800325 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200326
327
Edward Lesmes6c24d372018-03-28 12:52:29 -0400328def Parse(content, expand_vars, validate_syntax, filename, vars_override=None):
329 """Parses DEPS strings.
330
331 Executes the Python-like string stored in content, resulting in a Python
332 dictionary specifyied by the schema above. Supports syntax validation and
333 variable expansion.
334
335 Args:
336 content: str. DEPS file stored as a string.
337 expand_vars: bool. Whether variables should be expanded to their values.
338 validate_syntax: bool. Whether syntax should be validated using the schema
339 defined above.
340 filename: str. The name of the DEPS file, or a string describing the source
341 of the content, e.g. '<string>', '<unknown>'.
342 vars_override: dict, optional. A dictionary with overrides for the variables
343 defined by the DEPS file.
344
345 Returns:
346 A Python dict with the parsed contents of the DEPS file, as specified by the
347 schema above.
348 """
349 # TODO(ehmaldonado): Make validate_syntax = True the only case
350 if validate_syntax:
351 return Exec(content, expand_vars, filename, vars_override)
352
353 local_scope = {}
354 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
355
356 # If we use 'exec' directly, it complains that 'Parse' contains a nested
357 # function with free variables.
358 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
359 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
360 eval(compile(content, filename, 'exec'), global_scope, local_scope)
361
362 if 'vars' not in local_scope or not expand_vars:
363 return local_scope
364
365 vars_dict = {}
366 vars_dict.update(local_scope['vars'])
367 if vars_override:
368 vars_dict.update({
369 k: v
370 for k, v in vars_override.iteritems()
371 if k in vars_dict
372 })
373
374 def _DeepFormat(node):
375 if isinstance(node, basestring):
376 return node.format(**vars_dict)
377 elif isinstance(node, dict):
378 return {
379 k.format(**vars_dict): _DeepFormat(v)
380 for k, v in node.iteritems()
381 }
382 elif isinstance(node, list):
383 return [_DeepFormat(elem) for elem in node]
384 elif isinstance(node, tuple):
385 return tuple(_DeepFormat(elem) for elem in node)
386 else:
387 return node
388
389 return _DeepFormat(local_scope)
390
391
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200392def EvaluateCondition(condition, variables, referenced_variables=None):
393 """Safely evaluates a boolean condition. Returns the result."""
394 if not referenced_variables:
395 referenced_variables = set()
396 _allowed_names = {'None': None, 'True': True, 'False': False}
397 main_node = ast.parse(condition, mode='eval')
398 if isinstance(main_node, ast.Expression):
399 main_node = main_node.body
400 def _convert(node):
401 if isinstance(node, ast.Str):
402 return node.s
403 elif isinstance(node, ast.Name):
404 if node.id in referenced_variables:
405 raise ValueError(
406 'invalid cyclic reference to %r (inside %r)' % (
407 node.id, condition))
408 elif node.id in _allowed_names:
409 return _allowed_names[node.id]
410 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200411 value = variables[node.id]
412
413 # Allow using "native" types, without wrapping everything in strings.
414 # Note that schema constraints still apply to variables.
415 if not isinstance(value, basestring):
416 return value
417
418 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200419 return EvaluateCondition(
420 variables[node.id],
421 variables,
422 referenced_variables.union([node.id]))
423 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200424 # Implicitly convert unrecognized names to strings.
425 # If we want to change this, we'll need to explicitly distinguish
426 # between arguments for GN to be passed verbatim, and ones to
427 # be evaluated.
428 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200429 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
430 if len(node.values) != 2:
431 raise ValueError(
432 'invalid "or": exactly 2 operands required (inside %r)' % (
433 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200434 left = _convert(node.values[0])
435 right = _convert(node.values[1])
436 if not isinstance(left, bool):
437 raise ValueError(
438 'invalid "or" operand %r (inside %r)' % (left, condition))
439 if not isinstance(right, bool):
440 raise ValueError(
441 'invalid "or" operand %r (inside %r)' % (right, condition))
442 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200443 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
444 if len(node.values) != 2:
445 raise ValueError(
446 'invalid "and": exactly 2 operands required (inside %r)' % (
447 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200448 left = _convert(node.values[0])
449 right = _convert(node.values[1])
450 if not isinstance(left, bool):
451 raise ValueError(
452 'invalid "and" operand %r (inside %r)' % (left, condition))
453 if not isinstance(right, bool):
454 raise ValueError(
455 'invalid "and" operand %r (inside %r)' % (right, condition))
456 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200457 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200458 value = _convert(node.operand)
459 if not isinstance(value, bool):
460 raise ValueError(
461 'invalid "not" operand %r (inside %r)' % (value, condition))
462 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200463 elif isinstance(node, ast.Compare):
464 if len(node.ops) != 1:
465 raise ValueError(
466 'invalid compare: exactly 1 operator required (inside %r)' % (
467 condition))
468 if len(node.comparators) != 1:
469 raise ValueError(
470 'invalid compare: exactly 1 comparator required (inside %r)' % (
471 condition))
472
473 left = _convert(node.left)
474 right = _convert(node.comparators[0])
475
476 if isinstance(node.ops[0], ast.Eq):
477 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700478 if isinstance(node.ops[0], ast.NotEq):
479 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200480
481 raise ValueError(
482 'unexpected operator: %s %s (inside %r)' % (
483 node.ops[0], ast.dump(node), condition))
484 else:
485 raise ValueError(
486 'unexpected AST node: %s %s (inside %r)' % (
487 node, ast.dump(node), condition))
488 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400489
490
491def RenderDEPSFile(gclient_dict):
492 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
493 return tokenize.untokenize(contents)
494
495
496def _UpdateAstString(tokens, node, value):
497 position = node.lineno, node.col_offset
Edward Lesmes62af4e42018-03-30 18:15:44 -0400498 quote_char = tokens[position][1][0]
499 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400500 node.s = value
501
502
503def SetVar(gclient_dict, var_name, value):
504 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
505 raise ValueError(
506 "Can't use SetVar for the given gclient dict. It contains no "
507 "formatting information.")
508 tokens = gclient_dict.tokens
509
510 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
511 raise ValueError(
512 "Could not find any variable called %s." % var_name)
513
514 node = gclient_dict['vars'].GetNode(var_name)
515 if node is None:
516 raise ValueError(
517 "The vars entry for %s has no formatting information." % var_name)
518
519 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400520 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400521
522
523def SetCIPD(gclient_dict, dep_name, package_name, new_version):
524 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
525 raise ValueError(
526 "Can't use SetCIPD for the given gclient dict. It contains no "
527 "formatting information.")
528 tokens = gclient_dict.tokens
529
530 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
531 raise ValueError(
532 "Could not find any dependency called %s." % dep_name)
533
534 # Find the package with the given name
535 packages = [
536 package
537 for package in gclient_dict['deps'][dep_name]['packages']
538 if package['package'] == package_name
539 ]
540 if len(packages) != 1:
541 raise ValueError(
542 "There must be exactly one package with the given name (%s), "
543 "%s were found." % (package_name, len(packages)))
544
545 # TODO(ehmaldonado): Support Var in package's version.
546 node = packages[0].GetNode('version')
547 if node is None:
548 raise ValueError(
549 "The deps entry for %s:%s has no formatting information." %
550 (dep_name, package_name))
551
552 new_version = 'version:' + new_version
553 _UpdateAstString(tokens, node, new_version)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400554 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400555
556
Edward Lesmes9f531292018-03-20 21:27:15 -0400557def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400558 def _GetVarName(node):
559 if isinstance(node, ast.Call):
560 return node.args[0].s
561 elif node.s.endswith('}'):
562 last_brace = node.s.rfind('{')
563 return node.s[last_brace+1:-1]
564 return None
565
566 def _UpdateRevision(dep_dict, dep_key, new_revision):
567 dep_node = dep_dict.GetNode(dep_key)
568 if dep_node is None:
569 raise ValueError(
570 "The deps entry for %s has no formatting information." % dep_name)
571
572 node = dep_node
573 if isinstance(node, ast.BinOp):
574 node = node.right
575
576 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
577 raise ValueError(
578 "Unsupported dependency revision format. Please file a bug.")
579
580 var_name = _GetVarName(node)
581 if var_name is not None:
582 SetVar(gclient_dict, var_name, new_revision)
583 else:
584 if '@' in node.s:
585 new_revision = node.s.split('@')[0] + '@' + new_revision
586 _UpdateAstString(tokens, node, new_revision)
587 dep_dict.SetNode(dep_key, new_revision, node)
588
Edward Lesmes6f64a052018-03-20 17:35:49 -0400589 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
590 raise ValueError(
591 "Can't use SetRevision for the given gclient dict. It contains no "
592 "formatting information.")
593 tokens = gclient_dict.tokens
594
595 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
596 raise ValueError(
597 "Could not find any dependency called %s." % dep_name)
598
Edward Lesmes6f64a052018-03-20 17:35:49 -0400599 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400600 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400601 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400602 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)