blob: 6ea2fc78e4f1d5ed61991c5e676c60c025325971 [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
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +02006import collections
Edward Lemur16f4bad2018-05-16 16:53:49 -04007import logging
Raul Tambreb946b232019-03-26 14:48:46 +00008import sys
Edward Lesmes6f64a052018-03-20 17:35:49 -04009import tokenize
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +020010
Edward Lemur16f4bad2018-05-16 16:53:49 -040011import gclient_utils
12
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020013from third_party import schema
14
Raul Tambreb946b232019-03-26 14:48:46 +000015if sys.version_info.major == 2:
16 # We use cStringIO.StringIO because it is equivalent to Py3's io.StringIO.
17 from cStringIO import StringIO
18else:
19 from io import StringIO
20
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020021
Edward Lesmes6f64a052018-03-20 17:35:49 -040022class _NodeDict(collections.MutableMapping):
23 """Dict-like type that also stores information on AST nodes and tokens."""
24 def __init__(self, data, tokens=None):
25 self.data = collections.OrderedDict(data)
26 self.tokens = tokens
27
28 def __str__(self):
Raul Tambreb946b232019-03-26 14:48:46 +000029 return str({k: v[0] for k, v in self.data.items()})
Edward Lesmes6f64a052018-03-20 17:35:49 -040030
Edward Lemura1e4d482018-12-17 19:01:03 +000031 def __repr__(self):
32 return self.__str__()
33
Edward Lesmes6f64a052018-03-20 17:35:49 -040034 def __getitem__(self, key):
35 return self.data[key][0]
36
37 def __setitem__(self, key, value):
38 self.data[key] = (value, None)
39
40 def __delitem__(self, key):
41 del self.data[key]
42
43 def __iter__(self):
44 return iter(self.data)
45
46 def __len__(self):
47 return len(self.data)
48
Edward Lesmes3d993812018-04-02 12:52:49 -040049 def MoveTokens(self, origin, delta):
50 if self.tokens:
51 new_tokens = {}
52 for pos, token in self.tokens.iteritems():
53 if pos[0] >= origin:
54 pos = (pos[0] + delta, pos[1])
55 token = token[:2] + (pos,) + token[3:]
56 new_tokens[pos] = token
57
58 for value, node in self.data.values():
59 if node.lineno >= origin:
60 node.lineno += delta
61 if isinstance(value, _NodeDict):
62 value.MoveTokens(origin, delta)
63
Edward Lesmes6f64a052018-03-20 17:35:49 -040064 def GetNode(self, key):
65 return self.data[key][1]
66
Edward Lesmes6c24d372018-03-28 12:52:29 -040067 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040068 self.data[key] = (value, node)
69
70
71def _NodeDictSchema(dict_schema):
72 """Validate dict_schema after converting _NodeDict to a regular dict."""
73 def validate(d):
74 schema.Schema(dict_schema).validate(dict(d))
75 return True
76 return validate
77
78
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020079# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -040080_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Raul Tambreb946b232019-03-26 14:48:46 +000081 schema.Optional(str):
82 schema.Or(
83 None,
84 str,
85 _NodeDictSchema({
86 # Repo and revision to check out under the path
87 # (same as if no dict was used).
88 'url':
89 schema.Or(None, str),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020090
Raul Tambreb946b232019-03-26 14:48:46 +000091 # Optional condition string. The dep will only be processed
92 # if the condition evaluates to True.
93 schema.Optional('condition'):
94 str,
95 schema.Optional('dep_type', default='git'):
96 str,
97 }),
98 # CIPD package.
99 _NodeDictSchema({
100 'packages': [
101 _NodeDictSchema({
102 'package': str,
103 'version': str,
104 })
105 ],
106 schema.Optional('condition'):
107 str,
108 schema.Optional('dep_type', default='cipd'):
109 str,
110 }),
111 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400112})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200113
Raul Tambreb946b232019-03-26 14:48:46 +0000114_GCLIENT_HOOKS_SCHEMA = [
115 _NodeDictSchema({
116 # Hook action: list of command-line arguments to invoke.
117 'action': [str],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200118
Raul Tambreb946b232019-03-26 14:48:46 +0000119 # Name of the hook. Doesn't affect operation.
120 schema.Optional('name'):
121 str,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200122
Raul Tambreb946b232019-03-26 14:48:46 +0000123 # Hook pattern (regex). Originally intended to limit some hooks to run
124 # only when files matching the pattern have changed. In practice, with
125 # git, gclient runs all the hooks regardless of this field.
126 schema.Optional('pattern'):
127 str,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200128
Raul Tambreb946b232019-03-26 14:48:46 +0000129 # Working directory where to execute the hook.
130 schema.Optional('cwd'):
131 str,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200132
Raul Tambreb946b232019-03-26 14:48:46 +0000133 # Optional condition string. The hook will only be run
134 # if the condition evaluates to True.
135 schema.Optional('condition'):
136 str,
137 })
138]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200139
Raul Tambreb946b232019-03-26 14:48:46 +0000140_GCLIENT_SCHEMA = schema.Schema(
141 _NodeDictSchema({
142 # List of host names from which dependencies are allowed (whitelist).
143 # NOTE: when not present, all hosts are allowed.
144 # NOTE: scoped to current DEPS file, not recursive.
145 schema.Optional('allowed_hosts'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200146
Raul Tambreb946b232019-03-26 14:48:46 +0000147 # Mapping from paths to repo and revision to check out under that path.
148 # Applying this mapping to the on-disk checkout is the main purpose
149 # of gclient, and also why the config file is called DEPS.
150 #
151 # The following functions are allowed:
152 #
153 # Var(): allows variable substitution (either from 'vars' dict below,
154 # or command-line override)
155 schema.Optional('deps'):
156 _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200157
Raul Tambreb946b232019-03-26 14:48:46 +0000158 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
159 # Also see 'target_os'.
160 schema.Optional('deps_os'):
161 _NodeDictSchema({
162 schema.Optional(str): _GCLIENT_DEPS_SCHEMA,
163 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200164
Raul Tambreb946b232019-03-26 14:48:46 +0000165 # Dependency to get gclient_gn_args* settings from. This allows these
166 # values to be set in a recursedeps file, rather than requiring that
167 # they exist in the top-level solution.
168 schema.Optional('gclient_gn_args_from'):
169 str,
Michael Moss848c86e2018-05-03 16:05:50 -0700170
Raul Tambreb946b232019-03-26 14:48:46 +0000171 # Path to GN args file to write selected variables.
172 schema.Optional('gclient_gn_args_file'):
173 str,
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200174
Raul Tambreb946b232019-03-26 14:48:46 +0000175 # Subset of variables to write to the GN args file (see above).
176 schema.Optional('gclient_gn_args'): [schema.Optional(str)],
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200177
Raul Tambreb946b232019-03-26 14:48:46 +0000178 # Hooks executed after gclient sync (unless suppressed), or explicitly
179 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
180 # Also see 'pre_deps_hooks'.
181 schema.Optional('hooks'):
182 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200183
Raul Tambreb946b232019-03-26 14:48:46 +0000184 # Similar to 'hooks', also keyed by OS.
185 schema.Optional('hooks_os'):
186 _NodeDictSchema({
187 schema.Optional(str): _GCLIENT_HOOKS_SCHEMA
188 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700189
Raul Tambreb946b232019-03-26 14:48:46 +0000190 # Rules which #includes are allowed in the directory.
191 # Also see 'skip_child_includes' and 'specific_include_rules'.
192 schema.Optional('include_rules'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200193
Raul Tambreb946b232019-03-26 14:48:46 +0000194 # Hooks executed before processing DEPS. See 'hooks' for more details.
195 schema.Optional('pre_deps_hooks'):
196 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200197
Raul Tambreb946b232019-03-26 14:48:46 +0000198 # Recursion limit for nested DEPS.
199 schema.Optional('recursion'):
200 int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200201
Raul Tambreb946b232019-03-26 14:48:46 +0000202 # Whitelists deps for which recursion should be enabled.
203 schema.Optional('recursedeps'): [
204 schema.Optional(schema.Or(str, (str, str), [str, str])),
205 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200206
Raul Tambreb946b232019-03-26 14:48:46 +0000207 # Blacklists directories for checking 'include_rules'.
208 schema.Optional('skip_child_includes'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200209
Raul Tambreb946b232019-03-26 14:48:46 +0000210 # Mapping from paths to include rules specific for that path.
211 # See 'include_rules' for more details.
212 schema.Optional('specific_include_rules'):
213 _NodeDictSchema({
214 schema.Optional(str): [str]
215 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200216
Raul Tambreb946b232019-03-26 14:48:46 +0000217 # List of additional OS names to consider when selecting dependencies
218 # from deps_os.
219 schema.Optional('target_os'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200220
Raul Tambreb946b232019-03-26 14:48:46 +0000221 # For recursed-upon sub-dependencies, check out their own dependencies
222 # relative to the parent's path, rather than relative to the .gclient
223 # file.
224 schema.Optional('use_relative_paths'):
225 bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200226
Raul Tambreb946b232019-03-26 14:48:46 +0000227 # For recursed-upon sub-dependencies, run their hooks relative to the
228 # parent's path instead of relative to the .gclient file.
229 schema.Optional('use_relative_hooks'):
230 bool,
Corentin Walleza68660d2018-09-10 17:33:24 +0000231
Raul Tambreb946b232019-03-26 14:48:46 +0000232 # Variables that can be referenced using Var() - see 'deps'.
233 schema.Optional('vars'):
234 _NodeDictSchema({
235 schema.Optional(str): schema.Or(str, bool),
236 }),
237 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200238
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200239
Edward Lemure05f18d2018-06-08 17:36:53 +0000240def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200241 """Safely evaluates a single expression. Returns the result."""
242 _allowed_names = {'None': None, 'True': True, 'False': False}
Raul Tambreb946b232019-03-26 14:48:46 +0000243 if isinstance(node_or_string, str):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200244 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
245 if isinstance(node_or_string, ast.Expression):
246 node_or_string = node_or_string.body
247 def _convert(node):
248 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000249 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000250 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400251 try:
252 return node.s.format(**vars_dict)
253 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000254 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400255 '%s was used as a variable, but was not declared in the vars dict '
256 '(file %r, line %s)' % (
257 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200258 elif isinstance(node, ast.Num):
259 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200260 elif isinstance(node, ast.Tuple):
261 return tuple(map(_convert, node.elts))
262 elif isinstance(node, ast.List):
263 return list(map(_convert, node.elts))
264 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400265 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200266 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200267 elif isinstance(node, ast.Name):
268 if node.id not in _allowed_names:
269 raise ValueError(
270 'invalid name %r (file %r, line %s)' % (
271 node.id, filename, getattr(node, 'lineno', '<unknown>')))
272 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000273 elif not sys.version_info[:2] < (3, 4) and isinstance(
274 node, ast.NameConstant): # Since Python 3.4
275 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200276 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400277 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200278 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400279 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200280 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000281 if node.keywords or getattr(node, 'starargs', None) or getattr(
282 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200283 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400284 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200285 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400286 arg = _convert(node.args[0])
Raul Tambreb946b232019-03-26 14:48:46 +0000287 if not isinstance(arg, str):
Edward Lesmes9f531292018-03-20 21:27:15 -0400288 raise ValueError(
289 'Var\'s argument must be a variable name (file %r, line %s)' % (
290 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400291 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000292 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400293 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000294 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400295 '%s was used as a variable, but was not declared in the vars dict '
296 '(file %r, line %s)' % (
297 arg, filename, getattr(node, 'lineno', '<unknown>')))
298 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200299 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
300 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200301 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
302 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200303 else:
304 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200305 'unexpected AST node: %s %s (file %r, line %s)' % (
306 node, ast.dump(node), filename,
307 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200308 return _convert(node_or_string)
309
310
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000311def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400312 """Safely execs a set of assignments."""
313 def _validate_statement(node, local_scope):
314 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200315 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200316 'unexpected AST node: %s %s (file %r, line %s)' % (
317 node, ast.dump(node), filename,
318 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200319
Edward Lesmes6c24d372018-03-28 12:52:29 -0400320 if len(node.targets) != 1:
321 raise ValueError(
322 'invalid assignment: use exactly one target (file %r, line %s)' % (
323 filename, getattr(node, 'lineno', '<unknown>')))
324
325 target = node.targets[0]
326 if not isinstance(target, ast.Name):
327 raise ValueError(
328 'invalid assignment: target should be a name (file %r, line %s)' % (
329 filename, getattr(node, 'lineno', '<unknown>')))
330 if target.id in local_scope:
331 raise ValueError(
332 'invalid assignment: overrides var %r (file %r, line %s)' % (
333 target.id, filename, getattr(node, 'lineno', '<unknown>')))
334
335 node_or_string = ast.parse(content, filename=filename, mode='exec')
336 if isinstance(node_or_string, ast.Expression):
337 node_or_string = node_or_string.body
338
339 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200340 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200341 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200342 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200343 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200344 filename,
345 getattr(node_or_string, 'lineno', '<unknown>')))
346
Edward Lesmes6c24d372018-03-28 12:52:29 -0400347 statements = {}
348 for statement in node_or_string.body:
349 _validate_statement(statement, statements)
350 statements[statement.targets[0].id] = statement.value
351
Raul Tambreb946b232019-03-26 14:48:46 +0000352 # The tokenized representation needs to end with a newline token, otherwise
353 # untokenization will trigger an assert later on.
354 # In Python 2.7 on Windows we need to ensure the input ends with a newline
355 # for a newline token to be generated.
356 # In other cases a newline token is always generated during tokenization so
357 # this has no effect.
358 # TODO: Remove this workaround after migrating to Python 3.
359 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400360 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000361 token[2]: list(token) for token in tokenize.generate_tokens(
362 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400363 }
Raul Tambreb946b232019-03-26 14:48:46 +0000364
Edward Lesmes6c24d372018-03-28 12:52:29 -0400365 local_scope = _NodeDict({}, tokens)
366
367 # Process vars first, so we can expand variables in the rest of the DEPS file.
368 vars_dict = {}
369 if 'vars' in statements:
370 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000371 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400372 local_scope.SetNode('vars', value, vars_statement)
373 # Update the parsed vars with the overrides, but only if they are already
374 # present (overrides do not introduce new variables).
375 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000376
377 if builtin_vars:
378 vars_dict.update(builtin_vars)
379
380 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000381 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400382
Raul Tambreb946b232019-03-26 14:48:46 +0000383 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000384 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400385 local_scope.SetNode(name, value, node)
386
John Budorick0f7b2002018-01-19 15:46:17 -0800387 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200388
389
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000390def ExecLegacy(content, filename='<unknown>', vars_override=None,
391 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400392 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400393 local_scope = {}
394 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
395
396 # If we use 'exec' directly, it complains that 'Parse' contains a nested
397 # function with free variables.
398 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
399 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
400 eval(compile(content, filename, 'exec'), global_scope, local_scope)
401
Edward Lesmes6c24d372018-03-28 12:52:29 -0400402 vars_dict = {}
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000403 vars_dict.update(local_scope.get('vars', {}))
404 if builtin_vars:
405 vars_dict.update(builtin_vars)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400406 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000407 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400408
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000409 if not vars_dict:
410 return local_scope
411
Edward Lesmes6c24d372018-03-28 12:52:29 -0400412 def _DeepFormat(node):
Raul Tambreb946b232019-03-26 14:48:46 +0000413 if isinstance(node, str):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400414 return node.format(**vars_dict)
415 elif isinstance(node, dict):
Raul Tambreb946b232019-03-26 14:48:46 +0000416 return {k.format(**vars_dict): _DeepFormat(v) for k, v in node.items()}
Edward Lesmes6c24d372018-03-28 12:52:29 -0400417 elif isinstance(node, list):
418 return [_DeepFormat(elem) for elem in node]
419 elif isinstance(node, tuple):
420 return tuple(_DeepFormat(elem) for elem in node)
421 else:
422 return node
423
424 return _DeepFormat(local_scope)
425
426
Edward Lemur16f4bad2018-05-16 16:53:49 -0400427def _StandardizeDeps(deps_dict, vars_dict):
428 """"Standardizes the deps_dict.
429
430 For each dependency:
431 - Expands the variable in the dependency name.
432 - Ensures the dependency is a dictionary.
433 - Set's the 'dep_type' to be 'git' by default.
434 """
435 new_deps_dict = {}
436 for dep_name, dep_info in deps_dict.items():
437 dep_name = dep_name.format(**vars_dict)
438 if not isinstance(dep_info, collections.Mapping):
439 dep_info = {'url': dep_info}
440 dep_info.setdefault('dep_type', 'git')
441 new_deps_dict[dep_name] = dep_info
442 return new_deps_dict
443
444
445def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
446 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
447
448 The dependencies in os_deps_dict are transformed into conditional dependencies
449 using |'checkout_' + os_name|.
450 If the dependency is already present, the URL and revision must coincide.
451 """
452 for dep_name, dep_info in os_deps_dict.items():
453 # Make this condition very visible, so it's not a silent failure.
454 # It's unclear how to support None override in deps_os.
455 if dep_info['url'] is None:
456 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
457 continue
458
459 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
460 UpdateCondition(dep_info, 'and', os_condition)
461
462 if dep_name in deps_dict:
463 if deps_dict[dep_name]['url'] != dep_info['url']:
464 raise gclient_utils.Error(
465 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
466 'entry (%r).' % (
467 os_name, dep_name, dep_info, deps_dict[dep_name]))
468
469 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
470
471 deps_dict[dep_name] = dep_info
472
473
474def UpdateCondition(info_dict, op, new_condition):
475 """Updates info_dict's condition with |new_condition|.
476
477 An absent value is treated as implicitly True.
478 """
479 curr_condition = info_dict.get('condition')
480 # Easy case: Both are present.
481 if curr_condition and new_condition:
482 info_dict['condition'] = '(%s) %s (%s)' % (
483 curr_condition, op, new_condition)
484 # If |op| == 'and', and at least one condition is present, then use it.
485 elif op == 'and' and (curr_condition or new_condition):
486 info_dict['condition'] = curr_condition or new_condition
487 # Otherwise, no condition should be set
488 elif curr_condition:
489 del info_dict['condition']
490
491
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000492def Parse(content, validate_syntax, filename, vars_override=None,
493 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400494 """Parses DEPS strings.
495
496 Executes the Python-like string stored in content, resulting in a Python
497 dictionary specifyied by the schema above. Supports syntax validation and
498 variable expansion.
499
500 Args:
501 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400502 validate_syntax: bool. Whether syntax should be validated using the schema
503 defined above.
504 filename: str. The name of the DEPS file, or a string describing the source
505 of the content, e.g. '<string>', '<unknown>'.
506 vars_override: dict, optional. A dictionary with overrides for the variables
507 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000508 builtin_vars: dict, optional. A dictionary with variables that are provided
509 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400510
511 Returns:
512 A Python dict with the parsed contents of the DEPS file, as specified by the
513 schema above.
514 """
515 if validate_syntax:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000516 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400517 else:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000518 result = ExecLegacy(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400519
520 vars_dict = result.get('vars', {})
521 if 'deps' in result:
522 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
523
524 if 'deps_os' in result:
525 deps = result.setdefault('deps', {})
526 for os_name, os_deps in result['deps_os'].iteritems():
527 os_deps = _StandardizeDeps(os_deps, vars_dict)
528 _MergeDepsOs(deps, os_deps, os_name)
529 del result['deps_os']
530
531 if 'hooks_os' in result:
532 hooks = result.setdefault('hooks', [])
533 for os_name, os_hooks in result['hooks_os'].iteritems():
534 for hook in os_hooks:
535 UpdateCondition(hook, 'and', 'checkout_' + os_name)
536 hooks.extend(os_hooks)
537 del result['hooks_os']
538
539 return result
540
541
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200542def EvaluateCondition(condition, variables, referenced_variables=None):
543 """Safely evaluates a boolean condition. Returns the result."""
544 if not referenced_variables:
545 referenced_variables = set()
546 _allowed_names = {'None': None, 'True': True, 'False': False}
547 main_node = ast.parse(condition, mode='eval')
548 if isinstance(main_node, ast.Expression):
549 main_node = main_node.body
550 def _convert(node):
551 if isinstance(node, ast.Str):
552 return node.s
553 elif isinstance(node, ast.Name):
554 if node.id in referenced_variables:
555 raise ValueError(
556 'invalid cyclic reference to %r (inside %r)' % (
557 node.id, condition))
558 elif node.id in _allowed_names:
559 return _allowed_names[node.id]
560 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200561 value = variables[node.id]
562
563 # Allow using "native" types, without wrapping everything in strings.
564 # Note that schema constraints still apply to variables.
Raul Tambreb946b232019-03-26 14:48:46 +0000565 if not isinstance(value, str):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200566 return value
567
568 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200569 return EvaluateCondition(
570 variables[node.id],
571 variables,
572 referenced_variables.union([node.id]))
573 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200574 # Implicitly convert unrecognized names to strings.
575 # If we want to change this, we'll need to explicitly distinguish
576 # between arguments for GN to be passed verbatim, and ones to
577 # be evaluated.
578 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200579 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
580 if len(node.values) != 2:
581 raise ValueError(
582 'invalid "or": exactly 2 operands required (inside %r)' % (
583 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200584 left = _convert(node.values[0])
585 right = _convert(node.values[1])
586 if not isinstance(left, bool):
587 raise ValueError(
588 'invalid "or" operand %r (inside %r)' % (left, condition))
589 if not isinstance(right, bool):
590 raise ValueError(
591 'invalid "or" operand %r (inside %r)' % (right, condition))
592 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200593 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
594 if len(node.values) != 2:
595 raise ValueError(
596 'invalid "and": exactly 2 operands required (inside %r)' % (
597 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200598 left = _convert(node.values[0])
599 right = _convert(node.values[1])
600 if not isinstance(left, bool):
601 raise ValueError(
602 'invalid "and" operand %r (inside %r)' % (left, condition))
603 if not isinstance(right, bool):
604 raise ValueError(
605 'invalid "and" operand %r (inside %r)' % (right, condition))
606 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200607 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200608 value = _convert(node.operand)
609 if not isinstance(value, bool):
610 raise ValueError(
611 'invalid "not" operand %r (inside %r)' % (value, condition))
612 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200613 elif isinstance(node, ast.Compare):
614 if len(node.ops) != 1:
615 raise ValueError(
616 'invalid compare: exactly 1 operator required (inside %r)' % (
617 condition))
618 if len(node.comparators) != 1:
619 raise ValueError(
620 'invalid compare: exactly 1 comparator required (inside %r)' % (
621 condition))
622
623 left = _convert(node.left)
624 right = _convert(node.comparators[0])
625
626 if isinstance(node.ops[0], ast.Eq):
627 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700628 if isinstance(node.ops[0], ast.NotEq):
629 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200630
631 raise ValueError(
632 'unexpected operator: %s %s (inside %r)' % (
633 node.ops[0], ast.dump(node), condition))
634 else:
635 raise ValueError(
636 'unexpected AST node: %s %s (inside %r)' % (
637 node, ast.dump(node), condition))
638 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400639
640
641def RenderDEPSFile(gclient_dict):
642 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000643 # The last token is a newline, which we ensure in Exec() for compatibility.
644 # However tests pass in inputs not ending with a newline and expect the same
645 # back, so for backwards compatibility need to remove that newline character.
646 # TODO: Fix tests to expect the newline
647 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400648
649
650def _UpdateAstString(tokens, node, value):
651 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000652 quote_char = ''
653 if isinstance(node, ast.Str):
654 quote_char = tokens[position][1][0]
Edward Lesmes62af4e42018-03-30 18:15:44 -0400655 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400656 node.s = value
657
658
Edward Lesmes3d993812018-04-02 12:52:49 -0400659def _ShiftLinesInTokens(tokens, delta, start):
660 new_tokens = {}
661 for token in tokens.values():
662 if token[2][0] >= start:
663 token[2] = token[2][0] + delta, token[2][1]
664 token[3] = token[3][0] + delta, token[3][1]
665 new_tokens[token[2]] = token
666 return new_tokens
667
668
669def AddVar(gclient_dict, var_name, value):
670 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
671 raise ValueError(
672 "Can't use SetVar for the given gclient dict. It contains no "
673 "formatting information.")
674
675 if 'vars' not in gclient_dict:
676 raise KeyError("vars dict is not defined.")
677
678 if var_name in gclient_dict['vars']:
679 raise ValueError(
680 "%s has already been declared in the vars dict. Consider using SetVar "
681 "instead." % var_name)
682
683 if not gclient_dict['vars']:
684 raise ValueError('vars dict is empty. This is not yet supported.')
685
Edward Lesmes8d626572018-04-05 17:53:10 -0400686 # We will attempt to add the var right after 'vars = {'.
687 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400688 if node is None:
689 raise ValueError(
690 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400691 line = node.lineno + 1
692
693 # We will try to match the new var's indentation to the next variable.
694 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400695
696 # We use a minimal Python dictionary, so that ast can parse it.
697 var_content = '{\n%s"%s": "%s",\n}' % (' ' * col, var_name, value)
698 var_ast = ast.parse(var_content).body[0].value
699
700 # Set the ast nodes for the key and value.
701 vars_node = gclient_dict.GetNode('vars')
702
703 var_name_node = var_ast.keys[0]
704 var_name_node.lineno += line - 2
705 vars_node.keys.insert(0, var_name_node)
706
707 value_node = var_ast.values[0]
708 value_node.lineno += line - 2
709 vars_node.values.insert(0, value_node)
710
711 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000712 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400713 var_tokens = {
714 token[2]: list(token)
715 # Ignore the tokens corresponding to braces and new lines.
716 for token in var_tokens[2:-2]
717 }
718
719 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
720 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
721
722
Edward Lesmes6f64a052018-03-20 17:35:49 -0400723def SetVar(gclient_dict, var_name, value):
724 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
725 raise ValueError(
726 "Can't use SetVar for the given gclient dict. It contains no "
727 "formatting information.")
728 tokens = gclient_dict.tokens
729
Edward Lesmes3d993812018-04-02 12:52:49 -0400730 if 'vars' not in gclient_dict:
731 raise KeyError("vars dict is not defined.")
732
733 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400734 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400735 "%s has not been declared in the vars dict. Consider using AddVar "
736 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400737
738 node = gclient_dict['vars'].GetNode(var_name)
739 if node is None:
740 raise ValueError(
741 "The vars entry for %s has no formatting information." % var_name)
742
743 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400744 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400745
746
Edward Lemura1e4d482018-12-17 19:01:03 +0000747def _GetVarName(node):
748 if isinstance(node, ast.Call):
749 return node.args[0].s
750 elif node.s.endswith('}'):
751 last_brace = node.s.rfind('{')
752 return node.s[last_brace+1:-1]
753 return None
754
755
Edward Lesmes6f64a052018-03-20 17:35:49 -0400756def SetCIPD(gclient_dict, dep_name, package_name, new_version):
757 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
758 raise ValueError(
759 "Can't use SetCIPD for the given gclient dict. It contains no "
760 "formatting information.")
761 tokens = gclient_dict.tokens
762
763 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400764 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400765 "Could not find any dependency called %s." % dep_name)
766
767 # Find the package with the given name
768 packages = [
769 package
770 for package in gclient_dict['deps'][dep_name]['packages']
771 if package['package'] == package_name
772 ]
773 if len(packages) != 1:
774 raise ValueError(
775 "There must be exactly one package with the given name (%s), "
776 "%s were found." % (package_name, len(packages)))
777
778 # TODO(ehmaldonado): Support Var in package's version.
779 node = packages[0].GetNode('version')
780 if node is None:
781 raise ValueError(
782 "The deps entry for %s:%s has no formatting information." %
783 (dep_name, package_name))
784
Edward Lemura1e4d482018-12-17 19:01:03 +0000785 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
786 raise ValueError(
787 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000788 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000789
790 var_name = _GetVarName(node)
791 if var_name is not None:
792 SetVar(gclient_dict, var_name, new_version)
793 else:
794 _UpdateAstString(tokens, node, new_version)
795 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400796
797
Edward Lesmes9f531292018-03-20 21:27:15 -0400798def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400799 def _UpdateRevision(dep_dict, dep_key, new_revision):
800 dep_node = dep_dict.GetNode(dep_key)
801 if dep_node is None:
802 raise ValueError(
803 "The deps entry for %s has no formatting information." % dep_name)
804
805 node = dep_node
806 if isinstance(node, ast.BinOp):
807 node = node.right
808
809 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
810 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000811 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000812 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400813
814 var_name = _GetVarName(node)
815 if var_name is not None:
816 SetVar(gclient_dict, var_name, new_revision)
817 else:
818 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400819 # '@' is part of the last string, which we want to modify. Discard
820 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400821 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400822 elif '@' not in dep_dict[dep_key]:
823 # '@' is not part of the URL at all. This mean the dependency is
824 # unpinned and we should pin it.
825 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400826 _UpdateAstString(tokens, node, new_revision)
827 dep_dict.SetNode(dep_key, new_revision, node)
828
Edward Lesmes6f64a052018-03-20 17:35:49 -0400829 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
830 raise ValueError(
831 "Can't use SetRevision for the given gclient dict. It contains no "
832 "formatting information.")
833 tokens = gclient_dict.tokens
834
835 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400836 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400837 "Could not find any dependency called %s." % dep_name)
838
Edward Lesmes6f64a052018-03-20 17:35:49 -0400839 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400840 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400841 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400842 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400843
844
845def GetVar(gclient_dict, var_name):
846 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
847 raise KeyError(
848 "Could not find any variable called %s." % var_name)
849
850 return gclient_dict['vars'][var_name]
851
852
853def GetCIPD(gclient_dict, dep_name, package_name):
854 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
855 raise KeyError(
856 "Could not find any dependency called %s." % dep_name)
857
858 # Find the package with the given name
859 packages = [
860 package
861 for package in gclient_dict['deps'][dep_name]['packages']
862 if package['package'] == package_name
863 ]
864 if len(packages) != 1:
865 raise ValueError(
866 "There must be exactly one package with the given name (%s), "
867 "%s were found." % (package_name, len(packages)))
868
Edward Lemura92b9612018-07-03 02:34:32 +0000869 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400870
871
872def GetRevision(gclient_dict, dep_name):
873 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
874 raise KeyError(
875 "Could not find any dependency called %s." % dep_name)
876
877 dep = gclient_dict['deps'][dep_name]
878 if dep is None:
879 return None
880 elif isinstance(dep, basestring):
881 _, _, revision = dep.partition('@')
882 return revision or None
883 elif isinstance(dep, collections.Mapping) and 'url' in dep:
884 _, _, revision = dep['url'].partition('@')
885 return revision or None
886 else:
887 raise ValueError(
888 '%s is not a valid git dependency.' % dep_name)