blob: 1652eb7d30846911e41faf4bfdc93d93a2a8e66f [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
6
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +02007from third_party import schema
8
9
10# See https://github.com/keleshev/schema for docs how to configure schema.
11_GCLIENT_HOOKS_SCHEMA = [{
12 # Hook action: list of command-line arguments to invoke.
13 'action': [basestring],
14
15 # Name of the hook. Doesn't affect operation.
16 schema.Optional('name'): basestring,
17
18 # Hook pattern (regex). Originally intended to limit some hooks to run
19 # only when files matching the pattern have changed. In practice, with git,
20 # gclient runs all the hooks regardless of this field.
21 schema.Optional('pattern'): basestring,
22}]
23
24_GCLIENT_SCHEMA = schema.Schema({
25 # List of host names from which dependencies are allowed (whitelist).
26 # NOTE: when not present, all hosts are allowed.
27 # NOTE: scoped to current DEPS file, not recursive.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020028 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020029
30 # Mapping from paths to repo and revision to check out under that path.
31 # Applying this mapping to the on-disk checkout is the main purpose
32 # of gclient, and also why the config file is called DEPS.
33 #
34 # The following functions are allowed:
35 #
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020036 # Var(): allows variable substitution (either from 'vars' dict below,
37 # or command-line override)
Paweł Hajdan, Jrc7ba0332017-05-29 16:38:45 +020038 schema.Optional('deps'): {
39 schema.Optional(basestring): schema.Or(
40 basestring,
41 {
42 'url': basestring,
43 },
44 ),
45 },
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020046
47 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020048 # Also see 'target_os'.
49 schema.Optional('deps_os'): {
50 schema.Optional(basestring): {
51 schema.Optional(basestring): schema.Or(basestring, None)
52 }
53 },
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020054
55 # Hooks executed after gclient sync (unless suppressed), or explicitly
56 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
57 # Also see 'pre_deps_hooks'.
58 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
59
Scott Grahamc4826742017-05-11 16:59:23 -070060 # Similar to 'hooks', also keyed by OS.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020061 schema.Optional('hooks_os'): {
62 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
63 },
Scott Grahamc4826742017-05-11 16:59:23 -070064
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020065 # Rules which #includes are allowed in the directory.
66 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020067 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020068
69 # Hooks executed before processing DEPS. See 'hooks' for more details.
70 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
71
72 # Whitelists deps for which recursion should be enabled.
73 schema.Optional('recursedeps'): [
Paweł Hajdan, Jr05fec032017-05-30 23:04:23 +020074 schema.Optional(schema.Or(
75 basestring,
76 (basestring, basestring),
77 [basestring, basestring]
78 )),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020079 ],
80
81 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020082 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020083
84 # Mapping from paths to include rules specific for that path.
85 # See 'include_rules' for more details.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020086 schema.Optional('specific_include_rules'): {
87 schema.Optional(basestring): [basestring]
88 },
89
90 # List of additional OS names to consider when selecting dependencies
91 # from deps_os.
92 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020093
94 # For recursed-upon sub-dependencies, check out their own dependencies
95 # relative to the paren't path, rather than relative to the .gclient file.
96 schema.Optional('use_relative_paths'): bool,
97
98 # Variables that can be referenced using Var() - see 'deps'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020099 schema.Optional('vars'): {schema.Optional(basestring): basestring},
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200100})
101
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200102
103def _gclient_eval(node_or_string, global_scope, filename='<unknown>'):
104 """Safely evaluates a single expression. Returns the result."""
105 _allowed_names = {'None': None, 'True': True, 'False': False}
106 if isinstance(node_or_string, basestring):
107 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
108 if isinstance(node_or_string, ast.Expression):
109 node_or_string = node_or_string.body
110 def _convert(node):
111 if isinstance(node, ast.Str):
112 return node.s
113 elif isinstance(node, ast.Tuple):
114 return tuple(map(_convert, node.elts))
115 elif isinstance(node, ast.List):
116 return list(map(_convert, node.elts))
117 elif isinstance(node, ast.Dict):
118 return dict((_convert(k), _convert(v))
119 for k, v in zip(node.keys, node.values))
120 elif isinstance(node, ast.Name):
121 if node.id not in _allowed_names:
122 raise ValueError(
123 'invalid name %r (file %r, line %s)' % (
124 node.id, filename, getattr(node, 'lineno', '<unknown>')))
125 return _allowed_names[node.id]
126 elif isinstance(node, ast.Call):
127 if not isinstance(node.func, ast.Name):
128 raise ValueError(
129 'invalid call: func should be a name (file %r, line %s)' % (
130 filename, getattr(node, 'lineno', '<unknown>')))
131 if node.keywords or node.starargs or node.kwargs:
132 raise ValueError(
133 'invalid call: use only regular args (file %r, line %s)' % (
134 filename, getattr(node, 'lineno', '<unknown>')))
135 args = map(_convert, node.args)
136 return global_scope[node.func.id](*args)
137 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
138 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200139 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
140 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200141 else:
142 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200143 'unexpected AST node: %s %s (file %r, line %s)' % (
144 node, ast.dump(node), filename,
145 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200146 return _convert(node_or_string)
147
148
149def _gclient_exec(node_or_string, global_scope, filename='<unknown>'):
150 """Safely execs a set of assignments. Returns resulting scope."""
151 result_scope = {}
152
153 if isinstance(node_or_string, basestring):
154 node_or_string = ast.parse(node_or_string, filename=filename, mode='exec')
155 if isinstance(node_or_string, ast.Expression):
156 node_or_string = node_or_string.body
157
158 def _visit_in_module(node):
159 if isinstance(node, ast.Assign):
160 if len(node.targets) != 1:
161 raise ValueError(
162 'invalid assignment: use exactly one target (file %r, line %s)' % (
163 filename, getattr(node, 'lineno', '<unknown>')))
164 target = node.targets[0]
165 if not isinstance(target, ast.Name):
166 raise ValueError(
167 'invalid assignment: target should be a name (file %r, line %s)' % (
168 filename, getattr(node, 'lineno', '<unknown>')))
169 value = _gclient_eval(node.value, global_scope, filename=filename)
170
171 if target.id in result_scope:
172 raise ValueError(
173 'invalid assignment: overrides var %r (file %r, line %s)' % (
174 target.id, filename, getattr(node, 'lineno', '<unknown>')))
175
176 result_scope[target.id] = value
177 else:
178 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200179 'unexpected AST node: %s %s (file %r, line %s)' % (
180 node, ast.dump(node), filename,
181 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200182
183 if isinstance(node_or_string, ast.Module):
184 for stmt in node_or_string.body:
185 _visit_in_module(stmt)
186 else:
187 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200188 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200189 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200190 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200191 filename,
192 getattr(node_or_string, 'lineno', '<unknown>')))
193
194 return result_scope
195
196
197class CheckFailure(Exception):
198 """Contains details of a check failure."""
199 def __init__(self, msg, path, exp, act):
200 super(CheckFailure, self).__init__(msg)
201 self.path = path
202 self.exp = exp
203 self.act = act
204
205
206def Check(content, path, global_scope, expected_scope):
207 """Cross-checks the old and new gclient eval logic.
208
209 Safely execs |content| (backed by file |path|) using |global_scope|,
210 and compares with |expected_scope|.
211
212 Throws CheckFailure if any difference between |expected_scope| and scope
213 returned by new gclient eval code is detected.
214 """
215 def fail(prefix, exp, act):
216 raise CheckFailure(
217 'gclient check for %s: %s exp %s, got %s' % (
218 path, prefix, repr(exp), repr(act)), prefix, exp, act)
219
220 def compare(expected, actual, var_path, actual_scope):
221 if isinstance(expected, dict):
222 exp = set(expected.keys())
223 act = set(actual.keys())
224 if exp != act:
225 fail(var_path, exp, act)
226 for k in expected:
227 compare(expected[k], actual[k], var_path + '["%s"]' % k, actual_scope)
228 return
229 elif isinstance(expected, list):
230 exp = len(expected)
231 act = len(actual)
232 if exp != act:
233 fail('len(%s)' % var_path, expected_scope, actual_scope)
234 for i in range(exp):
235 compare(expected[i], actual[i], var_path + '[%d]' % i, actual_scope)
236 else:
237 if expected != actual:
238 fail(var_path, expected_scope, actual_scope)
239
240 result_scope = _gclient_exec(content, global_scope, filename=path)
241
242 compare(expected_scope, result_scope, '', result_scope)
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200243
244 _GCLIENT_SCHEMA.validate(result_scope)