blob: caf63d4f6e157362545951be8e8eaf0d4380d316 [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(
Paweł Hajdan, Jr1ba610b2017-05-24 18:14:44132 'unexpected AST node: %s %s (file %r, line %s)' % (
133 node, ast.dump(node), filename,
134 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 08:04:02135 return _convert(node_or_string)
136
137
138def _gclient_exec(node_or_string, global_scope, filename='<unknown>'):
139 """Safely execs a set of assignments. Returns resulting scope."""
140 result_scope = {}
141
142 if isinstance(node_or_string, basestring):
143 node_or_string = ast.parse(node_or_string, filename=filename, mode='exec')
144 if isinstance(node_or_string, ast.Expression):
145 node_or_string = node_or_string.body
146
147 def _visit_in_module(node):
148 if isinstance(node, ast.Assign):
149 if len(node.targets) != 1:
150 raise ValueError(
151 'invalid assignment: use exactly one target (file %r, line %s)' % (
152 filename, getattr(node, 'lineno', '<unknown>')))
153 target = node.targets[0]
154 if not isinstance(target, ast.Name):
155 raise ValueError(
156 'invalid assignment: target should be a name (file %r, line %s)' % (
157 filename, getattr(node, 'lineno', '<unknown>')))
158 value = _gclient_eval(node.value, global_scope, filename=filename)
159
160 if target.id in result_scope:
161 raise ValueError(
162 'invalid assignment: overrides var %r (file %r, line %s)' % (
163 target.id, filename, getattr(node, 'lineno', '<unknown>')))
164
165 result_scope[target.id] = value
166 else:
167 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 18:14:44168 'unexpected AST node: %s %s (file %r, line %s)' % (
169 node, ast.dump(node), filename,
170 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 08:04:02171
172 if isinstance(node_or_string, ast.Module):
173 for stmt in node_or_string.body:
174 _visit_in_module(stmt)
175 else:
176 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 18:14:44177 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 08:04:02178 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 18:14:44179 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 08:04:02180 filename,
181 getattr(node_or_string, 'lineno', '<unknown>')))
182
183 return result_scope
184
185
186class CheckFailure(Exception):
187 """Contains details of a check failure."""
188 def __init__(self, msg, path, exp, act):
189 super(CheckFailure, self).__init__(msg)
190 self.path = path
191 self.exp = exp
192 self.act = act
193
194
195def Check(content, path, global_scope, expected_scope):
196 """Cross-checks the old and new gclient eval logic.
197
198 Safely execs |content| (backed by file |path|) using |global_scope|,
199 and compares with |expected_scope|.
200
201 Throws CheckFailure if any difference between |expected_scope| and scope
202 returned by new gclient eval code is detected.
203 """
204 def fail(prefix, exp, act):
205 raise CheckFailure(
206 'gclient check for %s: %s exp %s, got %s' % (
207 path, prefix, repr(exp), repr(act)), prefix, exp, act)
208
209 def compare(expected, actual, var_path, actual_scope):
210 if isinstance(expected, dict):
211 exp = set(expected.keys())
212 act = set(actual.keys())
213 if exp != act:
214 fail(var_path, exp, act)
215 for k in expected:
216 compare(expected[k], actual[k], var_path + '["%s"]' % k, actual_scope)
217 return
218 elif isinstance(expected, list):
219 exp = len(expected)
220 act = len(actual)
221 if exp != act:
222 fail('len(%s)' % var_path, expected_scope, actual_scope)
223 for i in range(exp):
224 compare(expected[i], actual[i], var_path + '[%d]' % i, actual_scope)
225 else:
226 if expected != actual:
227 fail(var_path, expected_scope, actual_scope)
228
229 result_scope = _gclient_exec(content, global_scope, filename=path)
230
231 compare(expected_scope, result_scope, '', result_scope)
Paweł Hajdan, Jrbeec0062017-05-10 19:51:05232
233 _GCLIENT_SCHEMA.validate(result_scope)