blob: dd39823fd1acb84fff60bd99470ff16d55f0d09d [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
Edward Lesmes6f64a052018-03-20 17:35:49 -04006import cStringIO
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +02007import collections
Edward Lemur16f4bad2018-05-16 16:53:49 -04008import logging
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
15
Edward Lesmes6f64a052018-03-20 17:35:49 -040016class _NodeDict(collections.MutableMapping):
17 """Dict-like type that also stores information on AST nodes and tokens."""
18 def __init__(self, data, tokens=None):
19 self.data = collections.OrderedDict(data)
20 self.tokens = tokens
21
22 def __str__(self):
23 return str({k: v[0] for k, v in self.data.iteritems()})
24
25 def __getitem__(self, key):
26 return self.data[key][0]
27
28 def __setitem__(self, key, value):
29 self.data[key] = (value, None)
30
31 def __delitem__(self, key):
32 del self.data[key]
33
34 def __iter__(self):
35 return iter(self.data)
36
37 def __len__(self):
38 return len(self.data)
39
Edward Lesmes3d993812018-04-02 12:52:49 -040040 def MoveTokens(self, origin, delta):
41 if self.tokens:
42 new_tokens = {}
43 for pos, token in self.tokens.iteritems():
44 if pos[0] >= origin:
45 pos = (pos[0] + delta, pos[1])
46 token = token[:2] + (pos,) + token[3:]
47 new_tokens[pos] = token
48
49 for value, node in self.data.values():
50 if node.lineno >= origin:
51 node.lineno += delta
52 if isinstance(value, _NodeDict):
53 value.MoveTokens(origin, delta)
54
Edward Lesmes6f64a052018-03-20 17:35:49 -040055 def GetNode(self, key):
56 return self.data[key][1]
57
Edward Lesmes6c24d372018-03-28 12:52:29 -040058 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040059 self.data[key] = (value, node)
60
61
62def _NodeDictSchema(dict_schema):
63 """Validate dict_schema after converting _NodeDict to a regular dict."""
64 def validate(d):
65 schema.Schema(dict_schema).validate(dict(d))
66 return True
67 return validate
68
69
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020070# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -040071_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020072 schema.Optional(basestring): schema.Or(
73 None,
74 basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040075 _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020076 # Repo and revision to check out under the path
77 # (same as if no dict was used).
Michael Moss012013e2018-03-30 17:03:19 -070078 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020079
80 # Optional condition string. The dep will only be processed
81 # if the condition evaluates to True.
82 schema.Optional('condition'): basestring,
John Budorick0f7b2002018-01-19 15:46:17 -080083
84 schema.Optional('dep_type', default='git'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040085 }),
John Budorick0f7b2002018-01-19 15:46:17 -080086 # CIPD package.
Edward Lesmes6f64a052018-03-20 17:35:49 -040087 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080088 'packages': [
Edward Lesmes6f64a052018-03-20 17:35:49 -040089 _NodeDictSchema({
John Budorick0f7b2002018-01-19 15:46:17 -080090 'package': basestring,
91
92 'version': basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040093 })
John Budorick0f7b2002018-01-19 15:46:17 -080094 ],
95
96 schema.Optional('condition'): basestring,
97
98 schema.Optional('dep_type', default='cipd'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -040099 }),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200100 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400101})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200102
Edward Lesmes6f64a052018-03-20 17:35:49 -0400103_GCLIENT_HOOKS_SCHEMA = [_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200104 # Hook action: list of command-line arguments to invoke.
105 'action': [basestring],
106
107 # Name of the hook. Doesn't affect operation.
108 schema.Optional('name'): basestring,
109
110 # Hook pattern (regex). Originally intended to limit some hooks to run
111 # only when files matching the pattern have changed. In practice, with git,
112 # gclient runs all the hooks regardless of this field.
113 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200114
115 # Working directory where to execute the hook.
116 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200117
118 # Optional condition string. The hook will only be run
119 # if the condition evaluates to True.
120 schema.Optional('condition'): basestring,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400121})]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200122
Edward Lesmes6f64a052018-03-20 17:35:49 -0400123_GCLIENT_SCHEMA = schema.Schema(_NodeDictSchema({
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200124 # List of host names from which dependencies are allowed (whitelist).
125 # NOTE: when not present, all hosts are allowed.
126 # NOTE: scoped to current DEPS file, not recursive.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200127 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200128
129 # Mapping from paths to repo and revision to check out under that path.
130 # Applying this mapping to the on-disk checkout is the main purpose
131 # of gclient, and also why the config file is called DEPS.
132 #
133 # The following functions are allowed:
134 #
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200135 # Var(): allows variable substitution (either from 'vars' dict below,
136 # or command-line override)
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200137 schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200138
139 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200140 # Also see 'target_os'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400141 schema.Optional('deps_os'): _NodeDictSchema({
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200142 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
Edward Lesmes6f64a052018-03-20 17:35:49 -0400143 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200144
Michael Moss848c86e2018-05-03 16:05:50 -0700145 # Dependency to get gclient_gn_args* settings from. This allows these values
146 # to be set in a recursedeps file, rather than requiring that they exist in
147 # the top-level solution.
148 schema.Optional('gclient_gn_args_from'): basestring,
149
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200150 # Path to GN args file to write selected variables.
151 schema.Optional('gclient_gn_args_file'): basestring,
152
153 # Subset of variables to write to the GN args file (see above).
154 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
155
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200156 # Hooks executed after gclient sync (unless suppressed), or explicitly
157 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
158 # Also see 'pre_deps_hooks'.
159 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
160
Scott Grahamc4826742017-05-11 16:59:23 -0700161 # Similar to 'hooks', also keyed by OS.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400162 schema.Optional('hooks_os'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200163 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
Edward Lesmes6f64a052018-03-20 17:35:49 -0400164 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700165
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200166 # Rules which #includes are allowed in the directory.
167 # Also see 'skip_child_includes' and 'specific_include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200168 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200169
170 # Hooks executed before processing DEPS. See 'hooks' for more details.
171 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
172
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200173 # Recursion limit for nested DEPS.
174 schema.Optional('recursion'): int,
175
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200176 # Whitelists deps for which recursion should be enabled.
177 schema.Optional('recursedeps'): [
Paweł Hajdan, Jr05fec032017-05-30 23:04:23 +0200178 schema.Optional(schema.Or(
179 basestring,
180 (basestring, basestring),
181 [basestring, basestring]
182 )),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200183 ],
184
185 # Blacklists directories for checking 'include_rules'.
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200186 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200187
188 # Mapping from paths to include rules specific for that path.
189 # See 'include_rules' for more details.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400190 schema.Optional('specific_include_rules'): _NodeDictSchema({
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200191 schema.Optional(basestring): [basestring]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400192 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200193
194 # List of additional OS names to consider when selecting dependencies
195 # from deps_os.
196 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200197
198 # For recursed-upon sub-dependencies, check out their own dependencies
199 # relative to the paren't path, rather than relative to the .gclient file.
200 schema.Optional('use_relative_paths'): bool,
201
202 # Variables that can be referenced using Var() - see 'deps'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400203 schema.Optional('vars'): _NodeDictSchema({
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200204 schema.Optional(basestring): schema.Or(basestring, bool),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400205 }),
206}))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200207
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200208
Edward Lemure05f18d2018-06-08 17:36:53 +0000209def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200210 """Safely evaluates a single expression. Returns the result."""
211 _allowed_names = {'None': None, 'True': True, 'False': False}
212 if isinstance(node_or_string, basestring):
213 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
214 if isinstance(node_or_string, ast.Expression):
215 node_or_string = node_or_string.body
216 def _convert(node):
217 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000218 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000219 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400220 try:
221 return node.s.format(**vars_dict)
222 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000223 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400224 '%s was used as a variable, but was not declared in the vars dict '
225 '(file %r, line %s)' % (
226 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200227 elif isinstance(node, ast.Num):
228 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200229 elif isinstance(node, ast.Tuple):
230 return tuple(map(_convert, node.elts))
231 elif isinstance(node, ast.List):
232 return list(map(_convert, node.elts))
233 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400234 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200235 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200236 elif isinstance(node, ast.Name):
237 if node.id not in _allowed_names:
238 raise ValueError(
239 'invalid name %r (file %r, line %s)' % (
240 node.id, filename, getattr(node, 'lineno', '<unknown>')))
241 return _allowed_names[node.id]
242 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400243 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200244 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400245 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200246 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400247 if node.keywords or node.starargs or node.kwargs or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200248 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400249 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200250 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400251 arg = _convert(node.args[0])
252 if not isinstance(arg, basestring):
253 raise ValueError(
254 'Var\'s argument must be a variable name (file %r, line %s)' % (
255 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400256 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000257 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400258 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000259 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400260 '%s was used as a variable, but was not declared in the vars dict '
261 '(file %r, line %s)' % (
262 arg, filename, getattr(node, 'lineno', '<unknown>')))
263 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200264 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
265 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200266 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
267 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200268 else:
269 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200270 'unexpected AST node: %s %s (file %r, line %s)' % (
271 node, ast.dump(node), filename,
272 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200273 return _convert(node_or_string)
274
275
Edward Lemure05f18d2018-06-08 17:36:53 +0000276def Exec(content, filename='<unknown>', vars_override=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400277 """Safely execs a set of assignments."""
278 def _validate_statement(node, local_scope):
279 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200280 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200281 'unexpected AST node: %s %s (file %r, line %s)' % (
282 node, ast.dump(node), filename,
283 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200284
Edward Lesmes6c24d372018-03-28 12:52:29 -0400285 if len(node.targets) != 1:
286 raise ValueError(
287 'invalid assignment: use exactly one target (file %r, line %s)' % (
288 filename, getattr(node, 'lineno', '<unknown>')))
289
290 target = node.targets[0]
291 if not isinstance(target, ast.Name):
292 raise ValueError(
293 'invalid assignment: target should be a name (file %r, line %s)' % (
294 filename, getattr(node, 'lineno', '<unknown>')))
295 if target.id in local_scope:
296 raise ValueError(
297 'invalid assignment: overrides var %r (file %r, line %s)' % (
298 target.id, filename, getattr(node, 'lineno', '<unknown>')))
299
300 node_or_string = ast.parse(content, filename=filename, mode='exec')
301 if isinstance(node_or_string, ast.Expression):
302 node_or_string = node_or_string.body
303
304 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200305 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200306 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200307 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200308 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200309 filename,
310 getattr(node_or_string, 'lineno', '<unknown>')))
311
Edward Lesmes6c24d372018-03-28 12:52:29 -0400312 statements = {}
313 for statement in node_or_string.body:
314 _validate_statement(statement, statements)
315 statements[statement.targets[0].id] = statement.value
316
317 tokens = {
318 token[2]: list(token)
319 for token in tokenize.generate_tokens(
320 cStringIO.StringIO(content).readline)
321 }
322 local_scope = _NodeDict({}, tokens)
323
324 # Process vars first, so we can expand variables in the rest of the DEPS file.
325 vars_dict = {}
326 if 'vars' in statements:
327 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000328 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400329 local_scope.SetNode('vars', value, vars_statement)
330 # Update the parsed vars with the overrides, but only if they are already
331 # present (overrides do not introduce new variables).
332 vars_dict.update(value)
333 if vars_override:
334 vars_dict.update({
335 k: v
336 for k, v in vars_override.iteritems()
337 if k in vars_dict})
338
339 for name, node in statements.iteritems():
Edward Lemure05f18d2018-06-08 17:36:53 +0000340 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400341 local_scope.SetNode(name, value, node)
342
John Budorick0f7b2002018-01-19 15:46:17 -0800343 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200344
345
Edward Lemure05f18d2018-06-08 17:36:53 +0000346def ExecLegacy(content, filename='<unknown>', vars_override=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400347 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400348 local_scope = {}
349 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
350
351 # If we use 'exec' directly, it complains that 'Parse' contains a nested
352 # function with free variables.
353 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
354 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
355 eval(compile(content, filename, 'exec'), global_scope, local_scope)
356
Edward Lemure05f18d2018-06-08 17:36:53 +0000357 if 'vars' not in local_scope:
Edward Lesmes6c24d372018-03-28 12:52:29 -0400358 return local_scope
359
360 vars_dict = {}
361 vars_dict.update(local_scope['vars'])
362 if vars_override:
363 vars_dict.update({
364 k: v
365 for k, v in vars_override.iteritems()
366 if k in vars_dict
367 })
368
369 def _DeepFormat(node):
370 if isinstance(node, basestring):
371 return node.format(**vars_dict)
372 elif isinstance(node, dict):
373 return {
374 k.format(**vars_dict): _DeepFormat(v)
375 for k, v in node.iteritems()
376 }
377 elif isinstance(node, list):
378 return [_DeepFormat(elem) for elem in node]
379 elif isinstance(node, tuple):
380 return tuple(_DeepFormat(elem) for elem in node)
381 else:
382 return node
383
384 return _DeepFormat(local_scope)
385
386
Edward Lemur16f4bad2018-05-16 16:53:49 -0400387def _StandardizeDeps(deps_dict, vars_dict):
388 """"Standardizes the deps_dict.
389
390 For each dependency:
391 - Expands the variable in the dependency name.
392 - Ensures the dependency is a dictionary.
393 - Set's the 'dep_type' to be 'git' by default.
394 """
395 new_deps_dict = {}
396 for dep_name, dep_info in deps_dict.items():
397 dep_name = dep_name.format(**vars_dict)
398 if not isinstance(dep_info, collections.Mapping):
399 dep_info = {'url': dep_info}
400 dep_info.setdefault('dep_type', 'git')
401 new_deps_dict[dep_name] = dep_info
402 return new_deps_dict
403
404
405def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
406 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
407
408 The dependencies in os_deps_dict are transformed into conditional dependencies
409 using |'checkout_' + os_name|.
410 If the dependency is already present, the URL and revision must coincide.
411 """
412 for dep_name, dep_info in os_deps_dict.items():
413 # Make this condition very visible, so it's not a silent failure.
414 # It's unclear how to support None override in deps_os.
415 if dep_info['url'] is None:
416 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
417 continue
418
419 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
420 UpdateCondition(dep_info, 'and', os_condition)
421
422 if dep_name in deps_dict:
423 if deps_dict[dep_name]['url'] != dep_info['url']:
424 raise gclient_utils.Error(
425 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
426 'entry (%r).' % (
427 os_name, dep_name, dep_info, deps_dict[dep_name]))
428
429 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
430
431 deps_dict[dep_name] = dep_info
432
433
434def UpdateCondition(info_dict, op, new_condition):
435 """Updates info_dict's condition with |new_condition|.
436
437 An absent value is treated as implicitly True.
438 """
439 curr_condition = info_dict.get('condition')
440 # Easy case: Both are present.
441 if curr_condition and new_condition:
442 info_dict['condition'] = '(%s) %s (%s)' % (
443 curr_condition, op, new_condition)
444 # If |op| == 'and', and at least one condition is present, then use it.
445 elif op == 'and' and (curr_condition or new_condition):
446 info_dict['condition'] = curr_condition or new_condition
447 # Otherwise, no condition should be set
448 elif curr_condition:
449 del info_dict['condition']
450
451
Edward Lemure05f18d2018-06-08 17:36:53 +0000452def Parse(content, validate_syntax, filename, vars_override=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400453 """Parses DEPS strings.
454
455 Executes the Python-like string stored in content, resulting in a Python
456 dictionary specifyied by the schema above. Supports syntax validation and
457 variable expansion.
458
459 Args:
460 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400461 validate_syntax: bool. Whether syntax should be validated using the schema
462 defined above.
463 filename: str. The name of the DEPS file, or a string describing the source
464 of the content, e.g. '<string>', '<unknown>'.
465 vars_override: dict, optional. A dictionary with overrides for the variables
466 defined by the DEPS file.
467
468 Returns:
469 A Python dict with the parsed contents of the DEPS file, as specified by the
470 schema above.
471 """
472 if validate_syntax:
Edward Lemure05f18d2018-06-08 17:36:53 +0000473 result = Exec(content, filename, vars_override)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400474 else:
Edward Lemure05f18d2018-06-08 17:36:53 +0000475 result = ExecLegacy(content, filename, vars_override)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400476
477 vars_dict = result.get('vars', {})
478 if 'deps' in result:
479 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
480
481 if 'deps_os' in result:
482 deps = result.setdefault('deps', {})
483 for os_name, os_deps in result['deps_os'].iteritems():
484 os_deps = _StandardizeDeps(os_deps, vars_dict)
485 _MergeDepsOs(deps, os_deps, os_name)
486 del result['deps_os']
487
488 if 'hooks_os' in result:
489 hooks = result.setdefault('hooks', [])
490 for os_name, os_hooks in result['hooks_os'].iteritems():
491 for hook in os_hooks:
492 UpdateCondition(hook, 'and', 'checkout_' + os_name)
493 hooks.extend(os_hooks)
494 del result['hooks_os']
495
496 return result
497
498
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200499def EvaluateCondition(condition, variables, referenced_variables=None):
500 """Safely evaluates a boolean condition. Returns the result."""
501 if not referenced_variables:
502 referenced_variables = set()
503 _allowed_names = {'None': None, 'True': True, 'False': False}
504 main_node = ast.parse(condition, mode='eval')
505 if isinstance(main_node, ast.Expression):
506 main_node = main_node.body
507 def _convert(node):
508 if isinstance(node, ast.Str):
509 return node.s
510 elif isinstance(node, ast.Name):
511 if node.id in referenced_variables:
512 raise ValueError(
513 'invalid cyclic reference to %r (inside %r)' % (
514 node.id, condition))
515 elif node.id in _allowed_names:
516 return _allowed_names[node.id]
517 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200518 value = variables[node.id]
519
520 # Allow using "native" types, without wrapping everything in strings.
521 # Note that schema constraints still apply to variables.
522 if not isinstance(value, basestring):
523 return value
524
525 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200526 return EvaluateCondition(
527 variables[node.id],
528 variables,
529 referenced_variables.union([node.id]))
530 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200531 # Implicitly convert unrecognized names to strings.
532 # If we want to change this, we'll need to explicitly distinguish
533 # between arguments for GN to be passed verbatim, and ones to
534 # be evaluated.
535 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200536 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
537 if len(node.values) != 2:
538 raise ValueError(
539 'invalid "or": exactly 2 operands required (inside %r)' % (
540 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200541 left = _convert(node.values[0])
542 right = _convert(node.values[1])
543 if not isinstance(left, bool):
544 raise ValueError(
545 'invalid "or" operand %r (inside %r)' % (left, condition))
546 if not isinstance(right, bool):
547 raise ValueError(
548 'invalid "or" operand %r (inside %r)' % (right, condition))
549 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200550 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
551 if len(node.values) != 2:
552 raise ValueError(
553 'invalid "and": exactly 2 operands required (inside %r)' % (
554 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200555 left = _convert(node.values[0])
556 right = _convert(node.values[1])
557 if not isinstance(left, bool):
558 raise ValueError(
559 'invalid "and" operand %r (inside %r)' % (left, condition))
560 if not isinstance(right, bool):
561 raise ValueError(
562 'invalid "and" operand %r (inside %r)' % (right, condition))
563 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200564 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200565 value = _convert(node.operand)
566 if not isinstance(value, bool):
567 raise ValueError(
568 'invalid "not" operand %r (inside %r)' % (value, condition))
569 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200570 elif isinstance(node, ast.Compare):
571 if len(node.ops) != 1:
572 raise ValueError(
573 'invalid compare: exactly 1 operator required (inside %r)' % (
574 condition))
575 if len(node.comparators) != 1:
576 raise ValueError(
577 'invalid compare: exactly 1 comparator required (inside %r)' % (
578 condition))
579
580 left = _convert(node.left)
581 right = _convert(node.comparators[0])
582
583 if isinstance(node.ops[0], ast.Eq):
584 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700585 if isinstance(node.ops[0], ast.NotEq):
586 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200587
588 raise ValueError(
589 'unexpected operator: %s %s (inside %r)' % (
590 node.ops[0], ast.dump(node), condition))
591 else:
592 raise ValueError(
593 'unexpected AST node: %s %s (inside %r)' % (
594 node, ast.dump(node), condition))
595 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400596
597
598def RenderDEPSFile(gclient_dict):
599 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
600 return tokenize.untokenize(contents)
601
602
603def _UpdateAstString(tokens, node, value):
604 position = node.lineno, node.col_offset
Edward Lesmes62af4e42018-03-30 18:15:44 -0400605 quote_char = tokens[position][1][0]
606 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400607 node.s = value
608
609
Edward Lesmes3d993812018-04-02 12:52:49 -0400610def _ShiftLinesInTokens(tokens, delta, start):
611 new_tokens = {}
612 for token in tokens.values():
613 if token[2][0] >= start:
614 token[2] = token[2][0] + delta, token[2][1]
615 token[3] = token[3][0] + delta, token[3][1]
616 new_tokens[token[2]] = token
617 return new_tokens
618
619
620def AddVar(gclient_dict, var_name, value):
621 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
622 raise ValueError(
623 "Can't use SetVar for the given gclient dict. It contains no "
624 "formatting information.")
625
626 if 'vars' not in gclient_dict:
627 raise KeyError("vars dict is not defined.")
628
629 if var_name in gclient_dict['vars']:
630 raise ValueError(
631 "%s has already been declared in the vars dict. Consider using SetVar "
632 "instead." % var_name)
633
634 if not gclient_dict['vars']:
635 raise ValueError('vars dict is empty. This is not yet supported.')
636
Edward Lesmes8d626572018-04-05 17:53:10 -0400637 # We will attempt to add the var right after 'vars = {'.
638 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400639 if node is None:
640 raise ValueError(
641 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400642 line = node.lineno + 1
643
644 # We will try to match the new var's indentation to the next variable.
645 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400646
647 # We use a minimal Python dictionary, so that ast can parse it.
648 var_content = '{\n%s"%s": "%s",\n}' % (' ' * col, var_name, value)
649 var_ast = ast.parse(var_content).body[0].value
650
651 # Set the ast nodes for the key and value.
652 vars_node = gclient_dict.GetNode('vars')
653
654 var_name_node = var_ast.keys[0]
655 var_name_node.lineno += line - 2
656 vars_node.keys.insert(0, var_name_node)
657
658 value_node = var_ast.values[0]
659 value_node.lineno += line - 2
660 vars_node.values.insert(0, value_node)
661
662 # Update the tokens.
663 var_tokens = list(tokenize.generate_tokens(
664 cStringIO.StringIO(var_content).readline))
665 var_tokens = {
666 token[2]: list(token)
667 # Ignore the tokens corresponding to braces and new lines.
668 for token in var_tokens[2:-2]
669 }
670
671 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
672 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
673
674
Edward Lesmes6f64a052018-03-20 17:35:49 -0400675def SetVar(gclient_dict, var_name, value):
676 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
677 raise ValueError(
678 "Can't use SetVar for the given gclient dict. It contains no "
679 "formatting information.")
680 tokens = gclient_dict.tokens
681
Edward Lesmes3d993812018-04-02 12:52:49 -0400682 if 'vars' not in gclient_dict:
683 raise KeyError("vars dict is not defined.")
684
685 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400686 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400687 "%s has not been declared in the vars dict. Consider using AddVar "
688 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400689
690 node = gclient_dict['vars'].GetNode(var_name)
691 if node is None:
692 raise ValueError(
693 "The vars entry for %s has no formatting information." % var_name)
694
695 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400696 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400697
698
699def SetCIPD(gclient_dict, dep_name, package_name, new_version):
700 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
701 raise ValueError(
702 "Can't use SetCIPD for the given gclient dict. It contains no "
703 "formatting information.")
704 tokens = gclient_dict.tokens
705
706 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400707 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400708 "Could not find any dependency called %s." % dep_name)
709
710 # Find the package with the given name
711 packages = [
712 package
713 for package in gclient_dict['deps'][dep_name]['packages']
714 if package['package'] == package_name
715 ]
716 if len(packages) != 1:
717 raise ValueError(
718 "There must be exactly one package with the given name (%s), "
719 "%s were found." % (package_name, len(packages)))
720
721 # TODO(ehmaldonado): Support Var in package's version.
722 node = packages[0].GetNode('version')
723 if node is None:
724 raise ValueError(
725 "The deps entry for %s:%s has no formatting information." %
726 (dep_name, package_name))
727
728 new_version = 'version:' + new_version
729 _UpdateAstString(tokens, node, new_version)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400730 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400731
732
Edward Lesmes9f531292018-03-20 21:27:15 -0400733def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400734 def _GetVarName(node):
735 if isinstance(node, ast.Call):
736 return node.args[0].s
737 elif node.s.endswith('}'):
738 last_brace = node.s.rfind('{')
739 return node.s[last_brace+1:-1]
740 return None
741
742 def _UpdateRevision(dep_dict, dep_key, new_revision):
743 dep_node = dep_dict.GetNode(dep_key)
744 if dep_node is None:
745 raise ValueError(
746 "The deps entry for %s has no formatting information." % dep_name)
747
748 node = dep_node
749 if isinstance(node, ast.BinOp):
750 node = node.right
751
752 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
753 raise ValueError(
754 "Unsupported dependency revision format. Please file a bug.")
755
756 var_name = _GetVarName(node)
757 if var_name is not None:
758 SetVar(gclient_dict, var_name, new_revision)
759 else:
760 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400761 # '@' is part of the last string, which we want to modify. Discard
762 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400763 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400764 elif '@' not in dep_dict[dep_key]:
765 # '@' is not part of the URL at all. This mean the dependency is
766 # unpinned and we should pin it.
767 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400768 _UpdateAstString(tokens, node, new_revision)
769 dep_dict.SetNode(dep_key, new_revision, node)
770
Edward Lesmes6f64a052018-03-20 17:35:49 -0400771 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
772 raise ValueError(
773 "Can't use SetRevision for the given gclient dict. It contains no "
774 "formatting information.")
775 tokens = gclient_dict.tokens
776
777 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400778 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400779 "Could not find any dependency called %s." % dep_name)
780
Edward Lesmes6f64a052018-03-20 17:35:49 -0400781 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400782 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400783 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400784 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400785
786
787def GetVar(gclient_dict, var_name):
788 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
789 raise KeyError(
790 "Could not find any variable called %s." % var_name)
791
792 return gclient_dict['vars'][var_name]
793
794
795def GetCIPD(gclient_dict, dep_name, package_name):
796 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
797 raise KeyError(
798 "Could not find any dependency called %s." % dep_name)
799
800 # Find the package with the given name
801 packages = [
802 package
803 for package in gclient_dict['deps'][dep_name]['packages']
804 if package['package'] == package_name
805 ]
806 if len(packages) != 1:
807 raise ValueError(
808 "There must be exactly one package with the given name (%s), "
809 "%s were found." % (package_name, len(packages)))
810
811 return packages[0]['version'][len('version:'):]
812
813
814def GetRevision(gclient_dict, dep_name):
815 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
816 raise KeyError(
817 "Could not find any dependency called %s." % dep_name)
818
819 dep = gclient_dict['deps'][dep_name]
820 if dep is None:
821 return None
822 elif isinstance(dep, basestring):
823 _, _, revision = dep.partition('@')
824 return revision or None
825 elif isinstance(dep, collections.Mapping) and 'url' in dep:
826 _, _, revision = dep['url'].partition('@')
827 return revision or None
828 else:
829 raise ValueError(
830 '%s is not a valid git dependency.' % dep_name)