blob: 8cf91f012d4630213a7a78393513d9d8b9f77fab [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
James Darpinianf994d872019-08-06 18:57:40 +000014from third_party import six
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020015
Edward Lemurba1b1f72019-07-27 00:41:59 +000016if six.PY2:
Raul Tambreb946b232019-03-26 14:48:46 +000017 # We use cStringIO.StringIO because it is equivalent to Py3's io.StringIO.
18 from cStringIO import StringIO
Raul Tambre6693d092020-02-19 20:36:45 +000019 import collections as collections_abc
Raul Tambreb946b232019-03-26 14:48:46 +000020else:
Raul Tambre6693d092020-02-19 20:36:45 +000021 from collections import abc as collections_abc
Raul Tambreb946b232019-03-26 14:48:46 +000022 from io import StringIO
Aaron Gableac9b0f32019-04-18 17:38:37 +000023 # pylint: disable=redefined-builtin
24 basestring = str
25
26
Dirk Prankefdd2cd62020-06-30 23:30:47 +000027class ConstantString(object):
28 def __init__(self, value):
29 self.value = value
30
31 def __format__(self, format_spec):
32 del format_spec
33 return self.value
34
35 def __repr__(self):
36 return "Str('" + self.value + "')"
37
38 def __eq__(self, other):
39 if isinstance(other, ConstantString):
40 return self.value == other.value
41 else:
42 return self.value == other
43
44 def __hash__(self):
45 return self.value.__hash__()
46
47
Raul Tambre6693d092020-02-19 20:36:45 +000048class _NodeDict(collections_abc.MutableMapping):
Edward Lesmes6f64a052018-03-20 17:35:49 -040049 """Dict-like type that also stores information on AST nodes and tokens."""
Edward Lemurc00ac8d2020-03-04 23:37:57 +000050 def __init__(self, data=None, tokens=None):
51 self.data = collections.OrderedDict(data or [])
Edward Lesmes6f64a052018-03-20 17:35:49 -040052 self.tokens = tokens
53
54 def __str__(self):
Raul Tambreb946b232019-03-26 14:48:46 +000055 return str({k: v[0] for k, v in self.data.items()})
Edward Lesmes6f64a052018-03-20 17:35:49 -040056
Edward Lemura1e4d482018-12-17 19:01:03 +000057 def __repr__(self):
58 return self.__str__()
59
Edward Lesmes6f64a052018-03-20 17:35:49 -040060 def __getitem__(self, key):
61 return self.data[key][0]
62
63 def __setitem__(self, key, value):
64 self.data[key] = (value, None)
65
66 def __delitem__(self, key):
67 del self.data[key]
68
69 def __iter__(self):
70 return iter(self.data)
71
72 def __len__(self):
73 return len(self.data)
74
Edward Lesmes3d993812018-04-02 12:52:49 -040075 def MoveTokens(self, origin, delta):
76 if self.tokens:
77 new_tokens = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000078 for pos, token in self.tokens.items():
Edward Lesmes3d993812018-04-02 12:52:49 -040079 if pos[0] >= origin:
80 pos = (pos[0] + delta, pos[1])
81 token = token[:2] + (pos,) + token[3:]
82 new_tokens[pos] = token
83
84 for value, node in self.data.values():
85 if node.lineno >= origin:
86 node.lineno += delta
87 if isinstance(value, _NodeDict):
88 value.MoveTokens(origin, delta)
89
Edward Lesmes6f64a052018-03-20 17:35:49 -040090 def GetNode(self, key):
91 return self.data[key][1]
92
Edward Lesmes6c24d372018-03-28 12:52:29 -040093 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040094 self.data[key] = (value, node)
95
96
97def _NodeDictSchema(dict_schema):
98 """Validate dict_schema after converting _NodeDict to a regular dict."""
99 def validate(d):
100 schema.Schema(dict_schema).validate(dict(d))
101 return True
102 return validate
103
104
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200105# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400106_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +0000107 schema.Optional(basestring):
Raul Tambreb946b232019-03-26 14:48:46 +0000108 schema.Or(
109 None,
Aaron Gableac9b0f32019-04-18 17:38:37 +0000110 basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000111 _NodeDictSchema({
112 # Repo and revision to check out under the path
113 # (same as if no dict was used).
Aaron Gableac9b0f32019-04-18 17:38:37 +0000114 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200115
Raul Tambreb946b232019-03-26 14:48:46 +0000116 # Optional condition string. The dep will only be processed
117 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000118 schema.Optional('condition'): basestring,
119 schema.Optional('dep_type', default='git'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000120 }),
121 # CIPD package.
122 _NodeDictSchema({
123 'packages': [
124 _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +0000125 'package': basestring,
126 'version': basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000127 })
128 ],
Aaron Gableac9b0f32019-04-18 17:38:37 +0000129 schema.Optional('condition'): basestring,
130 schema.Optional('dep_type', default='cipd'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000131 }),
132 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400133})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200134
Raul Tambreb946b232019-03-26 14:48:46 +0000135_GCLIENT_HOOKS_SCHEMA = [
136 _NodeDictSchema({
137 # Hook action: list of command-line arguments to invoke.
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000138 'action': [schema.Or(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200139
Raul Tambreb946b232019-03-26 14:48:46 +0000140 # Name of the hook. Doesn't affect operation.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000141 schema.Optional('name'): basestring,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200142
Raul Tambreb946b232019-03-26 14:48:46 +0000143 # Hook pattern (regex). Originally intended to limit some hooks to run
144 # only when files matching the pattern have changed. In practice, with
145 # git, gclient runs all the hooks regardless of this field.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000146 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200147
Raul Tambreb946b232019-03-26 14:48:46 +0000148 # Working directory where to execute the hook.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000149 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200150
Raul Tambreb946b232019-03-26 14:48:46 +0000151 # Optional condition string. The hook will only be run
152 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000153 schema.Optional('condition'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000154 })
155]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200156
Raul Tambreb946b232019-03-26 14:48:46 +0000157_GCLIENT_SCHEMA = schema.Schema(
158 _NodeDictSchema({
Ayu Ishii09858612020-06-26 18:00:52 +0000159 # List of host names from which dependencies are allowed (allowlist).
Raul Tambreb946b232019-03-26 14:48:46 +0000160 # NOTE: when not present, all hosts are allowed.
161 # NOTE: scoped to current DEPS file, not recursive.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000162 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200163
Raul Tambreb946b232019-03-26 14:48:46 +0000164 # Mapping from paths to repo and revision to check out under that path.
165 # Applying this mapping to the on-disk checkout is the main purpose
166 # of gclient, and also why the config file is called DEPS.
167 #
168 # The following functions are allowed:
169 #
170 # Var(): allows variable substitution (either from 'vars' dict below,
171 # or command-line override)
Aaron Gableac9b0f32019-04-18 17:38:37 +0000172 schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200173
Raul Tambreb946b232019-03-26 14:48:46 +0000174 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
175 # Also see 'target_os'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000176 schema.Optional('deps_os'): _NodeDictSchema({
177 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
178 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200179
Raul Tambreb946b232019-03-26 14:48:46 +0000180 # Dependency to get gclient_gn_args* settings from. This allows these
181 # values to be set in a recursedeps file, rather than requiring that
182 # they exist in the top-level solution.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000183 schema.Optional('gclient_gn_args_from'): basestring,
Michael Moss848c86e2018-05-03 16:05:50 -0700184
Raul Tambreb946b232019-03-26 14:48:46 +0000185 # Path to GN args file to write selected variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000186 schema.Optional('gclient_gn_args_file'): basestring,
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200187
Raul Tambreb946b232019-03-26 14:48:46 +0000188 # Subset of variables to write to the GN args file (see above).
Aaron Gableac9b0f32019-04-18 17:38:37 +0000189 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200190
Raul Tambreb946b232019-03-26 14:48:46 +0000191 # Hooks executed after gclient sync (unless suppressed), or explicitly
192 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
193 # Also see 'pre_deps_hooks'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000194 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200195
Raul Tambreb946b232019-03-26 14:48:46 +0000196 # Similar to 'hooks', also keyed by OS.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000197 schema.Optional('hooks_os'): _NodeDictSchema({
198 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
199 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700200
Raul Tambreb946b232019-03-26 14:48:46 +0000201 # Rules which #includes are allowed in the directory.
202 # Also see 'skip_child_includes' and 'specific_include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000203 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200204
Raul Tambreb946b232019-03-26 14:48:46 +0000205 # Hooks executed before processing DEPS. See 'hooks' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000206 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200207
Raul Tambreb946b232019-03-26 14:48:46 +0000208 # Recursion limit for nested DEPS.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000209 schema.Optional('recursion'): int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200210
Ayu Ishii09858612020-06-26 18:00:52 +0000211 # Allowlists deps for which recursion should be enabled.
Raul Tambreb946b232019-03-26 14:48:46 +0000212 schema.Optional('recursedeps'): [
Aaron Gableac9b0f32019-04-18 17:38:37 +0000213 schema.Optional(schema.Or(
214 basestring,
215 (basestring, basestring),
216 [basestring, basestring]
217 )),
Raul Tambreb946b232019-03-26 14:48:46 +0000218 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200219
Ayu Ishii09858612020-06-26 18:00:52 +0000220 # Blocklists directories for checking 'include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000221 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200222
Raul Tambreb946b232019-03-26 14:48:46 +0000223 # Mapping from paths to include rules specific for that path.
224 # See 'include_rules' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000225 schema.Optional('specific_include_rules'): _NodeDictSchema({
226 schema.Optional(basestring): [basestring]
227 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200228
Raul Tambreb946b232019-03-26 14:48:46 +0000229 # List of additional OS names to consider when selecting dependencies
230 # from deps_os.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000231 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200232
Raul Tambreb946b232019-03-26 14:48:46 +0000233 # For recursed-upon sub-dependencies, check out their own dependencies
234 # relative to the parent's path, rather than relative to the .gclient
235 # file.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000236 schema.Optional('use_relative_paths'): bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200237
Raul Tambreb946b232019-03-26 14:48:46 +0000238 # Variables that can be referenced using Var() - see 'deps'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000239 schema.Optional('vars'): _NodeDictSchema({
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000240 schema.Optional(basestring): schema.Or(ConstantString,
241 basestring,
242 bool),
Aaron Gableac9b0f32019-04-18 17:38:37 +0000243 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000244 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200245
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200246
Edward Lemure05f18d2018-06-08 17:36:53 +0000247def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200248 """Safely evaluates a single expression. Returns the result."""
249 _allowed_names = {'None': None, 'True': True, 'False': False}
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000250 if isinstance(node_or_string, ConstantString):
251 return node_or_string.value
Aaron Gableac9b0f32019-04-18 17:38:37 +0000252 if isinstance(node_or_string, basestring):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200253 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
254 if isinstance(node_or_string, ast.Expression):
255 node_or_string = node_or_string.body
256 def _convert(node):
257 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000258 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000259 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400260 try:
261 return node.s.format(**vars_dict)
262 except KeyError as e:
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)' % (
Edward Lemurba1b1f72019-07-27 00:41:59 +0000266 e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200267 elif isinstance(node, ast.Num):
268 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200269 elif isinstance(node, ast.Tuple):
270 return tuple(map(_convert, node.elts))
271 elif isinstance(node, ast.List):
272 return list(map(_convert, node.elts))
273 elif isinstance(node, ast.Dict):
Edward Lemurc00ac8d2020-03-04 23:37:57 +0000274 node_dict = _NodeDict()
275 for key_node, value_node in zip(node.keys, node.values):
276 key = _convert(key_node)
277 if key in node_dict:
278 raise ValueError(
279 'duplicate key in dictionary: %s (file %r, line %s)' % (
280 key, filename, getattr(key_node, 'lineno', '<unknown>')))
281 node_dict.SetNode(key, _convert(value_node), value_node)
282 return node_dict
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200283 elif isinstance(node, ast.Name):
284 if node.id not in _allowed_names:
285 raise ValueError(
286 'invalid name %r (file %r, line %s)' % (
287 node.id, filename, getattr(node, 'lineno', '<unknown>')))
288 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000289 elif not sys.version_info[:2] < (3, 4) and isinstance(
290 node, ast.NameConstant): # Since Python 3.4
291 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200292 elif isinstance(node, ast.Call):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000293 if (not isinstance(node.func, ast.Name) or
294 (node.func.id not in ('Str', 'Var'))):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200295 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000296 'Str and Var are the only allowed functions (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200297 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000298 if node.keywords or getattr(node, 'starargs', None) or getattr(
299 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200300 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000301 '%s takes exactly one argument (file %r, line %s)' % (
302 node.func.id, filename, getattr(node, 'lineno', '<unknown>')))
303 if node.func.id == 'Str':
304 if isinstance(node.args[0], ast.Str):
305 return ConstantString(node.args[0].s)
306 raise ValueError('Passed a non-string to Str() (file %r, line%s)' % (
307 filename, getattr(node, 'lineno', '<unknown>')))
308 else:
309 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000310 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400311 raise ValueError(
312 'Var\'s argument must be a variable name (file %r, line %s)' % (
313 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400314 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000315 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400316 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000317 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400318 '%s was used as a variable, but was not declared in the vars dict '
319 '(file %r, line %s)' % (
320 arg, filename, getattr(node, 'lineno', '<unknown>')))
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000321 val = vars_dict[arg]
322 if isinstance(val, ConstantString):
323 val = val.value
324 return val
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200325 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
326 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200327 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
328 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200329 else:
330 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200331 'unexpected AST node: %s %s (file %r, line %s)' % (
332 node, ast.dump(node), filename,
333 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200334 return _convert(node_or_string)
335
336
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000337def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400338 """Safely execs a set of assignments."""
339 def _validate_statement(node, local_scope):
340 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200341 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200342 'unexpected AST node: %s %s (file %r, line %s)' % (
343 node, ast.dump(node), filename,
344 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200345
Edward Lesmes6c24d372018-03-28 12:52:29 -0400346 if len(node.targets) != 1:
347 raise ValueError(
348 'invalid assignment: use exactly one target (file %r, line %s)' % (
349 filename, getattr(node, 'lineno', '<unknown>')))
350
351 target = node.targets[0]
352 if not isinstance(target, ast.Name):
353 raise ValueError(
354 'invalid assignment: target should be a name (file %r, line %s)' % (
355 filename, getattr(node, 'lineno', '<unknown>')))
356 if target.id in local_scope:
357 raise ValueError(
358 'invalid assignment: overrides var %r (file %r, line %s)' % (
359 target.id, filename, getattr(node, 'lineno', '<unknown>')))
360
361 node_or_string = ast.parse(content, filename=filename, mode='exec')
362 if isinstance(node_or_string, ast.Expression):
363 node_or_string = node_or_string.body
364
365 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200366 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200367 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200368 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200369 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200370 filename,
371 getattr(node_or_string, 'lineno', '<unknown>')))
372
Edward Lesmes6c24d372018-03-28 12:52:29 -0400373 statements = {}
374 for statement in node_or_string.body:
375 _validate_statement(statement, statements)
376 statements[statement.targets[0].id] = statement.value
377
Raul Tambreb946b232019-03-26 14:48:46 +0000378 # The tokenized representation needs to end with a newline token, otherwise
379 # untokenization will trigger an assert later on.
380 # In Python 2.7 on Windows we need to ensure the input ends with a newline
381 # for a newline token to be generated.
382 # In other cases a newline token is always generated during tokenization so
383 # this has no effect.
384 # TODO: Remove this workaround after migrating to Python 3.
385 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400386 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000387 token[2]: list(token) for token in tokenize.generate_tokens(
388 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400389 }
Raul Tambreb946b232019-03-26 14:48:46 +0000390
Edward Lesmes6c24d372018-03-28 12:52:29 -0400391 local_scope = _NodeDict({}, tokens)
392
393 # Process vars first, so we can expand variables in the rest of the DEPS file.
394 vars_dict = {}
395 if 'vars' in statements:
396 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000397 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400398 local_scope.SetNode('vars', value, vars_statement)
399 # Update the parsed vars with the overrides, but only if they are already
400 # present (overrides do not introduce new variables).
401 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000402
403 if builtin_vars:
404 vars_dict.update(builtin_vars)
405
406 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
Raul Tambreb946b232019-03-26 14:48:46 +0000409 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000410 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400411 local_scope.SetNode(name, value, node)
412
Edward Lemur67cabcd2020-03-03 19:31:15 +0000413 try:
414 return _GCLIENT_SCHEMA.validate(local_scope)
415 except schema.SchemaError as e:
416 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400417
418
Edward Lemur16f4bad2018-05-16 16:53:49 -0400419def _StandardizeDeps(deps_dict, vars_dict):
420 """"Standardizes the deps_dict.
421
422 For each dependency:
423 - Expands the variable in the dependency name.
424 - Ensures the dependency is a dictionary.
425 - Set's the 'dep_type' to be 'git' by default.
426 """
427 new_deps_dict = {}
428 for dep_name, dep_info in deps_dict.items():
429 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000430 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400431 dep_info = {'url': dep_info}
432 dep_info.setdefault('dep_type', 'git')
433 new_deps_dict[dep_name] = dep_info
434 return new_deps_dict
435
436
437def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
438 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
439
440 The dependencies in os_deps_dict are transformed into conditional dependencies
441 using |'checkout_' + os_name|.
442 If the dependency is already present, the URL and revision must coincide.
443 """
444 for dep_name, dep_info in os_deps_dict.items():
445 # Make this condition very visible, so it's not a silent failure.
446 # It's unclear how to support None override in deps_os.
447 if dep_info['url'] is None:
448 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
449 continue
450
451 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
452 UpdateCondition(dep_info, 'and', os_condition)
453
454 if dep_name in deps_dict:
455 if deps_dict[dep_name]['url'] != dep_info['url']:
456 raise gclient_utils.Error(
457 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
458 'entry (%r).' % (
459 os_name, dep_name, dep_info, deps_dict[dep_name]))
460
461 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
462
463 deps_dict[dep_name] = dep_info
464
465
466def UpdateCondition(info_dict, op, new_condition):
467 """Updates info_dict's condition with |new_condition|.
468
469 An absent value is treated as implicitly True.
470 """
471 curr_condition = info_dict.get('condition')
472 # Easy case: Both are present.
473 if curr_condition and new_condition:
474 info_dict['condition'] = '(%s) %s (%s)' % (
475 curr_condition, op, new_condition)
476 # If |op| == 'and', and at least one condition is present, then use it.
477 elif op == 'and' and (curr_condition or new_condition):
478 info_dict['condition'] = curr_condition or new_condition
479 # Otherwise, no condition should be set
480 elif curr_condition:
481 del info_dict['condition']
482
483
Edward Lemur67cabcd2020-03-03 19:31:15 +0000484def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400485 """Parses DEPS strings.
486
487 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000488 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400489 variable expansion.
490
491 Args:
492 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400493 filename: str. The name of the DEPS file, or a string describing the source
494 of the content, e.g. '<string>', '<unknown>'.
495 vars_override: dict, optional. A dictionary with overrides for the variables
496 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000497 builtin_vars: dict, optional. A dictionary with variables that are provided
498 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400499
500 Returns:
501 A Python dict with the parsed contents of the DEPS file, as specified by the
502 schema above.
503 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000504 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400505
506 vars_dict = result.get('vars', {})
507 if 'deps' in result:
508 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
509
510 if 'deps_os' in result:
511 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000512 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400513 os_deps = _StandardizeDeps(os_deps, vars_dict)
514 _MergeDepsOs(deps, os_deps, os_name)
515 del result['deps_os']
516
517 if 'hooks_os' in result:
518 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000519 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400520 for hook in os_hooks:
521 UpdateCondition(hook, 'and', 'checkout_' + os_name)
522 hooks.extend(os_hooks)
523 del result['hooks_os']
524
525 return result
526
527
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200528def EvaluateCondition(condition, variables, referenced_variables=None):
529 """Safely evaluates a boolean condition. Returns the result."""
530 if not referenced_variables:
531 referenced_variables = set()
532 _allowed_names = {'None': None, 'True': True, 'False': False}
533 main_node = ast.parse(condition, mode='eval')
534 if isinstance(main_node, ast.Expression):
535 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000536 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200537 if isinstance(node, ast.Str):
538 return node.s
Ben Pastenea541b282019-05-24 00:25:12 +0000539 elif isinstance(node, ast.Tuple) and allow_tuple:
540 return tuple(map(_convert, node.elts))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200541 elif isinstance(node, ast.Name):
542 if node.id in referenced_variables:
543 raise ValueError(
544 'invalid cyclic reference to %r (inside %r)' % (
545 node.id, condition))
546 elif node.id in _allowed_names:
547 return _allowed_names[node.id]
548 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200549 value = variables[node.id]
550
551 # Allow using "native" types, without wrapping everything in strings.
552 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000553 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200554 return value
555
556 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200557 return EvaluateCondition(
558 variables[node.id],
559 variables,
560 referenced_variables.union([node.id]))
561 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200562 # Implicitly convert unrecognized names to strings.
563 # If we want to change this, we'll need to explicitly distinguish
564 # between arguments for GN to be passed verbatim, and ones to
565 # be evaluated.
566 return node.id
Edward Lemurba1b1f72019-07-27 00:41:59 +0000567 elif not sys.version_info[:2] < (3, 4) and isinstance(
568 node, ast.NameConstant): # Since Python 3.4
569 return node.value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200570 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000571 bool_values = []
572 for value in node.values:
573 bool_values.append(_convert(value))
574 if not isinstance(bool_values[-1], bool):
575 raise ValueError(
576 'invalid "or" operand %r (inside %r)' % (
577 bool_values[-1], condition))
578 return any(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200579 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000580 bool_values = []
581 for value in node.values:
582 bool_values.append(_convert(value))
583 if not isinstance(bool_values[-1], bool):
584 raise ValueError(
585 'invalid "and" operand %r (inside %r)' % (
586 bool_values[-1], condition))
587 return all(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200588 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200589 value = _convert(node.operand)
590 if not isinstance(value, bool):
591 raise ValueError(
592 'invalid "not" operand %r (inside %r)' % (value, condition))
593 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200594 elif isinstance(node, ast.Compare):
595 if len(node.ops) != 1:
596 raise ValueError(
597 'invalid compare: exactly 1 operator required (inside %r)' % (
598 condition))
599 if len(node.comparators) != 1:
600 raise ValueError(
601 'invalid compare: exactly 1 comparator required (inside %r)' % (
602 condition))
603
604 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000605 right = _convert(
606 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200607
608 if isinstance(node.ops[0], ast.Eq):
609 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700610 if isinstance(node.ops[0], ast.NotEq):
611 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000612 if isinstance(node.ops[0], ast.In):
613 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200614
615 raise ValueError(
616 'unexpected operator: %s %s (inside %r)' % (
617 node.ops[0], ast.dump(node), condition))
618 else:
619 raise ValueError(
620 'unexpected AST node: %s %s (inside %r)' % (
621 node, ast.dump(node), condition))
622 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400623
624
625def RenderDEPSFile(gclient_dict):
626 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000627 # The last token is a newline, which we ensure in Exec() for compatibility.
628 # However tests pass in inputs not ending with a newline and expect the same
629 # back, so for backwards compatibility need to remove that newline character.
630 # TODO: Fix tests to expect the newline
631 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400632
633
634def _UpdateAstString(tokens, node, value):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000635 if isinstance(node, ast.Call):
636 node = node.args[0]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400637 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000638 quote_char = ''
639 if isinstance(node, ast.Str):
640 quote_char = tokens[position][1][0]
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000641 value = value.encode('unicode_escape').decode('utf-8')
Edward Lesmes62af4e42018-03-30 18:15:44 -0400642 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400643 node.s = value
644
645
Edward Lesmes3d993812018-04-02 12:52:49 -0400646def _ShiftLinesInTokens(tokens, delta, start):
647 new_tokens = {}
648 for token in tokens.values():
649 if token[2][0] >= start:
650 token[2] = token[2][0] + delta, token[2][1]
651 token[3] = token[3][0] + delta, token[3][1]
652 new_tokens[token[2]] = token
653 return new_tokens
654
655
656def AddVar(gclient_dict, var_name, value):
657 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
658 raise ValueError(
659 "Can't use SetVar for the given gclient dict. It contains no "
660 "formatting information.")
661
662 if 'vars' not in gclient_dict:
663 raise KeyError("vars dict is not defined.")
664
665 if var_name in gclient_dict['vars']:
666 raise ValueError(
667 "%s has already been declared in the vars dict. Consider using SetVar "
668 "instead." % var_name)
669
670 if not gclient_dict['vars']:
671 raise ValueError('vars dict is empty. This is not yet supported.')
672
Edward Lesmes8d626572018-04-05 17:53:10 -0400673 # We will attempt to add the var right after 'vars = {'.
674 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400675 if node is None:
676 raise ValueError(
677 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400678 line = node.lineno + 1
679
680 # We will try to match the new var's indentation to the next variable.
681 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400682
683 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000684 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400685 var_ast = ast.parse(var_content).body[0].value
686
687 # Set the ast nodes for the key and value.
688 vars_node = gclient_dict.GetNode('vars')
689
690 var_name_node = var_ast.keys[0]
691 var_name_node.lineno += line - 2
692 vars_node.keys.insert(0, var_name_node)
693
694 value_node = var_ast.values[0]
695 value_node.lineno += line - 2
696 vars_node.values.insert(0, value_node)
697
698 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000699 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400700 var_tokens = {
701 token[2]: list(token)
702 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000703 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400704 }
705
706 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
707 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
708
709
Edward Lesmes6f64a052018-03-20 17:35:49 -0400710def SetVar(gclient_dict, var_name, value):
711 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
712 raise ValueError(
713 "Can't use SetVar for the given gclient dict. It contains no "
714 "formatting information.")
715 tokens = gclient_dict.tokens
716
Edward Lesmes3d993812018-04-02 12:52:49 -0400717 if 'vars' not in gclient_dict:
718 raise KeyError("vars dict is not defined.")
719
720 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400721 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400722 "%s has not been declared in the vars dict. Consider using AddVar "
723 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400724
725 node = gclient_dict['vars'].GetNode(var_name)
726 if node is None:
727 raise ValueError(
728 "The vars entry for %s has no formatting information." % var_name)
729
730 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400731 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400732
733
Edward Lemura1e4d482018-12-17 19:01:03 +0000734def _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
Edward Lesmes6f64a052018-03-20 17:35:49 -0400743def SetCIPD(gclient_dict, dep_name, package_name, new_version):
744 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
745 raise ValueError(
746 "Can't use SetCIPD for the given gclient dict. It contains no "
747 "formatting information.")
748 tokens = gclient_dict.tokens
749
750 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400751 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400752 "Could not find any dependency called %s." % dep_name)
753
754 # Find the package with the given name
755 packages = [
756 package
757 for package in gclient_dict['deps'][dep_name]['packages']
758 if package['package'] == package_name
759 ]
760 if len(packages) != 1:
761 raise ValueError(
762 "There must be exactly one package with the given name (%s), "
763 "%s were found." % (package_name, len(packages)))
764
765 # TODO(ehmaldonado): Support Var in package's version.
766 node = packages[0].GetNode('version')
767 if node is None:
768 raise ValueError(
769 "The deps entry for %s:%s has no formatting information." %
770 (dep_name, package_name))
771
Edward Lemura1e4d482018-12-17 19:01:03 +0000772 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
773 raise ValueError(
774 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000775 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000776
777 var_name = _GetVarName(node)
778 if var_name is not None:
779 SetVar(gclient_dict, var_name, new_version)
780 else:
781 _UpdateAstString(tokens, node, new_version)
782 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400783
784
Edward Lesmes9f531292018-03-20 21:27:15 -0400785def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400786 def _UpdateRevision(dep_dict, dep_key, new_revision):
787 dep_node = dep_dict.GetNode(dep_key)
788 if dep_node is None:
789 raise ValueError(
790 "The deps entry for %s has no formatting information." % dep_name)
791
792 node = dep_node
793 if isinstance(node, ast.BinOp):
794 node = node.right
795
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000796 if isinstance(node, ast.Str):
797 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
798 if token != node.s:
799 raise ValueError(
800 'Can\'t update value for %s. Multiline strings and implicitly '
801 'concatenated strings are not supported.\n'
802 'Consider reformatting the DEPS file.' % dep_key)
Edward Lemur3c117942020-03-12 17:21:12 +0000803
804
Edward Lesmes62af4e42018-03-30 18:15:44 -0400805 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
806 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000807 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000808 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400809
810 var_name = _GetVarName(node)
811 if var_name is not None:
812 SetVar(gclient_dict, var_name, new_revision)
813 else:
814 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400815 # '@' is part of the last string, which we want to modify. Discard
816 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400817 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400818 elif '@' not in dep_dict[dep_key]:
819 # '@' is not part of the URL at all. This mean the dependency is
820 # unpinned and we should pin it.
821 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400822 _UpdateAstString(tokens, node, new_revision)
823 dep_dict.SetNode(dep_key, new_revision, node)
824
Edward Lesmes6f64a052018-03-20 17:35:49 -0400825 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
826 raise ValueError(
827 "Can't use SetRevision for the given gclient dict. It contains no "
828 "formatting information.")
829 tokens = gclient_dict.tokens
830
831 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400832 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400833 "Could not find any dependency called %s." % dep_name)
834
Edward Lesmes6f64a052018-03-20 17:35:49 -0400835 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400836 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400837 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400838 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400839
840
841def GetVar(gclient_dict, var_name):
842 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
843 raise KeyError(
844 "Could not find any variable called %s." % var_name)
845
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000846 val = gclient_dict['vars'][var_name]
847 if isinstance(val, ConstantString):
848 return val.value
849 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400850
851
852def GetCIPD(gclient_dict, dep_name, package_name):
853 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
854 raise KeyError(
855 "Could not find any dependency called %s." % dep_name)
856
857 # Find the package with the given name
858 packages = [
859 package
860 for package in gclient_dict['deps'][dep_name]['packages']
861 if package['package'] == package_name
862 ]
863 if len(packages) != 1:
864 raise ValueError(
865 "There must be exactly one package with the given name (%s), "
866 "%s were found." % (package_name, len(packages)))
867
Edward Lemura92b9612018-07-03 02:34:32 +0000868 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400869
870
871def GetRevision(gclient_dict, dep_name):
872 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
873 raise KeyError(
874 "Could not find any dependency called %s." % dep_name)
875
876 dep = gclient_dict['deps'][dep_name]
877 if dep is None:
878 return None
879 elif isinstance(dep, basestring):
880 _, _, revision = dep.partition('@')
881 return revision or None
Raul Tambre6693d092020-02-19 20:36:45 +0000882 elif isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400883 _, _, revision = dep['url'].partition('@')
884 return revision or None
885 else:
886 raise ValueError(
887 '%s is not a valid git dependency.' % dep_name)