blob: 0bcbf78bdd9f0a5fa24103fd3618bb647bd40866 [file] [log] [blame]
Paweł Hajdan, Jre2f9feec2017-05-09 08:04:021# 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 19:51:057from 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 14:57:3728 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0529
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 19:51:0536 # Var(): allows variable substitution (either from 'vars' dict below,
37 # or command-line override)
38 schema.Optional('deps'): {schema.Optional(basestring): basestring},
39
40 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 14:57:3741 # Also see 'target_os'.
42 schema.Optional('deps_os'): {
43 schema.Optional(basestring): {
44 schema.Optional(basestring): schema.Or(basestring, None)
45 }
46 },
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0547
48 # Hooks executed after gclient sync (unless suppressed), or explicitly
49 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
50 # Also see 'pre_deps_hooks'.
51 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
52
Scott Grahamc4826742017-05-11 23:59:2353 # Similar to 'hooks', also keyed by OS.
Paweł Hajdan, Jrb7e53332017-05-23 14:57:3754 schema.Optional('hooks_os'): {
55 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
56 },
Scott Grahamc4826742017-05-11 23:59:2357
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0558 # Rules which #includes are allowed in the directory.
59 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 14:57:3760 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0561
62 # Hooks executed before processing DEPS. See 'hooks' for more details.
63 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
64
65 # Whitelists deps for which recursion should be enabled.
66 schema.Optional('recursedeps'): [
Paweł Hajdan, Jrb7e53332017-05-23 14:57:3767 schema.Optional(schema.Or(basestring, (basestring, basestring)))
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0568 ],
69
70 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 14:57:3771 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0572
73 # Mapping from paths to include rules specific for that path.
74 # See 'include_rules' for more details.
Paweł Hajdan, Jrb7e53332017-05-23 14:57:3775 schema.Optional('specific_include_rules'): {
76 schema.Optional(basestring): [basestring]
77 },
78
79 # List of additional OS names to consider when selecting dependencies
80 # from deps_os.
81 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0582
83 # For recursed-upon sub-dependencies, check out their own dependencies
84 # relative to the paren't path, rather than relative to the .gclient file.
85 schema.Optional('use_relative_paths'): bool,
86
87 # Variables that can be referenced using Var() - see 'deps'.
Paweł Hajdan, Jrb7e53332017-05-23 14:57:3788 schema.Optional('vars'): {schema.Optional(basestring): basestring},
Paweł Hajdan, Jrbeec0062017-05-10 19:51:0589})
90
Paweł Hajdan, Jre2f9feec2017-05-09 08:04:0291
92def _gclient_eval(node_or_string, global_scope, filename='<unknown>'):
93 """Safely evaluates a single expression. Returns the result."""
94 _allowed_names = {'None': None, 'True': True, 'False': False}
95 if isinstance(node_or_string, basestring):
96 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
97 if isinstance(node_or_string, ast.Expression):
98 node_or_string = node_or_string.body
99 def _convert(node):
100 if isinstance(node, ast.Str):
101 return node.s
102 elif isinstance(node, ast.Tuple):
103 return tuple(map(_convert, node.elts))
104 elif isinstance(node, ast.List):
105 return list(map(_convert, node.elts))
106 elif isinstance(node, ast.Dict):
107 return dict((_convert(k), _convert(v))
108 for k, v in zip(node.keys, node.values))
109 elif isinstance(node, ast.Name):
110 if node.id not in _allowed_names:
111 raise ValueError(
112 'invalid name %r (file %r, line %s)' % (
113 node.id, filename, getattr(node, 'lineno', '<unknown>')))
114 return _allowed_names[node.id]
115 elif isinstance(node, ast.Call):
116 if not isinstance(node.func, ast.Name):
117 raise ValueError(
118 'invalid call: func should be a name (file %r, line %s)' % (
119 filename, getattr(node, 'lineno', '<unknown>')))
120 if node.keywords or node.starargs or node.kwargs:
121 raise ValueError(
122 'invalid call: use only regular args (file %r, line %s)' % (
123 filename, getattr(node, 'lineno', '<unknown>')))
124 args = map(_convert, node.args)
125 return global_scope[node.func.id](*args)
126 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
127 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 14:57:37128 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
129 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 08:04:02130 else:
131 raise ValueError(
132 'unexpected AST node: %s (file %r, line %s)' % (
133 node, filename, getattr(node, 'lineno', '<unknown>')))
134 return _convert(node_or_string)
135
136
137def _gclient_exec(node_or_string, global_scope, filename='<unknown>'):
138 """Safely execs a set of assignments. Returns resulting scope."""
139 result_scope = {}
140
141 if isinstance(node_or_string, basestring):
142 node_or_string = ast.parse(node_or_string, filename=filename, mode='exec')
143 if isinstance(node_or_string, ast.Expression):
144 node_or_string = node_or_string.body
145
146 def _visit_in_module(node):
147 if isinstance(node, ast.Assign):
148 if len(node.targets) != 1:
149 raise ValueError(
150 'invalid assignment: use exactly one target (file %r, line %s)' % (
151 filename, getattr(node, 'lineno', '<unknown>')))
152 target = node.targets[0]
153 if not isinstance(target, ast.Name):
154 raise ValueError(
155 'invalid assignment: target should be a name (file %r, line %s)' % (
156 filename, getattr(node, 'lineno', '<unknown>')))
157 value = _gclient_eval(node.value, global_scope, filename=filename)
158
159 if target.id in result_scope:
160 raise ValueError(
161 'invalid assignment: overrides var %r (file %r, line %s)' % (
162 target.id, filename, getattr(node, 'lineno', '<unknown>')))
163
164 result_scope[target.id] = value
165 else:
166 raise ValueError(
167 'unexpected AST node: %s (file %r, line %s)' % (
168 node, filename, getattr(node, 'lineno', '<unknown>')))
169
170 if isinstance(node_or_string, ast.Module):
171 for stmt in node_or_string.body:
172 _visit_in_module(stmt)
173 else:
174 raise ValueError(
175 'unexpected AST node: %s (file %r, line %s)' % (
176 node_or_string,
177 filename,
178 getattr(node_or_string, 'lineno', '<unknown>')))
179
180 return result_scope
181
182
183class CheckFailure(Exception):
184 """Contains details of a check failure."""
185 def __init__(self, msg, path, exp, act):
186 super(CheckFailure, self).__init__(msg)
187 self.path = path
188 self.exp = exp
189 self.act = act
190
191
192def Check(content, path, global_scope, expected_scope):
193 """Cross-checks the old and new gclient eval logic.
194
195 Safely execs |content| (backed by file |path|) using |global_scope|,
196 and compares with |expected_scope|.
197
198 Throws CheckFailure if any difference between |expected_scope| and scope
199 returned by new gclient eval code is detected.
200 """
201 def fail(prefix, exp, act):
202 raise CheckFailure(
203 'gclient check for %s: %s exp %s, got %s' % (
204 path, prefix, repr(exp), repr(act)), prefix, exp, act)
205
206 def compare(expected, actual, var_path, actual_scope):
207 if isinstance(expected, dict):
208 exp = set(expected.keys())
209 act = set(actual.keys())
210 if exp != act:
211 fail(var_path, exp, act)
212 for k in expected:
213 compare(expected[k], actual[k], var_path + '["%s"]' % k, actual_scope)
214 return
215 elif isinstance(expected, list):
216 exp = len(expected)
217 act = len(actual)
218 if exp != act:
219 fail('len(%s)' % var_path, expected_scope, actual_scope)
220 for i in range(exp):
221 compare(expected[i], actual[i], var_path + '[%d]' % i, actual_scope)
222 else:
223 if expected != actual:
224 fail(var_path, expected_scope, actual_scope)
225
226 result_scope = _gclient_exec(content, global_scope, filename=path)
227
228 compare(expected_scope, result_scope, '', result_scope)
Paweł Hajdan, Jrbeec0062017-05-10 19:51:05229
230 _GCLIENT_SCHEMA.validate(result_scope)