blob: 2ee93f1244da114dcf46365edcc94c4c7efc5e4a [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
Corentin Walleza68660d2018-09-10 17:33:24 +0000199 # relative to the parent's path, rather than relative to the .gclient file.
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200200 schema.Optional('use_relative_paths'): bool,
201
Corentin Walleza68660d2018-09-10 17:33:24 +0000202 # For recursed-upon sub-dependencies, run their hooks relative to the
203 # parent's path instead of relative to the .gclient file.
204 schema.Optional('use_relative_hooks'): bool,
205
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200206 # Variables that can be referenced using Var() - see 'deps'.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400207 schema.Optional('vars'): _NodeDictSchema({
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200208 schema.Optional(basestring): schema.Or(basestring, bool),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400209 }),
210}))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200211
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200212
Edward Lemure05f18d2018-06-08 17:36:53 +0000213def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200214 """Safely evaluates a single expression. Returns the result."""
215 _allowed_names = {'None': None, 'True': True, 'False': False}
216 if isinstance(node_or_string, basestring):
217 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
218 if isinstance(node_or_string, ast.Expression):
219 node_or_string = node_or_string.body
220 def _convert(node):
221 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000222 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000223 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400224 try:
225 return node.s.format(**vars_dict)
226 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000227 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400228 '%s was used as a variable, but was not declared in the vars dict '
229 '(file %r, line %s)' % (
230 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200231 elif isinstance(node, ast.Num):
232 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200233 elif isinstance(node, ast.Tuple):
234 return tuple(map(_convert, node.elts))
235 elif isinstance(node, ast.List):
236 return list(map(_convert, node.elts))
237 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400238 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200239 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200240 elif isinstance(node, ast.Name):
241 if node.id not in _allowed_names:
242 raise ValueError(
243 'invalid name %r (file %r, line %s)' % (
244 node.id, filename, getattr(node, 'lineno', '<unknown>')))
245 return _allowed_names[node.id]
246 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400247 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200248 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400249 'Var is the only allowed function (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 if node.keywords or node.starargs or node.kwargs or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200252 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400253 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200254 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400255 arg = _convert(node.args[0])
256 if not isinstance(arg, basestring):
257 raise ValueError(
258 'Var\'s argument must be a variable name (file %r, line %s)' % (
259 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400260 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000261 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400262 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000263 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400264 '%s was used as a variable, but was not declared in the vars dict '
265 '(file %r, line %s)' % (
266 arg, filename, getattr(node, 'lineno', '<unknown>')))
267 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200268 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
269 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200270 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
271 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200272 else:
273 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200274 'unexpected AST node: %s %s (file %r, line %s)' % (
275 node, ast.dump(node), filename,
276 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200277 return _convert(node_or_string)
278
279
Edward Lemure05f18d2018-06-08 17:36:53 +0000280def Exec(content, filename='<unknown>', vars_override=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400281 """Safely execs a set of assignments."""
282 def _validate_statement(node, local_scope):
283 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200284 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200285 'unexpected AST node: %s %s (file %r, line %s)' % (
286 node, ast.dump(node), filename,
287 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200288
Edward Lesmes6c24d372018-03-28 12:52:29 -0400289 if len(node.targets) != 1:
290 raise ValueError(
291 'invalid assignment: use exactly one target (file %r, line %s)' % (
292 filename, getattr(node, 'lineno', '<unknown>')))
293
294 target = node.targets[0]
295 if not isinstance(target, ast.Name):
296 raise ValueError(
297 'invalid assignment: target should be a name (file %r, line %s)' % (
298 filename, getattr(node, 'lineno', '<unknown>')))
299 if target.id in local_scope:
300 raise ValueError(
301 'invalid assignment: overrides var %r (file %r, line %s)' % (
302 target.id, filename, getattr(node, 'lineno', '<unknown>')))
303
304 node_or_string = ast.parse(content, filename=filename, mode='exec')
305 if isinstance(node_or_string, ast.Expression):
306 node_or_string = node_or_string.body
307
308 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200309 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200310 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200311 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200312 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200313 filename,
314 getattr(node_or_string, 'lineno', '<unknown>')))
315
Edward Lesmes6c24d372018-03-28 12:52:29 -0400316 statements = {}
317 for statement in node_or_string.body:
318 _validate_statement(statement, statements)
319 statements[statement.targets[0].id] = statement.value
320
321 tokens = {
322 token[2]: list(token)
323 for token in tokenize.generate_tokens(
324 cStringIO.StringIO(content).readline)
325 }
326 local_scope = _NodeDict({}, tokens)
327
328 # Process vars first, so we can expand variables in the rest of the DEPS file.
329 vars_dict = {}
330 if 'vars' in statements:
331 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000332 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400333 local_scope.SetNode('vars', value, vars_statement)
334 # Update the parsed vars with the overrides, but only if they are already
335 # present (overrides do not introduce new variables).
336 vars_dict.update(value)
337 if vars_override:
338 vars_dict.update({
339 k: v
340 for k, v in vars_override.iteritems()
341 if k in vars_dict})
342
343 for name, node in statements.iteritems():
Edward Lemure05f18d2018-06-08 17:36:53 +0000344 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400345 local_scope.SetNode(name, value, node)
346
John Budorick0f7b2002018-01-19 15:46:17 -0800347 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200348
349
Edward Lemure05f18d2018-06-08 17:36:53 +0000350def ExecLegacy(content, filename='<unknown>', vars_override=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400351 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400352 local_scope = {}
353 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
354
355 # If we use 'exec' directly, it complains that 'Parse' contains a nested
356 # function with free variables.
357 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
358 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
359 eval(compile(content, filename, 'exec'), global_scope, local_scope)
360
Edward Lemure05f18d2018-06-08 17:36:53 +0000361 if 'vars' not in local_scope:
Edward Lesmes6c24d372018-03-28 12:52:29 -0400362 return local_scope
363
364 vars_dict = {}
365 vars_dict.update(local_scope['vars'])
366 if vars_override:
367 vars_dict.update({
368 k: v
369 for k, v in vars_override.iteritems()
370 if k in vars_dict
371 })
372
373 def _DeepFormat(node):
374 if isinstance(node, basestring):
375 return node.format(**vars_dict)
376 elif isinstance(node, dict):
377 return {
378 k.format(**vars_dict): _DeepFormat(v)
379 for k, v in node.iteritems()
380 }
381 elif isinstance(node, list):
382 return [_DeepFormat(elem) for elem in node]
383 elif isinstance(node, tuple):
384 return tuple(_DeepFormat(elem) for elem in node)
385 else:
386 return node
387
388 return _DeepFormat(local_scope)
389
390
Edward Lemur16f4bad2018-05-16 16:53:49 -0400391def _StandardizeDeps(deps_dict, vars_dict):
392 """"Standardizes the deps_dict.
393
394 For each dependency:
395 - Expands the variable in the dependency name.
396 - Ensures the dependency is a dictionary.
397 - Set's the 'dep_type' to be 'git' by default.
398 """
399 new_deps_dict = {}
400 for dep_name, dep_info in deps_dict.items():
401 dep_name = dep_name.format(**vars_dict)
402 if not isinstance(dep_info, collections.Mapping):
403 dep_info = {'url': dep_info}
404 dep_info.setdefault('dep_type', 'git')
405 new_deps_dict[dep_name] = dep_info
406 return new_deps_dict
407
408
409def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
410 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
411
412 The dependencies in os_deps_dict are transformed into conditional dependencies
413 using |'checkout_' + os_name|.
414 If the dependency is already present, the URL and revision must coincide.
415 """
416 for dep_name, dep_info in os_deps_dict.items():
417 # Make this condition very visible, so it's not a silent failure.
418 # It's unclear how to support None override in deps_os.
419 if dep_info['url'] is None:
420 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
421 continue
422
423 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
424 UpdateCondition(dep_info, 'and', os_condition)
425
426 if dep_name in deps_dict:
427 if deps_dict[dep_name]['url'] != dep_info['url']:
428 raise gclient_utils.Error(
429 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
430 'entry (%r).' % (
431 os_name, dep_name, dep_info, deps_dict[dep_name]))
432
433 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
434
435 deps_dict[dep_name] = dep_info
436
437
438def UpdateCondition(info_dict, op, new_condition):
439 """Updates info_dict's condition with |new_condition|.
440
441 An absent value is treated as implicitly True.
442 """
443 curr_condition = info_dict.get('condition')
444 # Easy case: Both are present.
445 if curr_condition and new_condition:
446 info_dict['condition'] = '(%s) %s (%s)' % (
447 curr_condition, op, new_condition)
448 # If |op| == 'and', and at least one condition is present, then use it.
449 elif op == 'and' and (curr_condition or new_condition):
450 info_dict['condition'] = curr_condition or new_condition
451 # Otherwise, no condition should be set
452 elif curr_condition:
453 del info_dict['condition']
454
455
Edward Lemure05f18d2018-06-08 17:36:53 +0000456def Parse(content, validate_syntax, filename, vars_override=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400457 """Parses DEPS strings.
458
459 Executes the Python-like string stored in content, resulting in a Python
460 dictionary specifyied by the schema above. Supports syntax validation and
461 variable expansion.
462
463 Args:
464 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400465 validate_syntax: bool. Whether syntax should be validated using the schema
466 defined above.
467 filename: str. The name of the DEPS file, or a string describing the source
468 of the content, e.g. '<string>', '<unknown>'.
469 vars_override: dict, optional. A dictionary with overrides for the variables
470 defined by the DEPS file.
471
472 Returns:
473 A Python dict with the parsed contents of the DEPS file, as specified by the
474 schema above.
475 """
476 if validate_syntax:
Edward Lemure05f18d2018-06-08 17:36:53 +0000477 result = Exec(content, filename, vars_override)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400478 else:
Edward Lemure05f18d2018-06-08 17:36:53 +0000479 result = ExecLegacy(content, filename, vars_override)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400480
481 vars_dict = result.get('vars', {})
482 if 'deps' in result:
483 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
484
485 if 'deps_os' in result:
486 deps = result.setdefault('deps', {})
487 for os_name, os_deps in result['deps_os'].iteritems():
488 os_deps = _StandardizeDeps(os_deps, vars_dict)
489 _MergeDepsOs(deps, os_deps, os_name)
490 del result['deps_os']
491
492 if 'hooks_os' in result:
493 hooks = result.setdefault('hooks', [])
494 for os_name, os_hooks in result['hooks_os'].iteritems():
495 for hook in os_hooks:
496 UpdateCondition(hook, 'and', 'checkout_' + os_name)
497 hooks.extend(os_hooks)
498 del result['hooks_os']
499
500 return result
501
502
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200503def EvaluateCondition(condition, variables, referenced_variables=None):
504 """Safely evaluates a boolean condition. Returns the result."""
505 if not referenced_variables:
506 referenced_variables = set()
507 _allowed_names = {'None': None, 'True': True, 'False': False}
508 main_node = ast.parse(condition, mode='eval')
509 if isinstance(main_node, ast.Expression):
510 main_node = main_node.body
511 def _convert(node):
512 if isinstance(node, ast.Str):
513 return node.s
514 elif isinstance(node, ast.Name):
515 if node.id in referenced_variables:
516 raise ValueError(
517 'invalid cyclic reference to %r (inside %r)' % (
518 node.id, condition))
519 elif node.id in _allowed_names:
520 return _allowed_names[node.id]
521 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200522 value = variables[node.id]
523
524 # Allow using "native" types, without wrapping everything in strings.
525 # Note that schema constraints still apply to variables.
526 if not isinstance(value, basestring):
527 return value
528
529 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200530 return EvaluateCondition(
531 variables[node.id],
532 variables,
533 referenced_variables.union([node.id]))
534 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200535 # Implicitly convert unrecognized names to strings.
536 # If we want to change this, we'll need to explicitly distinguish
537 # between arguments for GN to be passed verbatim, and ones to
538 # be evaluated.
539 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200540 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
541 if len(node.values) != 2:
542 raise ValueError(
543 'invalid "or": exactly 2 operands required (inside %r)' % (
544 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200545 left = _convert(node.values[0])
546 right = _convert(node.values[1])
547 if not isinstance(left, bool):
548 raise ValueError(
549 'invalid "or" operand %r (inside %r)' % (left, condition))
550 if not isinstance(right, bool):
551 raise ValueError(
552 'invalid "or" operand %r (inside %r)' % (right, condition))
553 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200554 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
555 if len(node.values) != 2:
556 raise ValueError(
557 'invalid "and": exactly 2 operands required (inside %r)' % (
558 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200559 left = _convert(node.values[0])
560 right = _convert(node.values[1])
561 if not isinstance(left, bool):
562 raise ValueError(
563 'invalid "and" operand %r (inside %r)' % (left, condition))
564 if not isinstance(right, bool):
565 raise ValueError(
566 'invalid "and" operand %r (inside %r)' % (right, condition))
567 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200568 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200569 value = _convert(node.operand)
570 if not isinstance(value, bool):
571 raise ValueError(
572 'invalid "not" operand %r (inside %r)' % (value, condition))
573 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200574 elif isinstance(node, ast.Compare):
575 if len(node.ops) != 1:
576 raise ValueError(
577 'invalid compare: exactly 1 operator required (inside %r)' % (
578 condition))
579 if len(node.comparators) != 1:
580 raise ValueError(
581 'invalid compare: exactly 1 comparator required (inside %r)' % (
582 condition))
583
584 left = _convert(node.left)
585 right = _convert(node.comparators[0])
586
587 if isinstance(node.ops[0], ast.Eq):
588 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700589 if isinstance(node.ops[0], ast.NotEq):
590 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200591
592 raise ValueError(
593 'unexpected operator: %s %s (inside %r)' % (
594 node.ops[0], ast.dump(node), condition))
595 else:
596 raise ValueError(
597 'unexpected AST node: %s %s (inside %r)' % (
598 node, ast.dump(node), condition))
599 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400600
601
602def RenderDEPSFile(gclient_dict):
603 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
604 return tokenize.untokenize(contents)
605
606
607def _UpdateAstString(tokens, node, value):
608 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000609 quote_char = ''
610 if isinstance(node, ast.Str):
611 quote_char = tokens[position][1][0]
Edward Lesmes62af4e42018-03-30 18:15:44 -0400612 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400613 node.s = value
614
615
Edward Lesmes3d993812018-04-02 12:52:49 -0400616def _ShiftLinesInTokens(tokens, delta, start):
617 new_tokens = {}
618 for token in tokens.values():
619 if token[2][0] >= start:
620 token[2] = token[2][0] + delta, token[2][1]
621 token[3] = token[3][0] + delta, token[3][1]
622 new_tokens[token[2]] = token
623 return new_tokens
624
625
626def AddVar(gclient_dict, var_name, value):
627 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
628 raise ValueError(
629 "Can't use SetVar for the given gclient dict. It contains no "
630 "formatting information.")
631
632 if 'vars' not in gclient_dict:
633 raise KeyError("vars dict is not defined.")
634
635 if var_name in gclient_dict['vars']:
636 raise ValueError(
637 "%s has already been declared in the vars dict. Consider using SetVar "
638 "instead." % var_name)
639
640 if not gclient_dict['vars']:
641 raise ValueError('vars dict is empty. This is not yet supported.')
642
Edward Lesmes8d626572018-04-05 17:53:10 -0400643 # We will attempt to add the var right after 'vars = {'.
644 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400645 if node is None:
646 raise ValueError(
647 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400648 line = node.lineno + 1
649
650 # We will try to match the new var's indentation to the next variable.
651 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400652
653 # We use a minimal Python dictionary, so that ast can parse it.
654 var_content = '{\n%s"%s": "%s",\n}' % (' ' * col, var_name, value)
655 var_ast = ast.parse(var_content).body[0].value
656
657 # Set the ast nodes for the key and value.
658 vars_node = gclient_dict.GetNode('vars')
659
660 var_name_node = var_ast.keys[0]
661 var_name_node.lineno += line - 2
662 vars_node.keys.insert(0, var_name_node)
663
664 value_node = var_ast.values[0]
665 value_node.lineno += line - 2
666 vars_node.values.insert(0, value_node)
667
668 # Update the tokens.
669 var_tokens = list(tokenize.generate_tokens(
670 cStringIO.StringIO(var_content).readline))
671 var_tokens = {
672 token[2]: list(token)
673 # Ignore the tokens corresponding to braces and new lines.
674 for token in var_tokens[2:-2]
675 }
676
677 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
678 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
679
680
Edward Lesmes6f64a052018-03-20 17:35:49 -0400681def SetVar(gclient_dict, var_name, value):
682 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
683 raise ValueError(
684 "Can't use SetVar for the given gclient dict. It contains no "
685 "formatting information.")
686 tokens = gclient_dict.tokens
687
Edward Lesmes3d993812018-04-02 12:52:49 -0400688 if 'vars' not in gclient_dict:
689 raise KeyError("vars dict is not defined.")
690
691 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400692 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400693 "%s has not been declared in the vars dict. Consider using AddVar "
694 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400695
696 node = gclient_dict['vars'].GetNode(var_name)
697 if node is None:
698 raise ValueError(
699 "The vars entry for %s has no formatting information." % var_name)
700
701 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400702 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400703
704
705def SetCIPD(gclient_dict, dep_name, package_name, new_version):
706 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
707 raise ValueError(
708 "Can't use SetCIPD for the given gclient dict. It contains no "
709 "formatting information.")
710 tokens = gclient_dict.tokens
711
712 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400713 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400714 "Could not find any dependency called %s." % dep_name)
715
716 # Find the package with the given name
717 packages = [
718 package
719 for package in gclient_dict['deps'][dep_name]['packages']
720 if package['package'] == package_name
721 ]
722 if len(packages) != 1:
723 raise ValueError(
724 "There must be exactly one package with the given name (%s), "
725 "%s were found." % (package_name, len(packages)))
726
727 # TODO(ehmaldonado): Support Var in package's version.
728 node = packages[0].GetNode('version')
729 if node is None:
730 raise ValueError(
731 "The deps entry for %s:%s has no formatting information." %
732 (dep_name, package_name))
733
Edward Lesmes6f64a052018-03-20 17:35:49 -0400734 _UpdateAstString(tokens, node, new_version)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400735 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400736
737
Edward Lesmes9f531292018-03-20 21:27:15 -0400738def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400739 def _GetVarName(node):
740 if isinstance(node, ast.Call):
741 return node.args[0].s
742 elif node.s.endswith('}'):
743 last_brace = node.s.rfind('{')
744 return node.s[last_brace+1:-1]
745 return None
746
747 def _UpdateRevision(dep_dict, dep_key, new_revision):
748 dep_node = dep_dict.GetNode(dep_key)
749 if dep_node is None:
750 raise ValueError(
751 "The deps entry for %s has no formatting information." % dep_name)
752
753 node = dep_node
754 if isinstance(node, ast.BinOp):
755 node = node.right
756
757 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
758 raise ValueError(
759 "Unsupported dependency revision format. Please file a bug.")
760
761 var_name = _GetVarName(node)
762 if var_name is not None:
763 SetVar(gclient_dict, var_name, new_revision)
764 else:
765 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400766 # '@' is part of the last string, which we want to modify. Discard
767 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400768 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400769 elif '@' not in dep_dict[dep_key]:
770 # '@' is not part of the URL at all. This mean the dependency is
771 # unpinned and we should pin it.
772 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400773 _UpdateAstString(tokens, node, new_revision)
774 dep_dict.SetNode(dep_key, new_revision, node)
775
Edward Lesmes6f64a052018-03-20 17:35:49 -0400776 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
777 raise ValueError(
778 "Can't use SetRevision for the given gclient dict. It contains no "
779 "formatting information.")
780 tokens = gclient_dict.tokens
781
782 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400783 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400784 "Could not find any dependency called %s." % dep_name)
785
Edward Lesmes6f64a052018-03-20 17:35:49 -0400786 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400787 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400788 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400789 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400790
791
792def GetVar(gclient_dict, var_name):
793 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
794 raise KeyError(
795 "Could not find any variable called %s." % var_name)
796
797 return gclient_dict['vars'][var_name]
798
799
800def GetCIPD(gclient_dict, dep_name, package_name):
801 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
802 raise KeyError(
803 "Could not find any dependency called %s." % dep_name)
804
805 # Find the package with the given name
806 packages = [
807 package
808 for package in gclient_dict['deps'][dep_name]['packages']
809 if package['package'] == package_name
810 ]
811 if len(packages) != 1:
812 raise ValueError(
813 "There must be exactly one package with the given name (%s), "
814 "%s were found." % (package_name, len(packages)))
815
Edward Lemura92b9612018-07-03 02:34:32 +0000816 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400817
818
819def GetRevision(gclient_dict, dep_name):
820 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
821 raise KeyError(
822 "Could not find any dependency called %s." % dep_name)
823
824 dep = gclient_dict['deps'][dep_name]
825 if dep is None:
826 return None
827 elif isinstance(dep, basestring):
828 _, _, revision = dep.partition('@')
829 return revision or None
830 elif isinstance(dep, collections.Mapping) and 'url' in dep:
831 _, _, revision = dep['url'].partition('@')
832 return revision or None
833 else:
834 raise ValueError(
835 '%s is not a valid git dependency.' % dep_name)