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