blob: 0ebb1c528facf3feb9e44deedd7e9ec854759700 [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 Lesmes0d9ecc92018-03-23 15:10:58 -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).
60 'url': basestring,
61
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 Lesmes0d9ecc92018-03-23 15:10:58 -0400186def _gclient_eval(node_or_string, vars_dict, expand_vars, filename):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200187 """Safely evaluates a single expression. Returns the result."""
188 _allowed_names = {'None': None, 'True': True, 'False': False}
189 if isinstance(node_or_string, basestring):
190 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
191 if isinstance(node_or_string, ast.Expression):
192 node_or_string = node_or_string.body
193 def _convert(node):
194 if isinstance(node, ast.Str):
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400195 if not expand_vars:
196 return node.s
197 try:
198 return node.s.format(**vars_dict)
199 except KeyError as e:
200 raise ValueError(
201 '%s was used as a variable, but was not declared in the vars dict '
202 '(file %r, line %s)' % (
203 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200204 elif isinstance(node, ast.Num):
205 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200206 elif isinstance(node, ast.Tuple):
207 return tuple(map(_convert, node.elts))
208 elif isinstance(node, ast.List):
209 return list(map(_convert, node.elts))
210 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400211 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200212 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200213 elif isinstance(node, ast.Name):
214 if node.id not in _allowed_names:
215 raise ValueError(
216 'invalid name %r (file %r, line %s)' % (
217 node.id, filename, getattr(node, 'lineno', '<unknown>')))
218 return _allowed_names[node.id]
219 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400220 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200221 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400222 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200223 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400224 if node.keywords or node.starargs or node.kwargs or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200225 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400226 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200227 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400228 arg = _convert(node.args[0])
229 if not isinstance(arg, basestring):
230 raise ValueError(
231 'Var\'s argument must be a variable name (file %r, line %s)' % (
232 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400233 if not expand_vars:
234 return '{%s}' % arg
235 if vars_dict is None:
236 raise ValueError(
237 'vars must be declared before Var can be used (file %r, line %s)'
238 % (filename, getattr(node, 'lineno', '<unknown>')))
239 if arg not in vars_dict:
240 raise ValueError(
241 '%s was used as a variable, but was not declared in the vars dict '
242 '(file %r, line %s)' % (
243 arg, filename, getattr(node, 'lineno', '<unknown>')))
244 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200245 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
246 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200247 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
248 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200249 else:
250 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200251 'unexpected AST node: %s %s (file %r, line %s)' % (
252 node, ast.dump(node), filename,
253 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200254 return _convert(node_or_string)
255
256
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400257def Exec(content, expand_vars, filename='<unknown>', vars_override=None):
258 """Safely execs a set of assignments."""
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200259 node_or_string = ast.parse(content, filename=filename, mode='exec')
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200260 if isinstance(node_or_string, ast.Expression):
261 node_or_string = node_or_string.body
262
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400263 tokens = {
264 token[2]: list(token)
265 for token in tokenize.generate_tokens(
266 cStringIO.StringIO(content).readline)
267 }
268 local_scope = _NodeDict({}, tokens)
269 vars_dict = {}
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200270 def _visit_in_module(node):
271 if isinstance(node, ast.Assign):
272 if len(node.targets) != 1:
273 raise ValueError(
274 'invalid assignment: use exactly one target (file %r, line %s)' % (
275 filename, getattr(node, 'lineno', '<unknown>')))
276 target = node.targets[0]
277 if not isinstance(target, ast.Name):
278 raise ValueError(
279 'invalid assignment: target should be a name (file %r, line %s)' % (
280 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400281 value = _gclient_eval(node.value, vars_dict, expand_vars, filename)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200282
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400283 if target.id in local_scope:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200284 raise ValueError(
285 'invalid assignment: overrides var %r (file %r, line %s)' % (
286 target.id, filename, getattr(node, 'lineno', '<unknown>')))
287
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400288 if target.id == 'vars':
289 vars_dict.update(value)
290 if vars_override:
291 vars_dict.update({
292 k: v
293 for k, v in vars_override.iteritems()
294 if k in vars_dict})
295
296 local_scope.SetNode(target.id, value, node.value)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200297 else:
298 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200299 'unexpected AST node: %s %s (file %r, line %s)' % (
300 node, ast.dump(node), filename,
301 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200302
303 if isinstance(node_or_string, ast.Module):
304 for stmt in node_or_string.body:
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400305 _visit_in_module(stmt)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200306 else:
307 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200308 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200309 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200310 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200311 filename,
312 getattr(node_or_string, 'lineno', '<unknown>')))
313
John Budorick0f7b2002018-01-19 15:46:17 -0800314 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200315
316
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400317def Parse(content, expand_vars, validate_syntax, filename, vars_override=None):
318 """Parses DEPS strings.
319
320 Executes the Python-like string stored in content, resulting in a Python
321 dictionary specifyied by the schema above. Supports syntax validation and
322 variable expansion.
323
324 Args:
325 content: str. DEPS file stored as a string.
326 expand_vars: bool. Whether variables should be expanded to their values.
327 validate_syntax: bool. Whether syntax should be validated using the schema
328 defined above.
329 filename: str. The name of the DEPS file, or a string describing the source
330 of the content, e.g. '<string>', '<unknown>'.
331 vars_override: dict, optional. A dictionary with overrides for the variables
332 defined by the DEPS file.
333
334 Returns:
335 A Python dict with the parsed contents of the DEPS file, as specified by the
336 schema above.
337 """
338 # TODO(ehmaldonado): Make validate_syntax = True the only case
339 if validate_syntax:
340 return Exec(content, expand_vars, filename, vars_override)
341
342 local_scope = {}
343 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
344
345 # If we use 'exec' directly, it complains that 'Parse' contains a nested
346 # function with free variables.
347 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
348 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
349 eval(compile(content, filename, 'exec'), global_scope, local_scope)
350
351 if 'vars' not in local_scope or not expand_vars:
352 return local_scope
353
354 vars_dict = {}
355 vars_dict.update(local_scope['vars'])
356 if vars_override:
357 vars_dict.update({
358 k: v
359 for k, v in vars_override.iteritems()
360 if k in vars_dict
361 })
362
363 def _DeepFormat(node):
364 if isinstance(node, basestring):
365 return node.format(**vars_dict)
366 elif isinstance(node, dict):
367 return {
368 k.format(**vars_dict): _DeepFormat(v)
369 for k, v in node.iteritems()
370 }
371 elif isinstance(node, list):
372 return [_DeepFormat(elem) for elem in node]
373 elif isinstance(node, tuple):
374 return tuple(_DeepFormat(elem) for elem in node)
375 else:
376 return node
377
378 return _DeepFormat(local_scope)
379
380
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200381def EvaluateCondition(condition, variables, referenced_variables=None):
382 """Safely evaluates a boolean condition. Returns the result."""
383 if not referenced_variables:
384 referenced_variables = set()
385 _allowed_names = {'None': None, 'True': True, 'False': False}
386 main_node = ast.parse(condition, mode='eval')
387 if isinstance(main_node, ast.Expression):
388 main_node = main_node.body
389 def _convert(node):
390 if isinstance(node, ast.Str):
391 return node.s
392 elif isinstance(node, ast.Name):
393 if node.id in referenced_variables:
394 raise ValueError(
395 'invalid cyclic reference to %r (inside %r)' % (
396 node.id, condition))
397 elif node.id in _allowed_names:
398 return _allowed_names[node.id]
399 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200400 value = variables[node.id]
401
402 # Allow using "native" types, without wrapping everything in strings.
403 # Note that schema constraints still apply to variables.
404 if not isinstance(value, basestring):
405 return value
406
407 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200408 return EvaluateCondition(
409 variables[node.id],
410 variables,
411 referenced_variables.union([node.id]))
412 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200413 # Implicitly convert unrecognized names to strings.
414 # If we want to change this, we'll need to explicitly distinguish
415 # between arguments for GN to be passed verbatim, and ones to
416 # be evaluated.
417 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200418 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
419 if len(node.values) != 2:
420 raise ValueError(
421 'invalid "or": exactly 2 operands required (inside %r)' % (
422 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200423 left = _convert(node.values[0])
424 right = _convert(node.values[1])
425 if not isinstance(left, bool):
426 raise ValueError(
427 'invalid "or" operand %r (inside %r)' % (left, condition))
428 if not isinstance(right, bool):
429 raise ValueError(
430 'invalid "or" operand %r (inside %r)' % (right, condition))
431 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200432 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
433 if len(node.values) != 2:
434 raise ValueError(
435 'invalid "and": exactly 2 operands required (inside %r)' % (
436 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200437 left = _convert(node.values[0])
438 right = _convert(node.values[1])
439 if not isinstance(left, bool):
440 raise ValueError(
441 'invalid "and" operand %r (inside %r)' % (left, condition))
442 if not isinstance(right, bool):
443 raise ValueError(
444 'invalid "and" operand %r (inside %r)' % (right, condition))
445 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200446 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200447 value = _convert(node.operand)
448 if not isinstance(value, bool):
449 raise ValueError(
450 'invalid "not" operand %r (inside %r)' % (value, condition))
451 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200452 elif isinstance(node, ast.Compare):
453 if len(node.ops) != 1:
454 raise ValueError(
455 'invalid compare: exactly 1 operator required (inside %r)' % (
456 condition))
457 if len(node.comparators) != 1:
458 raise ValueError(
459 'invalid compare: exactly 1 comparator required (inside %r)' % (
460 condition))
461
462 left = _convert(node.left)
463 right = _convert(node.comparators[0])
464
465 if isinstance(node.ops[0], ast.Eq):
466 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700467 if isinstance(node.ops[0], ast.NotEq):
468 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200469
470 raise ValueError(
471 'unexpected operator: %s %s (inside %r)' % (
472 node.ops[0], ast.dump(node), condition))
473 else:
474 raise ValueError(
475 'unexpected AST node: %s %s (inside %r)' % (
476 node, ast.dump(node), condition))
477 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400478
479
480def RenderDEPSFile(gclient_dict):
481 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
482 return tokenize.untokenize(contents)
483
484
485def _UpdateAstString(tokens, node, value):
486 position = node.lineno, node.col_offset
487 tokens[position][1] = repr(value)
488 node.s = value
489
490
491def SetVar(gclient_dict, var_name, value):
492 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
493 raise ValueError(
494 "Can't use SetVar for the given gclient dict. It contains no "
495 "formatting information.")
496 tokens = gclient_dict.tokens
497
498 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
499 raise ValueError(
500 "Could not find any variable called %s." % var_name)
501
502 node = gclient_dict['vars'].GetNode(var_name)
503 if node is None:
504 raise ValueError(
505 "The vars entry for %s has no formatting information." % var_name)
506
507 _UpdateAstString(tokens, node, value)
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400508 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400509
510
511def SetCIPD(gclient_dict, dep_name, package_name, new_version):
512 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
513 raise ValueError(
514 "Can't use SetCIPD for the given gclient dict. It contains no "
515 "formatting information.")
516 tokens = gclient_dict.tokens
517
518 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
519 raise ValueError(
520 "Could not find any dependency called %s." % dep_name)
521
522 # Find the package with the given name
523 packages = [
524 package
525 for package in gclient_dict['deps'][dep_name]['packages']
526 if package['package'] == package_name
527 ]
528 if len(packages) != 1:
529 raise ValueError(
530 "There must be exactly one package with the given name (%s), "
531 "%s were found." % (package_name, len(packages)))
532
533 # TODO(ehmaldonado): Support Var in package's version.
534 node = packages[0].GetNode('version')
535 if node is None:
536 raise ValueError(
537 "The deps entry for %s:%s has no formatting information." %
538 (dep_name, package_name))
539
540 new_version = 'version:' + new_version
541 _UpdateAstString(tokens, node, new_version)
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400542 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400543
544
Edward Lesmes9f531292018-03-20 21:27:15 -0400545def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400546 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
547 raise ValueError(
548 "Can't use SetRevision for the given gclient dict. It contains no "
549 "formatting information.")
550 tokens = gclient_dict.tokens
551
552 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
553 raise ValueError(
554 "Could not find any dependency called %s." % dep_name)
555
556 def _UpdateRevision(dep_dict, dep_key):
557 dep_node = dep_dict.GetNode(dep_key)
558 if dep_node is None:
559 raise ValueError(
560 "The deps entry for %s has no formatting information." % dep_name)
561
562 node = dep_node
563 if isinstance(node, ast.BinOp):
564 node = node.right
565 if isinstance(node, ast.Call):
566 SetVar(gclient_dict, node.args[0].s, new_revision)
567 else:
568 _UpdateAstString(tokens, node, new_revision)
Edward Lesmes0d9ecc92018-03-23 15:10:58 -0400569 value = _gclient_eval(dep_node, gclient_dict.get('vars', None),
570 expand_vars=True, filename='<unknown>')
571 dep_dict.SetNode(dep_key, value, dep_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400572
573 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
574 _UpdateRevision(gclient_dict['deps'][dep_name], 'url')
575 else:
576 _UpdateRevision(gclient_dict['deps'], dep_name)