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