blob: 2ce4f9cb22375fcc4e6021cd6e79ffa1937e26c6 [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, Jr032d5452017-06-22 20:43:53 +020026
27 # Optional condition string. The hook will only be run
28 # if the condition evaluates to True.
29 schema.Optional('condition'): basestring,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020030}]
31
32_GCLIENT_SCHEMA = schema.Schema({
33 # List of host names from which dependencies are allowed (whitelist).
34 # NOTE: when not present, all hosts are allowed.
35 # NOTE: scoped to current DEPS file, not recursive.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020036 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020037
38 # Mapping from paths to repo and revision to check out under that path.
39 # Applying this mapping to the on-disk checkout is the main purpose
40 # of gclient, and also why the config file is called DEPS.
41 #
42 # The following functions are allowed:
43 #
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020044 # Var(): allows variable substitution (either from 'vars' dict below,
45 # or command-line override)
Paweł Hajdan, Jrc7ba0332017-05-29 16:38:45 +020046 schema.Optional('deps'): {
47 schema.Optional(basestring): schema.Or(
48 basestring,
49 {
Paweł Hajdan, Jrf69860b2017-06-05 20:24:28 +020050 # Repo and revision to check out under the path
51 # (same as if no dict was used).
Paweł Hajdan, Jrc7ba0332017-05-29 16:38:45 +020052 'url': basestring,
Paweł Hajdan, Jrf69860b2017-06-05 20:24:28 +020053
54 # Optional condition string. The dep will only be processed
55 # if the condition evaluates to True.
56 schema.Optional('condition'): basestring,
Paweł Hajdan, Jrc7ba0332017-05-29 16:38:45 +020057 },
58 ),
59 },
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020060
61 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020062 # Also see 'target_os'.
63 schema.Optional('deps_os'): {
64 schema.Optional(basestring): {
65 schema.Optional(basestring): schema.Or(basestring, None)
66 }
67 },
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020068
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +020069 # Path to GN args file to write selected variables.
70 schema.Optional('gclient_gn_args_file'): basestring,
71
72 # Subset of variables to write to the GN args file (see above).
73 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
74
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020075 # Hooks executed after gclient sync (unless suppressed), or explicitly
76 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
77 # Also see 'pre_deps_hooks'.
78 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
79
Scott Grahamc4826742017-05-11 16:59:23 -070080 # Similar to 'hooks', also keyed by OS.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020081 schema.Optional('hooks_os'): {
82 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
83 },
Scott Grahamc4826742017-05-11 16:59:23 -070084
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020085 # Rules which #includes are allowed in the directory.
86 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020087 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020088
89 # Hooks executed before processing DEPS. See 'hooks' for more details.
90 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
91
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +020092 # Recursion limit for nested DEPS.
93 schema.Optional('recursion'): int,
94
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020095 # Whitelists deps for which recursion should be enabled.
96 schema.Optional('recursedeps'): [
Paweł Hajdan, Jr05fec032017-05-30 23:04:23 +020097 schema.Optional(schema.Or(
98 basestring,
99 (basestring, basestring),
100 [basestring, basestring]
101 )),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200102 ],
103
104 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200105 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200106
107 # Mapping from paths to include rules specific for that path.
108 # See 'include_rules' for more details.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200109 schema.Optional('specific_include_rules'): {
110 schema.Optional(basestring): [basestring]
111 },
112
113 # List of additional OS names to consider when selecting dependencies
114 # from deps_os.
115 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200116
117 # For recursed-upon sub-dependencies, check out their own dependencies
118 # relative to the paren't path, rather than relative to the .gclient file.
119 schema.Optional('use_relative_paths'): bool,
120
121 # Variables that can be referenced using Var() - see 'deps'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200122 schema.Optional('vars'): {schema.Optional(basestring): basestring},
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200123})
124
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200125
126def _gclient_eval(node_or_string, global_scope, filename='<unknown>'):
127 """Safely evaluates a single expression. Returns the result."""
128 _allowed_names = {'None': None, 'True': True, 'False': False}
129 if isinstance(node_or_string, basestring):
130 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
131 if isinstance(node_or_string, ast.Expression):
132 node_or_string = node_or_string.body
133 def _convert(node):
134 if isinstance(node, ast.Str):
135 return node.s
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200136 elif isinstance(node, ast.Num):
137 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200138 elif isinstance(node, ast.Tuple):
139 return tuple(map(_convert, node.elts))
140 elif isinstance(node, ast.List):
141 return list(map(_convert, node.elts))
142 elif isinstance(node, ast.Dict):
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200143 return collections.OrderedDict(
144 (_convert(k), _convert(v))
145 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200146 elif isinstance(node, ast.Name):
147 if node.id not in _allowed_names:
148 raise ValueError(
149 'invalid name %r (file %r, line %s)' % (
150 node.id, filename, getattr(node, 'lineno', '<unknown>')))
151 return _allowed_names[node.id]
152 elif isinstance(node, ast.Call):
153 if not isinstance(node.func, ast.Name):
154 raise ValueError(
155 'invalid call: func should be a name (file %r, line %s)' % (
156 filename, getattr(node, 'lineno', '<unknown>')))
157 if node.keywords or node.starargs or node.kwargs:
158 raise ValueError(
159 'invalid call: use only regular args (file %r, line %s)' % (
160 filename, getattr(node, 'lineno', '<unknown>')))
161 args = map(_convert, node.args)
162 return global_scope[node.func.id](*args)
163 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
164 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200165 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
166 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200167 else:
168 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200169 'unexpected AST node: %s %s (file %r, line %s)' % (
170 node, ast.dump(node), filename,
171 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200172 return _convert(node_or_string)
173
174
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200175def Exec(content, global_scope, local_scope, filename='<unknown>'):
176 """Safely execs a set of assignments. Mutates |local_scope|."""
177 node_or_string = ast.parse(content, filename=filename, mode='exec')
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200178 if isinstance(node_or_string, ast.Expression):
179 node_or_string = node_or_string.body
180
181 def _visit_in_module(node):
182 if isinstance(node, ast.Assign):
183 if len(node.targets) != 1:
184 raise ValueError(
185 'invalid assignment: use exactly one target (file %r, line %s)' % (
186 filename, getattr(node, 'lineno', '<unknown>')))
187 target = node.targets[0]
188 if not isinstance(target, ast.Name):
189 raise ValueError(
190 'invalid assignment: target should be a name (file %r, line %s)' % (
191 filename, getattr(node, 'lineno', '<unknown>')))
192 value = _gclient_eval(node.value, global_scope, filename=filename)
193
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200194 if target.id in local_scope:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200195 raise ValueError(
196 'invalid assignment: overrides var %r (file %r, line %s)' % (
197 target.id, filename, getattr(node, 'lineno', '<unknown>')))
198
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200199 local_scope[target.id] = value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200200 else:
201 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200202 'unexpected AST node: %s %s (file %r, line %s)' % (
203 node, ast.dump(node), filename,
204 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200205
206 if isinstance(node_or_string, ast.Module):
207 for stmt in node_or_string.body:
208 _visit_in_module(stmt)
209 else:
210 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200211 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200212 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200213 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200214 filename,
215 getattr(node_or_string, 'lineno', '<unknown>')))
216
Paweł Hajdan, Jrc485d5a2017-06-02 12:08:09 +0200217 _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200218
219
220def EvaluateCondition(condition, variables, referenced_variables=None):
221 """Safely evaluates a boolean condition. Returns the result."""
222 if not referenced_variables:
223 referenced_variables = set()
224 _allowed_names = {'None': None, 'True': True, 'False': False}
225 main_node = ast.parse(condition, mode='eval')
226 if isinstance(main_node, ast.Expression):
227 main_node = main_node.body
228 def _convert(node):
229 if isinstance(node, ast.Str):
230 return node.s
231 elif isinstance(node, ast.Name):
232 if node.id in referenced_variables:
233 raise ValueError(
234 'invalid cyclic reference to %r (inside %r)' % (
235 node.id, condition))
236 elif node.id in _allowed_names:
237 return _allowed_names[node.id]
238 elif node.id in variables:
239 return EvaluateCondition(
240 variables[node.id],
241 variables,
242 referenced_variables.union([node.id]))
243 else:
244 raise ValueError(
245 'invalid name %r (inside %r)' % (node.id, condition))
246 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
247 if len(node.values) != 2:
248 raise ValueError(
249 'invalid "or": exactly 2 operands required (inside %r)' % (
250 condition))
251 return _convert(node.values[0]) or _convert(node.values[1])
252 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
253 if len(node.values) != 2:
254 raise ValueError(
255 'invalid "and": exactly 2 operands required (inside %r)' % (
256 condition))
257 return _convert(node.values[0]) and _convert(node.values[1])
258 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
259 return not _convert(node.operand)
260 elif isinstance(node, ast.Compare):
261 if len(node.ops) != 1:
262 raise ValueError(
263 'invalid compare: exactly 1 operator required (inside %r)' % (
264 condition))
265 if len(node.comparators) != 1:
266 raise ValueError(
267 'invalid compare: exactly 1 comparator required (inside %r)' % (
268 condition))
269
270 left = _convert(node.left)
271 right = _convert(node.comparators[0])
272
273 if isinstance(node.ops[0], ast.Eq):
274 return left == right
275
276 raise ValueError(
277 'unexpected operator: %s %s (inside %r)' % (
278 node.ops[0], ast.dump(node), condition))
279 else:
280 raise ValueError(
281 'unexpected AST node: %s %s (inside %r)' % (
282 node, ast.dump(node), condition))
283 return _convert(main_node)