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