blob: 3f561cc8e8f5068f9bf911394d786ac342ce5766 [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
Edward Lemura1e4d482018-12-17 19:01:03 +000025 def __repr__(self):
26 return self.__str__()
27
Edward Lesmes6f64a052018-03-20 17:35:49 -040028 def __getitem__(self, key):
29 return self.data[key][0]
30
31 def __setitem__(self, key, value):
32 self.data[key] = (value, None)
33
34 def __delitem__(self, key):
35 del self.data[key]
36
37 def __iter__(self):
38 return iter(self.data)
39
40 def __len__(self):
41 return len(self.data)
42
Edward Lesmes3d993812018-04-02 12:52:49 -040043 def MoveTokens(self, origin, delta):
44 if self.tokens:
45 new_tokens = {}
46 for pos, token in self.tokens.iteritems():
47 if pos[0] >= origin:
48 pos = (pos[0] + delta, pos[1])
49 token = token[:2] + (pos,) + token[3:]
50 new_tokens[pos] = token
51
52 for value, node in self.data.values():
53 if node.lineno >= origin:
54 node.lineno += delta
55 if isinstance(value, _NodeDict):
56 value.MoveTokens(origin, delta)
57
Edward Lesmes6f64a052018-03-20 17:35:49 -040058 def GetNode(self, key):
59 return self.data[key][1]
60
Edward Lesmes6c24d372018-03-28 12:52:29 -040061 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040062 self.data[key] = (value, node)
63
64
65def _NodeDictSchema(dict_schema):
66 """Validate dict_schema after converting _NodeDict to a regular dict."""
67 def validate(d):
68 schema.Schema(dict_schema).validate(dict(d))
69 return True
70 return validate
71
72
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020073# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -040074_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020075 schema.Optional(basestring): schema.Or(
76 None,
77 basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040078 _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020079 # Repo and revision to check out under the path
80 # (same as if no dict was used).
Michael Moss012013e2018-03-30 17:03:19 -070081 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020082
83 # Optional condition string. The dep will only be processed
84 # if the condition evaluates to True.
85 schema.Optional('condition'): basestring,
John Budorick0f7b2002018-01-19 15:46:17 -080086
87 schema.Optional('dep_type', default='git'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040088 }),
John Budorick0f7b2002018-01-19 15:46:17 -080089 # CIPD package.
Edward Lesmes6f64a052018-03-20 17:35:49 -040090 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080091 'packages': [
Edward Lesmes6f64a052018-03-20 17:35:49 -040092 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080093 'package': basestring,
94
95 'version': basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040096 })
John Budorick0f7b2002018-01-19 15:46:17 -080097 ],
98
99 schema.Optional('condition'): basestring,
100
101 schema.Optional('dep_type', default='cipd'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400102 }),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200103 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400104})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200105
Edward Lesmes6f64a052018-03-20 17:35:49 -0400106_GCLIENT_HOOKS_SCHEMA = [_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200107 # Hook action: list of command-line arguments to invoke.
108 'action': [basestring],
109
110 # Name of the hook. Doesn't affect operation.
111 schema.Optional('name'): basestring,
112
113 # Hook pattern (regex). Originally intended to limit some hooks to run
114 # only when files matching the pattern have changed. In practice, with git,
115 # gclient runs all the hooks regardless of this field.
116 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200117
118 # Working directory where to execute the hook.
119 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200120
121 # Optional condition string. The hook will only be run
122 # if the condition evaluates to True.
123 schema.Optional('condition'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400124})]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200125
Edward Lesmes6f64a052018-03-20 17:35:49 -0400126_GCLIENT_SCHEMA = schema.Schema(_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200127 # List of host names from which dependencies are allowed (whitelist).
128 # NOTE: when not present, all hosts are allowed.
129 # NOTE: scoped to current DEPS file, not recursive.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200130 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200131
132 # Mapping from paths to repo and revision to check out under that path.
133 # Applying this mapping to the on-disk checkout is the main purpose
134 # of gclient, and also why the config file is called DEPS.
135 #
136 # The following functions are allowed:
137 #
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200138 # Var(): allows variable substitution (either from 'vars' dict below,
139 # or command-line override)
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200140 schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200141
142 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200143 # Also see 'target_os'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400144 schema.Optional('deps_os'): _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200145 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400146 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200147
Michael Moss848c86e2018-05-03 16:05:50 -0700148 # Dependency to get gclient_gn_args* settings from. This allows these values
149 # to be set in a recursedeps file, rather than requiring that they exist in
150 # the top-level solution.
151 schema.Optional('gclient_gn_args_from'): basestring,
152
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200153 # Path to GN args file to write selected variables.
154 schema.Optional('gclient_gn_args_file'): basestring,
155
156 # Subset of variables to write to the GN args file (see above).
157 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
158
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200159 # Hooks executed after gclient sync (unless suppressed), or explicitly
160 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
161 # Also see 'pre_deps_hooks'.
162 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
163
Scott Grahamc4826742017-05-11 16:59:23 -0700164 # Similar to 'hooks', also keyed by OS.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400165 schema.Optional('hooks_os'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200166 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
Edward Lesmes6f64a052018-03-20 17:35:49 -0400167 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700168
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200169 # Rules which #includes are allowed in the directory.
170 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200171 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200172
173 # Hooks executed before processing DEPS. See 'hooks' for more details.
174 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
175
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200176 # Recursion limit for nested DEPS.
177 schema.Optional('recursion'): int,
178
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200179 # Whitelists deps for which recursion should be enabled.
180 schema.Optional('recursedeps'): [
Paweł Hajdan, Jr05fec032017-05-30 23:04:23 +0200181 schema.Optional(schema.Or(
182 basestring,
183 (basestring, basestring),
184 [basestring, basestring]
185 )),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200186 ],
187
188 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200189 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200190
191 # Mapping from paths to include rules specific for that path.
192 # See 'include_rules' for more details.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400193 schema.Optional('specific_include_rules'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200194 schema.Optional(basestring): [basestring]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400195 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200196
197 # List of additional OS names to consider when selecting dependencies
198 # from deps_os.
199 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200200
201 # For recursed-upon sub-dependencies, check out their own dependencies
Corentin Walleza68660d2018-09-10 17:33:24 +0000202 # relative to the parent's path, rather than relative to the .gclient file.
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200203 schema.Optional('use_relative_paths'): bool,
204
Corentin Walleza68660d2018-09-10 17:33:24 +0000205 # For recursed-upon sub-dependencies, run their hooks relative to the
206 # parent's path instead of relative to the .gclient file.
207 schema.Optional('use_relative_hooks'): bool,
208
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200209 # Variables that can be referenced using Var() - see 'deps'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400210 schema.Optional('vars'): _NodeDictSchema({
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200211 schema.Optional(basestring): schema.Or(basestring, bool),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400212 }),
213}))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200214
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200215
Edward Lemure05f18d2018-06-08 17:36:53 +0000216def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200217 """Safely evaluates a single expression. Returns the result."""
218 _allowed_names = {'None': None, 'True': True, 'False': False}
219 if isinstance(node_or_string, basestring):
220 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
221 if isinstance(node_or_string, ast.Expression):
222 node_or_string = node_or_string.body
223 def _convert(node):
224 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000225 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000226 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400227 try:
228 return node.s.format(**vars_dict)
229 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000230 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400231 '%s was used as a variable, but was not declared in the vars dict '
232 '(file %r, line %s)' % (
233 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200234 elif isinstance(node, ast.Num):
235 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200236 elif isinstance(node, ast.Tuple):
237 return tuple(map(_convert, node.elts))
238 elif isinstance(node, ast.List):
239 return list(map(_convert, node.elts))
240 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400241 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200242 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200243 elif isinstance(node, ast.Name):
244 if node.id not in _allowed_names:
245 raise ValueError(
246 'invalid name %r (file %r, line %s)' % (
247 node.id, filename, getattr(node, 'lineno', '<unknown>')))
248 return _allowed_names[node.id]
249 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400250 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200251 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400252 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200253 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400254 if node.keywords or node.starargs or node.kwargs or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200255 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400256 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200257 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400258 arg = _convert(node.args[0])
259 if not isinstance(arg, basestring):
260 raise ValueError(
261 'Var\'s argument must be a variable name (file %r, line %s)' % (
262 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400263 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000264 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400265 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000266 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400267 '%s was used as a variable, but was not declared in the vars dict '
268 '(file %r, line %s)' % (
269 arg, filename, getattr(node, 'lineno', '<unknown>')))
270 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200271 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
272 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200273 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
274 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200275 else:
276 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200277 'unexpected AST node: %s %s (file %r, line %s)' % (
278 node, ast.dump(node), filename,
279 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200280 return _convert(node_or_string)
281
282
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000283def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400284 """Safely execs a set of assignments."""
285 def _validate_statement(node, local_scope):
286 if not isinstance(node, ast.Assign):
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)' % (
289 node, ast.dump(node), filename,
290 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200291
Edward Lesmes6c24d372018-03-28 12:52:29 -0400292 if len(node.targets) != 1:
293 raise ValueError(
294 'invalid assignment: use exactly one target (file %r, line %s)' % (
295 filename, getattr(node, 'lineno', '<unknown>')))
296
297 target = node.targets[0]
298 if not isinstance(target, ast.Name):
299 raise ValueError(
300 'invalid assignment: target should be a name (file %r, line %s)' % (
301 filename, getattr(node, 'lineno', '<unknown>')))
302 if target.id in local_scope:
303 raise ValueError(
304 'invalid assignment: overrides var %r (file %r, line %s)' % (
305 target.id, filename, getattr(node, 'lineno', '<unknown>')))
306
307 node_or_string = ast.parse(content, filename=filename, mode='exec')
308 if isinstance(node_or_string, ast.Expression):
309 node_or_string = node_or_string.body
310
311 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200312 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200313 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200314 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200315 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200316 filename,
317 getattr(node_or_string, 'lineno', '<unknown>')))
318
Edward Lesmes6c24d372018-03-28 12:52:29 -0400319 statements = {}
320 for statement in node_or_string.body:
321 _validate_statement(statement, statements)
322 statements[statement.targets[0].id] = statement.value
323
324 tokens = {
325 token[2]: list(token)
326 for token in tokenize.generate_tokens(
327 cStringIO.StringIO(content).readline)
328 }
329 local_scope = _NodeDict({}, tokens)
330
331 # Process vars first, so we can expand variables in the rest of the DEPS file.
332 vars_dict = {}
333 if 'vars' in statements:
334 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000335 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400336 local_scope.SetNode('vars', value, vars_statement)
337 # Update the parsed vars with the overrides, but only if they are already
338 # present (overrides do not introduce new variables).
339 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000340
341 if builtin_vars:
342 vars_dict.update(builtin_vars)
343
344 if vars_override:
345 vars_dict.update({
346 k: v
347 for k, v in vars_override.iteritems()
348 if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400349
350 for name, node in statements.iteritems():
Edward Lemure05f18d2018-06-08 17:36:53 +0000351 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400352 local_scope.SetNode(name, value, node)
353
John Budorick0f7b2002018-01-19 15:46:17 -0800354 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200355
356
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000357def ExecLegacy(content, filename='<unknown>', vars_override=None,
358 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400359 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400360 local_scope = {}
361 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
362
363 # If we use 'exec' directly, it complains that 'Parse' contains a nested
364 # function with free variables.
365 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
366 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
367 eval(compile(content, filename, 'exec'), global_scope, local_scope)
368
Edward Lesmes6c24d372018-03-28 12:52:29 -0400369 vars_dict = {}
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000370 vars_dict.update(local_scope.get('vars', {}))
371 if builtin_vars:
372 vars_dict.update(builtin_vars)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400373 if vars_override:
374 vars_dict.update({
375 k: v
376 for k, v in vars_override.iteritems()
377 if k in vars_dict
378 })
379
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000380 if not vars_dict:
381 return local_scope
382
Edward Lesmes6c24d372018-03-28 12:52:29 -0400383 def _DeepFormat(node):
384 if isinstance(node, basestring):
385 return node.format(**vars_dict)
386 elif isinstance(node, dict):
387 return {
388 k.format(**vars_dict): _DeepFormat(v)
389 for k, v in node.iteritems()
390 }
391 elif isinstance(node, list):
392 return [_DeepFormat(elem) for elem in node]
393 elif isinstance(node, tuple):
394 return tuple(_DeepFormat(elem) for elem in node)
395 else:
396 return node
397
398 return _DeepFormat(local_scope)
399
400
Edward Lemur16f4bad2018-05-16 16:53:49 -0400401def _StandardizeDeps(deps_dict, vars_dict):
402 """"Standardizes the deps_dict.
403
404 For each dependency:
405 - Expands the variable in the dependency name.
406 - Ensures the dependency is a dictionary.
407 - Set's the 'dep_type' to be 'git' by default.
408 """
409 new_deps_dict = {}
410 for dep_name, dep_info in deps_dict.items():
411 dep_name = dep_name.format(**vars_dict)
412 if not isinstance(dep_info, collections.Mapping):
413 dep_info = {'url': dep_info}
414 dep_info.setdefault('dep_type', 'git')
415 new_deps_dict[dep_name] = dep_info
416 return new_deps_dict
417
418
419def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
420 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
421
422 The dependencies in os_deps_dict are transformed into conditional dependencies
423 using |'checkout_' + os_name|.
424 If the dependency is already present, the URL and revision must coincide.
425 """
426 for dep_name, dep_info in os_deps_dict.items():
427 # Make this condition very visible, so it's not a silent failure.
428 # It's unclear how to support None override in deps_os.
429 if dep_info['url'] is None:
430 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
431 continue
432
433 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
434 UpdateCondition(dep_info, 'and', os_condition)
435
436 if dep_name in deps_dict:
437 if deps_dict[dep_name]['url'] != dep_info['url']:
438 raise gclient_utils.Error(
439 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
440 'entry (%r).' % (
441 os_name, dep_name, dep_info, deps_dict[dep_name]))
442
443 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
444
445 deps_dict[dep_name] = dep_info
446
447
448def UpdateCondition(info_dict, op, new_condition):
449 """Updates info_dict's condition with |new_condition|.
450
451 An absent value is treated as implicitly True.
452 """
453 curr_condition = info_dict.get('condition')
454 # Easy case: Both are present.
455 if curr_condition and new_condition:
456 info_dict['condition'] = '(%s) %s (%s)' % (
457 curr_condition, op, new_condition)
458 # If |op| == 'and', and at least one condition is present, then use it.
459 elif op == 'and' and (curr_condition or new_condition):
460 info_dict['condition'] = curr_condition or new_condition
461 # Otherwise, no condition should be set
462 elif curr_condition:
463 del info_dict['condition']
464
465
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000466def Parse(content, validate_syntax, filename, vars_override=None,
467 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400468 """Parses DEPS strings.
469
470 Executes the Python-like string stored in content, resulting in a Python
471 dictionary specifyied by the schema above. Supports syntax validation and
472 variable expansion.
473
474 Args:
475 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400476 validate_syntax: bool. Whether syntax should be validated using the schema
477 defined above.
478 filename: str. The name of the DEPS file, or a string describing the source
479 of the content, e.g. '<string>', '<unknown>'.
480 vars_override: dict, optional. A dictionary with overrides for the variables
481 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000482 builtin_vars: dict, optional. A dictionary with variables that are provided
483 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400484
485 Returns:
486 A Python dict with the parsed contents of the DEPS file, as specified by the
487 schema above.
488 """
489 if validate_syntax:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000490 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400491 else:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000492 result = ExecLegacy(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400493
494 vars_dict = result.get('vars', {})
495 if 'deps' in result:
496 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
497
498 if 'deps_os' in result:
499 deps = result.setdefault('deps', {})
500 for os_name, os_deps in result['deps_os'].iteritems():
501 os_deps = _StandardizeDeps(os_deps, vars_dict)
502 _MergeDepsOs(deps, os_deps, os_name)
503 del result['deps_os']
504
505 if 'hooks_os' in result:
506 hooks = result.setdefault('hooks', [])
507 for os_name, os_hooks in result['hooks_os'].iteritems():
508 for hook in os_hooks:
509 UpdateCondition(hook, 'and', 'checkout_' + os_name)
510 hooks.extend(os_hooks)
511 del result['hooks_os']
512
513 return result
514
515
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200516def EvaluateCondition(condition, variables, referenced_variables=None):
517 """Safely evaluates a boolean condition. Returns the result."""
518 if not referenced_variables:
519 referenced_variables = set()
520 _allowed_names = {'None': None, 'True': True, 'False': False}
521 main_node = ast.parse(condition, mode='eval')
522 if isinstance(main_node, ast.Expression):
523 main_node = main_node.body
524 def _convert(node):
525 if isinstance(node, ast.Str):
526 return node.s
527 elif isinstance(node, ast.Name):
528 if node.id in referenced_variables:
529 raise ValueError(
530 'invalid cyclic reference to %r (inside %r)' % (
531 node.id, condition))
532 elif node.id in _allowed_names:
533 return _allowed_names[node.id]
534 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200535 value = variables[node.id]
536
537 # Allow using "native" types, without wrapping everything in strings.
538 # Note that schema constraints still apply to variables.
539 if not isinstance(value, basestring):
540 return value
541
542 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200543 return EvaluateCondition(
544 variables[node.id],
545 variables,
546 referenced_variables.union([node.id]))
547 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200548 # Implicitly convert unrecognized names to strings.
549 # If we want to change this, we'll need to explicitly distinguish
550 # between arguments for GN to be passed verbatim, and ones to
551 # be evaluated.
552 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200553 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
554 if len(node.values) != 2:
555 raise ValueError(
556 'invalid "or": exactly 2 operands required (inside %r)' % (
557 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200558 left = _convert(node.values[0])
559 right = _convert(node.values[1])
560 if not isinstance(left, bool):
561 raise ValueError(
562 'invalid "or" operand %r (inside %r)' % (left, condition))
563 if not isinstance(right, bool):
564 raise ValueError(
565 'invalid "or" operand %r (inside %r)' % (right, condition))
566 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200567 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
568 if len(node.values) != 2:
569 raise ValueError(
570 'invalid "and": exactly 2 operands required (inside %r)' % (
571 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200572 left = _convert(node.values[0])
573 right = _convert(node.values[1])
574 if not isinstance(left, bool):
575 raise ValueError(
576 'invalid "and" operand %r (inside %r)' % (left, condition))
577 if not isinstance(right, bool):
578 raise ValueError(
579 'invalid "and" operand %r (inside %r)' % (right, condition))
580 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200581 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200582 value = _convert(node.operand)
583 if not isinstance(value, bool):
584 raise ValueError(
585 'invalid "not" operand %r (inside %r)' % (value, condition))
586 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200587 elif isinstance(node, ast.Compare):
588 if len(node.ops) != 1:
589 raise ValueError(
590 'invalid compare: exactly 1 operator required (inside %r)' % (
591 condition))
592 if len(node.comparators) != 1:
593 raise ValueError(
594 'invalid compare: exactly 1 comparator required (inside %r)' % (
595 condition))
596
597 left = _convert(node.left)
598 right = _convert(node.comparators[0])
599
600 if isinstance(node.ops[0], ast.Eq):
601 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700602 if isinstance(node.ops[0], ast.NotEq):
603 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200604
605 raise ValueError(
606 'unexpected operator: %s %s (inside %r)' % (
607 node.ops[0], ast.dump(node), condition))
608 else:
609 raise ValueError(
610 'unexpected AST node: %s %s (inside %r)' % (
611 node, ast.dump(node), condition))
612 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400613
614
615def RenderDEPSFile(gclient_dict):
616 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
617 return tokenize.untokenize(contents)
618
619
620def _UpdateAstString(tokens, node, value):
621 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000622 quote_char = ''
623 if isinstance(node, ast.Str):
624 quote_char = tokens[position][1][0]
Edward Lesmes62af4e42018-03-30 18:15:44 -0400625 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400626 node.s = value
627
628
Edward Lesmes3d993812018-04-02 12:52:49 -0400629def _ShiftLinesInTokens(tokens, delta, start):
630 new_tokens = {}
631 for token in tokens.values():
632 if token[2][0] >= start:
633 token[2] = token[2][0] + delta, token[2][1]
634 token[3] = token[3][0] + delta, token[3][1]
635 new_tokens[token[2]] = token
636 return new_tokens
637
638
639def AddVar(gclient_dict, var_name, value):
640 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
641 raise ValueError(
642 "Can't use SetVar for the given gclient dict. It contains no "
643 "formatting information.")
644
645 if 'vars' not in gclient_dict:
646 raise KeyError("vars dict is not defined.")
647
648 if var_name in gclient_dict['vars']:
649 raise ValueError(
650 "%s has already been declared in the vars dict. Consider using SetVar "
651 "instead." % var_name)
652
653 if not gclient_dict['vars']:
654 raise ValueError('vars dict is empty. This is not yet supported.')
655
Edward Lesmes8d626572018-04-05 17:53:10 -0400656 # We will attempt to add the var right after 'vars = {'.
657 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400658 if node is None:
659 raise ValueError(
660 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400661 line = node.lineno + 1
662
663 # We will try to match the new var's indentation to the next variable.
664 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400665
666 # We use a minimal Python dictionary, so that ast can parse it.
667 var_content = '{\n%s"%s": "%s",\n}' % (' ' * col, var_name, value)
668 var_ast = ast.parse(var_content).body[0].value
669
670 # Set the ast nodes for the key and value.
671 vars_node = gclient_dict.GetNode('vars')
672
673 var_name_node = var_ast.keys[0]
674 var_name_node.lineno += line - 2
675 vars_node.keys.insert(0, var_name_node)
676
677 value_node = var_ast.values[0]
678 value_node.lineno += line - 2
679 vars_node.values.insert(0, value_node)
680
681 # Update the tokens.
682 var_tokens = list(tokenize.generate_tokens(
683 cStringIO.StringIO(var_content).readline))
684 var_tokens = {
685 token[2]: list(token)
686 # Ignore the tokens corresponding to braces and new lines.
687 for token in var_tokens[2:-2]
688 }
689
690 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
691 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
692
693
Edward Lesmes6f64a052018-03-20 17:35:49 -0400694def SetVar(gclient_dict, var_name, value):
695 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
696 raise ValueError(
697 "Can't use SetVar for the given gclient dict. It contains no "
698 "formatting information.")
699 tokens = gclient_dict.tokens
700
Edward Lesmes3d993812018-04-02 12:52:49 -0400701 if 'vars' not in gclient_dict:
702 raise KeyError("vars dict is not defined.")
703
704 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400705 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400706 "%s has not been declared in the vars dict. Consider using AddVar "
707 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400708
709 node = gclient_dict['vars'].GetNode(var_name)
710 if node is None:
711 raise ValueError(
712 "The vars entry for %s has no formatting information." % var_name)
713
714 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400715 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400716
717
Edward Lemura1e4d482018-12-17 19:01:03 +0000718def _GetVarName(node):
719 if isinstance(node, ast.Call):
720 return node.args[0].s
721 elif node.s.endswith('}'):
722 last_brace = node.s.rfind('{')
723 return node.s[last_brace+1:-1]
724 return None
725
726
Edward Lesmes6f64a052018-03-20 17:35:49 -0400727def SetCIPD(gclient_dict, dep_name, package_name, new_version):
728 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
729 raise ValueError(
730 "Can't use SetCIPD for the given gclient dict. It contains no "
731 "formatting information.")
732 tokens = gclient_dict.tokens
733
734 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400735 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400736 "Could not find any dependency called %s." % dep_name)
737
738 # Find the package with the given name
739 packages = [
740 package
741 for package in gclient_dict['deps'][dep_name]['packages']
742 if package['package'] == package_name
743 ]
744 if len(packages) != 1:
745 raise ValueError(
746 "There must be exactly one package with the given name (%s), "
747 "%s were found." % (package_name, len(packages)))
748
749 # TODO(ehmaldonado): Support Var in package's version.
750 node = packages[0].GetNode('version')
751 if node is None:
752 raise ValueError(
753 "The deps entry for %s:%s has no formatting information." %
754 (dep_name, package_name))
755
Edward Lemura1e4d482018-12-17 19:01:03 +0000756 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
757 raise ValueError(
758 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000759 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000760
761 var_name = _GetVarName(node)
762 if var_name is not None:
763 SetVar(gclient_dict, var_name, new_version)
764 else:
765 _UpdateAstString(tokens, node, new_version)
766 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400767
768
Edward Lesmes9f531292018-03-20 21:27:15 -0400769def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400770 def _UpdateRevision(dep_dict, dep_key, new_revision):
771 dep_node = dep_dict.GetNode(dep_key)
772 if dep_node is None:
773 raise ValueError(
774 "The deps entry for %s has no formatting information." % dep_name)
775
776 node = dep_node
777 if isinstance(node, ast.BinOp):
778 node = node.right
779
780 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
781 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000782 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000783 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400784
785 var_name = _GetVarName(node)
786 if var_name is not None:
787 SetVar(gclient_dict, var_name, new_revision)
788 else:
789 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400790 # '@' is part of the last string, which we want to modify. Discard
791 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400792 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400793 elif '@' not in dep_dict[dep_key]:
794 # '@' is not part of the URL at all. This mean the dependency is
795 # unpinned and we should pin it.
796 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400797 _UpdateAstString(tokens, node, new_revision)
798 dep_dict.SetNode(dep_key, new_revision, node)
799
Edward Lesmes6f64a052018-03-20 17:35:49 -0400800 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
801 raise ValueError(
802 "Can't use SetRevision for the given gclient dict. It contains no "
803 "formatting information.")
804 tokens = gclient_dict.tokens
805
806 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400807 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400808 "Could not find any dependency called %s." % dep_name)
809
Edward Lesmes6f64a052018-03-20 17:35:49 -0400810 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400811 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400812 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400813 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400814
815
816def GetVar(gclient_dict, var_name):
817 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
818 raise KeyError(
819 "Could not find any variable called %s." % var_name)
820
821 return gclient_dict['vars'][var_name]
822
823
824def GetCIPD(gclient_dict, dep_name, package_name):
825 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
826 raise KeyError(
827 "Could not find any dependency called %s." % dep_name)
828
829 # Find the package with the given name
830 packages = [
831 package
832 for package in gclient_dict['deps'][dep_name]['packages']
833 if package['package'] == package_name
834 ]
835 if len(packages) != 1:
836 raise ValueError(
837 "There must be exactly one package with the given name (%s), "
838 "%s were found." % (package_name, len(packages)))
839
Edward Lemura92b9612018-07-03 02:34:32 +0000840 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400841
842
843def GetRevision(gclient_dict, dep_name):
844 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
845 raise KeyError(
846 "Could not find any dependency called %s." % dep_name)
847
848 dep = gclient_dict['deps'][dep_name]
849 if dep is None:
850 return None
851 elif isinstance(dep, basestring):
852 _, _, revision = dep.partition('@')
853 return revision or None
854 elif isinstance(dep, collections.Mapping) and 'url' in dep:
855 _, _, revision = dep['url'].partition('@')
856 return revision or None
857 else:
858 raise ValueError(
859 '%s is not a valid git dependency.' % dep_name)