blob: a995db9e1ef10a68efdf9919e5aaf459d7096910 [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, Jrb7e53332017-05-23 16:57:37 +020074 schema.Optional(schema.Or(basestring, (basestring, basestring)))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020075 ],
76
77 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020078 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020079
80 # Mapping from paths to include rules specific for that path.
81 # See 'include_rules' for more details.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020082 schema.Optional('specific_include_rules'): {
83 schema.Optional(basestring): [basestring]
84 },
85
86 # List of additional OS names to consider when selecting dependencies
87 # from deps_os.
88 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020089
90 # For recursed-upon sub-dependencies, check out their own dependencies
91 # relative to the paren't path, rather than relative to the .gclient file.
92 schema.Optional('use_relative_paths'): bool,
93
94 # Variables that can be referenced using Var() - see 'deps'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +020095 schema.Optional('vars'): {schema.Optional(basestring): basestring},
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020096})
97
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +020098
99def _gclient_eval(node_or_string, global_scope, filename='<unknown>'):
100 """Safely evaluates a single expression. Returns the result."""
101 _allowed_names = {'None': None, 'True': True, 'False': False}
102 if isinstance(node_or_string, basestring):
103 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
104 if isinstance(node_or_string, ast.Expression):
105 node_or_string = node_or_string.body
106 def _convert(node):
107 if isinstance(node, ast.Str):
108 return node.s
109 elif isinstance(node, ast.Tuple):
110 return tuple(map(_convert, node.elts))
111 elif isinstance(node, ast.List):
112 return list(map(_convert, node.elts))
113 elif isinstance(node, ast.Dict):
114 return dict((_convert(k), _convert(v))
115 for k, v in zip(node.keys, node.values))
116 elif isinstance(node, ast.Name):
117 if node.id not in _allowed_names:
118 raise ValueError(
119 'invalid name %r (file %r, line %s)' % (
120 node.id, filename, getattr(node, 'lineno', '<unknown>')))
121 return _allowed_names[node.id]
122 elif isinstance(node, ast.Call):
123 if not isinstance(node.func, ast.Name):
124 raise ValueError(
125 'invalid call: func should be a name (file %r, line %s)' % (
126 filename, getattr(node, 'lineno', '<unknown>')))
127 if node.keywords or node.starargs or node.kwargs:
128 raise ValueError(
129 'invalid call: use only regular args (file %r, line %s)' % (
130 filename, getattr(node, 'lineno', '<unknown>')))
131 args = map(_convert, node.args)
132 return global_scope[node.func.id](*args)
133 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
134 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200135 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
136 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200137 else:
138 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200139 'unexpected AST node: %s %s (file %r, line %s)' % (
140 node, ast.dump(node), filename,
141 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200142 return _convert(node_or_string)
143
144
145def _gclient_exec(node_or_string, global_scope, filename='<unknown>'):
146 """Safely execs a set of assignments. Returns resulting scope."""
147 result_scope = {}
148
149 if isinstance(node_or_string, basestring):
150 node_or_string = ast.parse(node_or_string, filename=filename, mode='exec')
151 if isinstance(node_or_string, ast.Expression):
152 node_or_string = node_or_string.body
153
154 def _visit_in_module(node):
155 if isinstance(node, ast.Assign):
156 if len(node.targets) != 1:
157 raise ValueError(
158 'invalid assignment: use exactly one target (file %r, line %s)' % (
159 filename, getattr(node, 'lineno', '<unknown>')))
160 target = node.targets[0]
161 if not isinstance(target, ast.Name):
162 raise ValueError(
163 'invalid assignment: target should be a name (file %r, line %s)' % (
164 filename, getattr(node, 'lineno', '<unknown>')))
165 value = _gclient_eval(node.value, global_scope, filename=filename)
166
167 if target.id in result_scope:
168 raise ValueError(
169 'invalid assignment: overrides var %r (file %r, line %s)' % (
170 target.id, filename, getattr(node, 'lineno', '<unknown>')))
171
172 result_scope[target.id] = value
173 else:
174 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200175 'unexpected AST node: %s %s (file %r, line %s)' % (
176 node, ast.dump(node), filename,
177 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200178
179 if isinstance(node_or_string, ast.Module):
180 for stmt in node_or_string.body:
181 _visit_in_module(stmt)
182 else:
183 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200184 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200185 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200186 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200187 filename,
188 getattr(node_or_string, 'lineno', '<unknown>')))
189
190 return result_scope
191
192
193class CheckFailure(Exception):
194 """Contains details of a check failure."""
195 def __init__(self, msg, path, exp, act):
196 super(CheckFailure, self).__init__(msg)
197 self.path = path
198 self.exp = exp
199 self.act = act
200
201
202def Check(content, path, global_scope, expected_scope):
203 """Cross-checks the old and new gclient eval logic.
204
205 Safely execs |content| (backed by file |path|) using |global_scope|,
206 and compares with |expected_scope|.
207
208 Throws CheckFailure if any difference between |expected_scope| and scope
209 returned by new gclient eval code is detected.
210 """
211 def fail(prefix, exp, act):
212 raise CheckFailure(
213 'gclient check for %s: %s exp %s, got %s' % (
214 path, prefix, repr(exp), repr(act)), prefix, exp, act)
215
216 def compare(expected, actual, var_path, actual_scope):
217 if isinstance(expected, dict):
218 exp = set(expected.keys())
219 act = set(actual.keys())
220 if exp != act:
221 fail(var_path, exp, act)
222 for k in expected:
223 compare(expected[k], actual[k], var_path + '["%s"]' % k, actual_scope)
224 return
225 elif isinstance(expected, list):
226 exp = len(expected)
227 act = len(actual)
228 if exp != act:
229 fail('len(%s)' % var_path, expected_scope, actual_scope)
230 for i in range(exp):
231 compare(expected[i], actual[i], var_path + '[%d]' % i, actual_scope)
232 else:
233 if expected != actual:
234 fail(var_path, expected_scope, actual_scope)
235
236 result_scope = _gclient_exec(content, global_scope, filename=path)
237
238 compare(expected_scope, result_scope, '', result_scope)
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200239
240 _GCLIENT_SCHEMA.validate(result_scope)