blob: 2f27634aefcc0f763870ebd10d46b1cb04325e69 [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
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +02006import collections
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +02007
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +02008from third_party import schema
9
10
11# See https://github.com/keleshev/schema for docs how to configure schema.
12_GCLIENT_HOOKS_SCHEMA = [{
13 # Hook action: list of command-line arguments to invoke.
14 'action': [basestring],
15
16 # Name of the hook. Doesn't affect operation.
17 schema.Optional('name'): basestring,
18
19 # Hook pattern (regex). Originally intended to limit some hooks to run
20 # only when files matching the pattern have changed. In practice, with git,
21 # gclient runs all the hooks regardless of this field.
22 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +020023
24 # Working directory where to execute the hook.
25 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020026}]
27
28_GCLIENT_SCHEMA = schema.Schema({
29 # List of host names from which dependencies are allowed (whitelist).
30 # NOTE: when not present, all hosts are allowed.
31 # NOTE: scoped to current DEPS file, not recursive.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020032 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020033
34 # Mapping from paths to repo and revision to check out under that path.
35 # Applying this mapping to the on-disk checkout is the main purpose
36 # of gclient, and also why the config file is called DEPS.
37 #
38 # The following functions are allowed:
39 #
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020040 # Var(): allows variable substitution (either from 'vars' dict below,
41 # or command-line override)
Paweł Hajdan, Jrc7ba0332017-05-29 16:38:45 +020042 schema.Optional('deps'): {
43 schema.Optional(basestring): schema.Or(
44 basestring,
45 {
Paweł Hajdan, Jrf69860b2017-06-05 20:24:28 +020046 # Repo and revision to check out under the path
47 # (same as if no dict was used).
Paweł Hajdan, Jrc7ba0332017-05-29 16:38:45 +020048 'url': basestring,
Paweł Hajdan, Jrf69860b2017-06-05 20:24:28 +020049
50 # Optional condition string. The dep will only be processed
51 # if the condition evaluates to True.
52 schema.Optional('condition'): basestring,
Paweł Hajdan, Jrc7ba0332017-05-29 16:38:45 +020053 },
54 ),
55 },
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020056
57 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020058 # Also see 'target_os'.
59 schema.Optional('deps_os'): {
60 schema.Optional(basestring): {
61 schema.Optional(basestring): schema.Or(basestring, None)
62 }
63 },
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020064
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +020065 # Path to GN args file to write selected variables.
66 schema.Optional('gclient_gn_args_file'): basestring,
67
68 # Subset of variables to write to the GN args file (see above).
69 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
70
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020071 # Hooks executed after gclient sync (unless suppressed), or explicitly
72 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
73 # Also see 'pre_deps_hooks'.
74 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
75
Scott Grahamc4826742017-05-11 16:59:23 -070076 # Similar to 'hooks', also keyed by OS.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020077 schema.Optional('hooks_os'): {
78 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
79 },
Scott Grahamc4826742017-05-11 16:59:23 -070080
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020081 # Rules which #includes are allowed in the directory.
82 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020083 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020084
85 # Hooks executed before processing DEPS. See 'hooks' for more details.
86 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
87
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +020088 # Recursion limit for nested DEPS.
89 schema.Optional('recursion'): int,
90
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020091 # Whitelists deps for which recursion should be enabled.
92 schema.Optional('recursedeps'): [
Paweł Hajdan, Jr05fec032017-05-30 23:04:23 +020093 schema.Optional(schema.Or(
94 basestring,
95 (basestring, basestring),
96 [basestring, basestring]
97 )),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020098 ],
99
100 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200101 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200102
103 # Mapping from paths to include rules specific for that path.
104 # See 'include_rules' for more details.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200105 schema.Optional('specific_include_rules'): {
106 schema.Optional(basestring): [basestring]
107 },
108
109 # List of additional OS names to consider when selecting dependencies
110 # from deps_os.
111 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200112
113 # For recursed-upon sub-dependencies, check out their own dependencies
114 # relative to the paren't path, rather than relative to the .gclient file.
115 schema.Optional('use_relative_paths'): bool,
116
117 # Variables that can be referenced using Var() - see 'deps'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200118 schema.Optional('vars'): {schema.Optional(basestring): basestring},
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200119})
120
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200121
122def _gclient_eval(node_or_string, global_scope, filename='<unknown>'):
123 """Safely evaluates a single expression. Returns the result."""
124 _allowed_names = {'None': None, 'True': True, 'False': False}
125 if isinstance(node_or_string, basestring):
126 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
127 if isinstance(node_or_string, ast.Expression):
128 node_or_string = node_or_string.body
129 def _convert(node):
130 if isinstance(node, ast.Str):
131 return node.s
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200132 elif isinstance(node, ast.Num):
133 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200134 elif isinstance(node, ast.Tuple):
135 return tuple(map(_convert, node.elts))
136 elif isinstance(node, ast.List):
137 return list(map(_convert, node.elts))
138 elif isinstance(node, ast.Dict):
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200139 return collections.OrderedDict(
140 (_convert(k), _convert(v))
141 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200142 elif isinstance(node, ast.Name):
143 if node.id not in _allowed_names:
144 raise ValueError(
145 'invalid name %r (file %r, line %s)' % (
146 node.id, filename, getattr(node, 'lineno', '<unknown>')))
147 return _allowed_names[node.id]
148 elif isinstance(node, ast.Call):
149 if not isinstance(node.func, ast.Name):
150 raise ValueError(
151 'invalid call: func should be a name (file %r, line %s)' % (
152 filename, getattr(node, 'lineno', '<unknown>')))
153 if node.keywords or node.starargs or node.kwargs:
154 raise ValueError(
155 'invalid call: use only regular args (file %r, line %s)' % (
156 filename, getattr(node, 'lineno', '<unknown>')))
157 args = map(_convert, node.args)
158 return global_scope[node.func.id](*args)
159 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
160 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200161 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
162 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200163 else:
164 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200165 'unexpected AST node: %s %s (file %r, line %s)' % (
166 node, ast.dump(node), filename,
167 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200168 return _convert(node_or_string)
169
170
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200171def Exec(content, global_scope, local_scope, filename='<unknown>'):
172 """Safely execs a set of assignments. Mutates |local_scope|."""
173 node_or_string = ast.parse(content, filename=filename, mode='exec')
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200174 if isinstance(node_or_string, ast.Expression):
175 node_or_string = node_or_string.body
176
177 def _visit_in_module(node):
178 if isinstance(node, ast.Assign):
179 if len(node.targets) != 1:
180 raise ValueError(
181 'invalid assignment: use exactly one target (file %r, line %s)' % (
182 filename, getattr(node, 'lineno', '<unknown>')))
183 target = node.targets[0]
184 if not isinstance(target, ast.Name):
185 raise ValueError(
186 'invalid assignment: target should be a name (file %r, line %s)' % (
187 filename, getattr(node, 'lineno', '<unknown>')))
188 value = _gclient_eval(node.value, global_scope, filename=filename)
189
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200190 if target.id in local_scope:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200191 raise ValueError(
192 'invalid assignment: overrides var %r (file %r, line %s)' % (
193 target.id, filename, getattr(node, 'lineno', '<unknown>')))
194
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200195 local_scope[target.id] = value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200196 else:
197 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200198 'unexpected AST node: %s %s (file %r, line %s)' % (
199 node, ast.dump(node), filename,
200 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200201
202 if isinstance(node_or_string, ast.Module):
203 for stmt in node_or_string.body:
204 _visit_in_module(stmt)
205 else:
206 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200207 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200208 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200209 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200210 filename,
211 getattr(node_or_string, 'lineno', '<unknown>')))
212
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200213 _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200214
215
216def EvaluateCondition(condition, variables, referenced_variables=None):
217 """Safely evaluates a boolean condition. Returns the result."""
218 if not referenced_variables:
219 referenced_variables = set()
220 _allowed_names = {'None': None, 'True': True, 'False': False}
221 main_node = ast.parse(condition, mode='eval')
222 if isinstance(main_node, ast.Expression):
223 main_node = main_node.body
224 def _convert(node):
225 if isinstance(node, ast.Str):
226 return node.s
227 elif isinstance(node, ast.Name):
228 if node.id in referenced_variables:
229 raise ValueError(
230 'invalid cyclic reference to %r (inside %r)' % (
231 node.id, condition))
232 elif node.id in _allowed_names:
233 return _allowed_names[node.id]
234 elif node.id in variables:
235 return EvaluateCondition(
236 variables[node.id],
237 variables,
238 referenced_variables.union([node.id]))
239 else:
240 raise ValueError(
241 'invalid name %r (inside %r)' % (node.id, condition))
242 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
243 if len(node.values) != 2:
244 raise ValueError(
245 'invalid "or": exactly 2 operands required (inside %r)' % (
246 condition))
247 return _convert(node.values[0]) or _convert(node.values[1])
248 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
249 if len(node.values) != 2:
250 raise ValueError(
251 'invalid "and": exactly 2 operands required (inside %r)' % (
252 condition))
253 return _convert(node.values[0]) and _convert(node.values[1])
254 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
255 return not _convert(node.operand)
256 elif isinstance(node, ast.Compare):
257 if len(node.ops) != 1:
258 raise ValueError(
259 'invalid compare: exactly 1 operator required (inside %r)' % (
260 condition))
261 if len(node.comparators) != 1:
262 raise ValueError(
263 'invalid compare: exactly 1 comparator required (inside %r)' % (
264 condition))
265
266 left = _convert(node.left)
267 right = _convert(node.comparators[0])
268
269 if isinstance(node.ops[0], ast.Eq):
270 return left == right
271
272 raise ValueError(
273 'unexpected operator: %s %s (inside %r)' % (
274 node.ops[0], ast.dump(node), condition))
275 else:
276 raise ValueError(
277 'unexpected AST node: %s %s (inside %r)' % (
278 node, ast.dump(node), condition))
279 return _convert(main_node)