blob: 602190b081d1a204d765c0199f9857ed9cc724b1 [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
Corentin Walleza68660d2018-09-10 17:33:24 +0000199 # relative to the parent's path, rather than relative to the .gclient file.
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200200 schema.Optional('use_relative_paths'): bool,
201
Corentin Walleza68660d2018-09-10 17:33:24 +0000202 # For recursed-upon sub-dependencies, run their hooks relative to the
203 # parent's path instead of relative to the .gclient file.
204 schema.Optional('use_relative_hooks'): bool,
205
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200206 # Variables that can be referenced using Var() - see 'deps'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400207 schema.Optional('vars'): _NodeDictSchema({
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200208 schema.Optional(basestring): schema.Or(basestring, bool),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400209 }),
210}))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200211
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200212
Edward Lemure05f18d2018-06-08 17:36:53 +0000213def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200214 """Safely evaluates a single expression. Returns the result."""
215 _allowed_names = {'None': None, 'True': True, 'False': False}
216 if isinstance(node_or_string, basestring):
217 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
218 if isinstance(node_or_string, ast.Expression):
219 node_or_string = node_or_string.body
220 def _convert(node):
221 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000222 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000223 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400224 try:
225 return node.s.format(**vars_dict)
226 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000227 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400228 '%s was used as a variable, but was not declared in the vars dict '
229 '(file %r, line %s)' % (
230 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200231 elif isinstance(node, ast.Num):
232 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200233 elif isinstance(node, ast.Tuple):
234 return tuple(map(_convert, node.elts))
235 elif isinstance(node, ast.List):
236 return list(map(_convert, node.elts))
237 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400238 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200239 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200240 elif isinstance(node, ast.Name):
241 if node.id not in _allowed_names:
242 raise ValueError(
243 'invalid name %r (file %r, line %s)' % (
244 node.id, filename, getattr(node, 'lineno', '<unknown>')))
245 return _allowed_names[node.id]
246 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400247 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200248 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400249 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200250 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400251 if node.keywords or node.starargs or node.kwargs or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200252 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400253 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200254 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400255 arg = _convert(node.args[0])
256 if not isinstance(arg, basestring):
257 raise ValueError(
258 'Var\'s argument must be a variable name (file %r, line %s)' % (
259 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400260 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000261 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400262 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000263 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400264 '%s was used as a variable, but was not declared in the vars dict '
265 '(file %r, line %s)' % (
266 arg, filename, getattr(node, 'lineno', '<unknown>')))
267 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200268 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
269 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200270 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
271 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200272 else:
273 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200274 'unexpected AST node: %s %s (file %r, line %s)' % (
275 node, ast.dump(node), filename,
276 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200277 return _convert(node_or_string)
278
279
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000280def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400281 """Safely execs a set of assignments."""
282 def _validate_statement(node, local_scope):
283 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200284 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200285 'unexpected AST node: %s %s (file %r, line %s)' % (
286 node, ast.dump(node), filename,
287 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200288
Edward Lesmes6c24d372018-03-28 12:52:29 -0400289 if len(node.targets) != 1:
290 raise ValueError(
291 'invalid assignment: use exactly one target (file %r, line %s)' % (
292 filename, getattr(node, 'lineno', '<unknown>')))
293
294 target = node.targets[0]
295 if not isinstance(target, ast.Name):
296 raise ValueError(
297 'invalid assignment: target should be a name (file %r, line %s)' % (
298 filename, getattr(node, 'lineno', '<unknown>')))
299 if target.id in local_scope:
300 raise ValueError(
301 'invalid assignment: overrides var %r (file %r, line %s)' % (
302 target.id, filename, getattr(node, 'lineno', '<unknown>')))
303
304 node_or_string = ast.parse(content, filename=filename, mode='exec')
305 if isinstance(node_or_string, ast.Expression):
306 node_or_string = node_or_string.body
307
308 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200309 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200310 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200311 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200312 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200313 filename,
314 getattr(node_or_string, 'lineno', '<unknown>')))
315
Edward Lesmes6c24d372018-03-28 12:52:29 -0400316 statements = {}
317 for statement in node_or_string.body:
318 _validate_statement(statement, statements)
319 statements[statement.targets[0].id] = statement.value
320
321 tokens = {
322 token[2]: list(token)
323 for token in tokenize.generate_tokens(
324 cStringIO.StringIO(content).readline)
325 }
326 local_scope = _NodeDict({}, tokens)
327
328 # Process vars first, so we can expand variables in the rest of the DEPS file.
329 vars_dict = {}
330 if 'vars' in statements:
331 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000332 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400333 local_scope.SetNode('vars', value, vars_statement)
334 # Update the parsed vars with the overrides, but only if they are already
335 # present (overrides do not introduce new variables).
336 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000337
338 if builtin_vars:
339 vars_dict.update(builtin_vars)
340
341 if vars_override:
342 vars_dict.update({
343 k: v
344 for k, v in vars_override.iteritems()
345 if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400346
347 for name, node in statements.iteritems():
Edward Lemure05f18d2018-06-08 17:36:53 +0000348 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400349 local_scope.SetNode(name, value, node)
350
John Budorick0f7b2002018-01-19 15:46:17 -0800351 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200352
353
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000354def ExecLegacy(content, filename='<unknown>', vars_override=None,
355 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400356 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400357 local_scope = {}
358 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
359
360 # If we use 'exec' directly, it complains that 'Parse' contains a nested
361 # function with free variables.
362 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
363 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
364 eval(compile(content, filename, 'exec'), global_scope, local_scope)
365
Edward Lesmes6c24d372018-03-28 12:52:29 -0400366 vars_dict = {}
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000367 vars_dict.update(local_scope.get('vars', {}))
368 if builtin_vars:
369 vars_dict.update(builtin_vars)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400370 if vars_override:
371 vars_dict.update({
372 k: v
373 for k, v in vars_override.iteritems()
374 if k in vars_dict
375 })
376
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000377 if not vars_dict:
378 return local_scope
379
Edward Lesmes6c24d372018-03-28 12:52:29 -0400380 def _DeepFormat(node):
381 if isinstance(node, basestring):
382 return node.format(**vars_dict)
383 elif isinstance(node, dict):
384 return {
385 k.format(**vars_dict): _DeepFormat(v)
386 for k, v in node.iteritems()
387 }
388 elif isinstance(node, list):
389 return [_DeepFormat(elem) for elem in node]
390 elif isinstance(node, tuple):
391 return tuple(_DeepFormat(elem) for elem in node)
392 else:
393 return node
394
395 return _DeepFormat(local_scope)
396
397
Edward Lemur16f4bad2018-05-16 16:53:49 -0400398def _StandardizeDeps(deps_dict, vars_dict):
399 """"Standardizes the deps_dict.
400
401 For each dependency:
402 - Expands the variable in the dependency name.
403 - Ensures the dependency is a dictionary.
404 - Set's the 'dep_type' to be 'git' by default.
405 """
406 new_deps_dict = {}
407 for dep_name, dep_info in deps_dict.items():
408 dep_name = dep_name.format(**vars_dict)
409 if not isinstance(dep_info, collections.Mapping):
410 dep_info = {'url': dep_info}
411 dep_info.setdefault('dep_type', 'git')
412 new_deps_dict[dep_name] = dep_info
413 return new_deps_dict
414
415
416def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
417 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
418
419 The dependencies in os_deps_dict are transformed into conditional dependencies
420 using |'checkout_' + os_name|.
421 If the dependency is already present, the URL and revision must coincide.
422 """
423 for dep_name, dep_info in os_deps_dict.items():
424 # Make this condition very visible, so it's not a silent failure.
425 # It's unclear how to support None override in deps_os.
426 if dep_info['url'] is None:
427 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
428 continue
429
430 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
431 UpdateCondition(dep_info, 'and', os_condition)
432
433 if dep_name in deps_dict:
434 if deps_dict[dep_name]['url'] != dep_info['url']:
435 raise gclient_utils.Error(
436 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
437 'entry (%r).' % (
438 os_name, dep_name, dep_info, deps_dict[dep_name]))
439
440 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
441
442 deps_dict[dep_name] = dep_info
443
444
445def UpdateCondition(info_dict, op, new_condition):
446 """Updates info_dict's condition with |new_condition|.
447
448 An absent value is treated as implicitly True.
449 """
450 curr_condition = info_dict.get('condition')
451 # Easy case: Both are present.
452 if curr_condition and new_condition:
453 info_dict['condition'] = '(%s) %s (%s)' % (
454 curr_condition, op, new_condition)
455 # If |op| == 'and', and at least one condition is present, then use it.
456 elif op == 'and' and (curr_condition or new_condition):
457 info_dict['condition'] = curr_condition or new_condition
458 # Otherwise, no condition should be set
459 elif curr_condition:
460 del info_dict['condition']
461
462
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000463def Parse(content, validate_syntax, filename, vars_override=None,
464 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400465 """Parses DEPS strings.
466
467 Executes the Python-like string stored in content, resulting in a Python
468 dictionary specifyied by the schema above. Supports syntax validation and
469 variable expansion.
470
471 Args:
472 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400473 validate_syntax: bool. Whether syntax should be validated using the schema
474 defined above.
475 filename: str. The name of the DEPS file, or a string describing the source
476 of the content, e.g. '<string>', '<unknown>'.
477 vars_override: dict, optional. A dictionary with overrides for the variables
478 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000479 builtin_vars: dict, optional. A dictionary with variables that are provided
480 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400481
482 Returns:
483 A Python dict with the parsed contents of the DEPS file, as specified by the
484 schema above.
485 """
486 if validate_syntax:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000487 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400488 else:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000489 result = ExecLegacy(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400490
491 vars_dict = result.get('vars', {})
492 if 'deps' in result:
493 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
494
495 if 'deps_os' in result:
496 deps = result.setdefault('deps', {})
497 for os_name, os_deps in result['deps_os'].iteritems():
498 os_deps = _StandardizeDeps(os_deps, vars_dict)
499 _MergeDepsOs(deps, os_deps, os_name)
500 del result['deps_os']
501
502 if 'hooks_os' in result:
503 hooks = result.setdefault('hooks', [])
504 for os_name, os_hooks in result['hooks_os'].iteritems():
505 for hook in os_hooks:
506 UpdateCondition(hook, 'and', 'checkout_' + os_name)
507 hooks.extend(os_hooks)
508 del result['hooks_os']
509
510 return result
511
512
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200513def EvaluateCondition(condition, variables, referenced_variables=None):
514 """Safely evaluates a boolean condition. Returns the result."""
515 if not referenced_variables:
516 referenced_variables = set()
517 _allowed_names = {'None': None, 'True': True, 'False': False}
518 main_node = ast.parse(condition, mode='eval')
519 if isinstance(main_node, ast.Expression):
520 main_node = main_node.body
521 def _convert(node):
522 if isinstance(node, ast.Str):
523 return node.s
524 elif isinstance(node, ast.Name):
525 if node.id in referenced_variables:
526 raise ValueError(
527 'invalid cyclic reference to %r (inside %r)' % (
528 node.id, condition))
529 elif node.id in _allowed_names:
530 return _allowed_names[node.id]
531 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200532 value = variables[node.id]
533
534 # Allow using "native" types, without wrapping everything in strings.
535 # Note that schema constraints still apply to variables.
536 if not isinstance(value, basestring):
537 return value
538
539 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200540 return EvaluateCondition(
541 variables[node.id],
542 variables,
543 referenced_variables.union([node.id]))
544 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200545 # Implicitly convert unrecognized names to strings.
546 # If we want to change this, we'll need to explicitly distinguish
547 # between arguments for GN to be passed verbatim, and ones to
548 # be evaluated.
549 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200550 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
551 if len(node.values) != 2:
552 raise ValueError(
553 'invalid "or": exactly 2 operands required (inside %r)' % (
554 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200555 left = _convert(node.values[0])
556 right = _convert(node.values[1])
557 if not isinstance(left, bool):
558 raise ValueError(
559 'invalid "or" operand %r (inside %r)' % (left, condition))
560 if not isinstance(right, bool):
561 raise ValueError(
562 'invalid "or" operand %r (inside %r)' % (right, condition))
563 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200564 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
565 if len(node.values) != 2:
566 raise ValueError(
567 'invalid "and": exactly 2 operands required (inside %r)' % (
568 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200569 left = _convert(node.values[0])
570 right = _convert(node.values[1])
571 if not isinstance(left, bool):
572 raise ValueError(
573 'invalid "and" operand %r (inside %r)' % (left, condition))
574 if not isinstance(right, bool):
575 raise ValueError(
576 'invalid "and" operand %r (inside %r)' % (right, condition))
577 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200578 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200579 value = _convert(node.operand)
580 if not isinstance(value, bool):
581 raise ValueError(
582 'invalid "not" operand %r (inside %r)' % (value, condition))
583 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200584 elif isinstance(node, ast.Compare):
585 if len(node.ops) != 1:
586 raise ValueError(
587 'invalid compare: exactly 1 operator required (inside %r)' % (
588 condition))
589 if len(node.comparators) != 1:
590 raise ValueError(
591 'invalid compare: exactly 1 comparator required (inside %r)' % (
592 condition))
593
594 left = _convert(node.left)
595 right = _convert(node.comparators[0])
596
597 if isinstance(node.ops[0], ast.Eq):
598 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700599 if isinstance(node.ops[0], ast.NotEq):
600 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200601
602 raise ValueError(
603 'unexpected operator: %s %s (inside %r)' % (
604 node.ops[0], ast.dump(node), condition))
605 else:
606 raise ValueError(
607 'unexpected AST node: %s %s (inside %r)' % (
608 node, ast.dump(node), condition))
609 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400610
611
612def RenderDEPSFile(gclient_dict):
613 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
614 return tokenize.untokenize(contents)
615
616
617def _UpdateAstString(tokens, node, value):
618 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000619 quote_char = ''
620 if isinstance(node, ast.Str):
621 quote_char = tokens[position][1][0]
Edward Lesmes62af4e42018-03-30 18:15:44 -0400622 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400623 node.s = value
624
625
Edward Lesmes3d993812018-04-02 12:52:49 -0400626def _ShiftLinesInTokens(tokens, delta, start):
627 new_tokens = {}
628 for token in tokens.values():
629 if token[2][0] >= start:
630 token[2] = token[2][0] + delta, token[2][1]
631 token[3] = token[3][0] + delta, token[3][1]
632 new_tokens[token[2]] = token
633 return new_tokens
634
635
636def AddVar(gclient_dict, var_name, value):
637 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
638 raise ValueError(
639 "Can't use SetVar for the given gclient dict. It contains no "
640 "formatting information.")
641
642 if 'vars' not in gclient_dict:
643 raise KeyError("vars dict is not defined.")
644
645 if var_name in gclient_dict['vars']:
646 raise ValueError(
647 "%s has already been declared in the vars dict. Consider using SetVar "
648 "instead." % var_name)
649
650 if not gclient_dict['vars']:
651 raise ValueError('vars dict is empty. This is not yet supported.')
652
Edward Lesmes8d626572018-04-05 17:53:10 -0400653 # We will attempt to add the var right after 'vars = {'.
654 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400655 if node is None:
656 raise ValueError(
657 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400658 line = node.lineno + 1
659
660 # We will try to match the new var's indentation to the next variable.
661 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400662
663 # We use a minimal Python dictionary, so that ast can parse it.
664 var_content = '{\n%s"%s": "%s",\n}' % (' ' * col, var_name, value)
665 var_ast = ast.parse(var_content).body[0].value
666
667 # Set the ast nodes for the key and value.
668 vars_node = gclient_dict.GetNode('vars')
669
670 var_name_node = var_ast.keys[0]
671 var_name_node.lineno += line - 2
672 vars_node.keys.insert(0, var_name_node)
673
674 value_node = var_ast.values[0]
675 value_node.lineno += line - 2
676 vars_node.values.insert(0, value_node)
677
678 # Update the tokens.
679 var_tokens = list(tokenize.generate_tokens(
680 cStringIO.StringIO(var_content).readline))
681 var_tokens = {
682 token[2]: list(token)
683 # Ignore the tokens corresponding to braces and new lines.
684 for token in var_tokens[2:-2]
685 }
686
687 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
688 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
689
690
Edward Lesmes6f64a052018-03-20 17:35:49 -0400691def SetVar(gclient_dict, var_name, value):
692 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
693 raise ValueError(
694 "Can't use SetVar for the given gclient dict. It contains no "
695 "formatting information.")
696 tokens = gclient_dict.tokens
697
Edward Lesmes3d993812018-04-02 12:52:49 -0400698 if 'vars' not in gclient_dict:
699 raise KeyError("vars dict is not defined.")
700
701 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400702 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400703 "%s has not been declared in the vars dict. Consider using AddVar "
704 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400705
706 node = gclient_dict['vars'].GetNode(var_name)
707 if node is None:
708 raise ValueError(
709 "The vars entry for %s has no formatting information." % var_name)
710
711 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400712 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400713
714
715def SetCIPD(gclient_dict, dep_name, package_name, new_version):
716 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
717 raise ValueError(
718 "Can't use SetCIPD for the given gclient dict. It contains no "
719 "formatting information.")
720 tokens = gclient_dict.tokens
721
722 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400723 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400724 "Could not find any dependency called %s." % dep_name)
725
726 # Find the package with the given name
727 packages = [
728 package
729 for package in gclient_dict['deps'][dep_name]['packages']
730 if package['package'] == package_name
731 ]
732 if len(packages) != 1:
733 raise ValueError(
734 "There must be exactly one package with the given name (%s), "
735 "%s were found." % (package_name, len(packages)))
736
737 # TODO(ehmaldonado): Support Var in package's version.
738 node = packages[0].GetNode('version')
739 if node is None:
740 raise ValueError(
741 "The deps entry for %s:%s has no formatting information." %
742 (dep_name, package_name))
743
Edward Lesmes6f64a052018-03-20 17:35:49 -0400744 _UpdateAstString(tokens, node, new_version)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400745 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400746
747
Edward Lesmes9f531292018-03-20 21:27:15 -0400748def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400749 def _GetVarName(node):
750 if isinstance(node, ast.Call):
751 return node.args[0].s
752 elif node.s.endswith('}'):
753 last_brace = node.s.rfind('{')
754 return node.s[last_brace+1:-1]
755 return None
756
757 def _UpdateRevision(dep_dict, dep_key, new_revision):
758 dep_node = dep_dict.GetNode(dep_key)
759 if dep_node is None:
760 raise ValueError(
761 "The deps entry for %s has no formatting information." % dep_name)
762
763 node = dep_node
764 if isinstance(node, ast.BinOp):
765 node = node.right
766
767 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
768 raise ValueError(
769 "Unsupported dependency revision format. Please file a bug.")
770
771 var_name = _GetVarName(node)
772 if var_name is not None:
773 SetVar(gclient_dict, var_name, new_revision)
774 else:
775 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400776 # '@' is part of the last string, which we want to modify. Discard
777 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400778 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400779 elif '@' not in dep_dict[dep_key]:
780 # '@' is not part of the URL at all. This mean the dependency is
781 # unpinned and we should pin it.
782 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400783 _UpdateAstString(tokens, node, new_revision)
784 dep_dict.SetNode(dep_key, new_revision, node)
785
Edward Lesmes6f64a052018-03-20 17:35:49 -0400786 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
787 raise ValueError(
788 "Can't use SetRevision for the given gclient dict. It contains no "
789 "formatting information.")
790 tokens = gclient_dict.tokens
791
792 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400793 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400794 "Could not find any dependency called %s." % dep_name)
795
Edward Lesmes6f64a052018-03-20 17:35:49 -0400796 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400797 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400798 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400799 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400800
801
802def GetVar(gclient_dict, var_name):
803 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
804 raise KeyError(
805 "Could not find any variable called %s." % var_name)
806
807 return gclient_dict['vars'][var_name]
808
809
810def GetCIPD(gclient_dict, dep_name, package_name):
811 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
812 raise KeyError(
813 "Could not find any dependency called %s." % dep_name)
814
815 # Find the package with the given name
816 packages = [
817 package
818 for package in gclient_dict['deps'][dep_name]['packages']
819 if package['package'] == package_name
820 ]
821 if len(packages) != 1:
822 raise ValueError(
823 "There must be exactly one package with the given name (%s), "
824 "%s were found." % (package_name, len(packages)))
825
Edward Lemura92b9612018-07-03 02:34:32 +0000826 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400827
828
829def GetRevision(gclient_dict, dep_name):
830 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
831 raise KeyError(
832 "Could not find any dependency called %s." % dep_name)
833
834 dep = gclient_dict['deps'][dep_name]
835 if dep is None:
836 return None
837 elif isinstance(dep, basestring):
838 _, _, revision = dep.partition('@')
839 return revision or None
840 elif isinstance(dep, collections.Mapping) and 'url' in dep:
841 _, _, revision = dep['url'].partition('@')
842 return revision or None
843 else:
844 raise ValueError(
845 '%s is not a valid git dependency.' % dep_name)