blob: c0098e4d431c84c3bc1786cce69e75534fa15bde [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
Michael Spang0e99b9b2020-08-12 13:34:48 +0000238 # For recursed-upon sub-dependencies, run their hooks relative to the
239 # parent's path instead of relative to the .gclient file.
240 schema.Optional('use_relative_hooks'): bool,
241
Raul Tambreb946b232019-03-26 14:48:46 +0000242 # Variables that can be referenced using Var() - see 'deps'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000243 schema.Optional('vars'): _NodeDictSchema({
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000244 schema.Optional(basestring): schema.Or(ConstantString,
245 basestring,
246 bool),
Aaron Gableac9b0f32019-04-18 17:38:37 +0000247 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000248 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200249
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200250
Edward Lemure05f18d2018-06-08 17:36:53 +0000251def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200252 """Safely evaluates a single expression. Returns the result."""
253 _allowed_names = {'None': None, 'True': True, 'False': False}
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000254 if isinstance(node_or_string, ConstantString):
255 return node_or_string.value
Aaron Gableac9b0f32019-04-18 17:38:37 +0000256 if isinstance(node_or_string, basestring):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200257 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
258 if isinstance(node_or_string, ast.Expression):
259 node_or_string = node_or_string.body
260 def _convert(node):
261 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000262 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000263 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400264 try:
265 return node.s.format(**vars_dict)
266 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000267 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400268 '%s was used as a variable, but was not declared in the vars dict '
269 '(file %r, line %s)' % (
Edward Lemurba1b1f72019-07-27 00:41:59 +0000270 e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200271 elif isinstance(node, ast.Num):
272 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200273 elif isinstance(node, ast.Tuple):
274 return tuple(map(_convert, node.elts))
275 elif isinstance(node, ast.List):
276 return list(map(_convert, node.elts))
277 elif isinstance(node, ast.Dict):
Edward Lemurc00ac8d2020-03-04 23:37:57 +0000278 node_dict = _NodeDict()
279 for key_node, value_node in zip(node.keys, node.values):
280 key = _convert(key_node)
281 if key in node_dict:
282 raise ValueError(
283 'duplicate key in dictionary: %s (file %r, line %s)' % (
284 key, filename, getattr(key_node, 'lineno', '<unknown>')))
285 node_dict.SetNode(key, _convert(value_node), value_node)
286 return node_dict
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200287 elif isinstance(node, ast.Name):
288 if node.id not in _allowed_names:
289 raise ValueError(
290 'invalid name %r (file %r, line %s)' % (
291 node.id, filename, getattr(node, 'lineno', '<unknown>')))
292 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000293 elif not sys.version_info[:2] < (3, 4) and isinstance(
294 node, ast.NameConstant): # Since Python 3.4
295 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200296 elif isinstance(node, ast.Call):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000297 if (not isinstance(node.func, ast.Name) or
298 (node.func.id not in ('Str', 'Var'))):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200299 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000300 'Str and Var are the only allowed functions (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200301 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000302 if node.keywords or getattr(node, 'starargs', None) or getattr(
303 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200304 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000305 '%s takes exactly one argument (file %r, line %s)' % (
306 node.func.id, filename, getattr(node, 'lineno', '<unknown>')))
307 if node.func.id == 'Str':
308 if isinstance(node.args[0], ast.Str):
309 return ConstantString(node.args[0].s)
310 raise ValueError('Passed a non-string to Str() (file %r, line%s)' % (
311 filename, getattr(node, 'lineno', '<unknown>')))
312 else:
313 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000314 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400315 raise ValueError(
316 'Var\'s argument must be a variable name (file %r, line %s)' % (
317 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400318 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000319 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400320 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000321 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400322 '%s was used as a variable, but was not declared in the vars dict '
323 '(file %r, line %s)' % (
324 arg, filename, getattr(node, 'lineno', '<unknown>')))
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000325 val = vars_dict[arg]
326 if isinstance(val, ConstantString):
327 val = val.value
328 return val
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200329 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
330 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200331 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
332 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200333 else:
334 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200335 'unexpected AST node: %s %s (file %r, line %s)' % (
336 node, ast.dump(node), filename,
337 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200338 return _convert(node_or_string)
339
340
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000341def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400342 """Safely execs a set of assignments."""
343 def _validate_statement(node, local_scope):
344 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200345 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200346 'unexpected AST node: %s %s (file %r, line %s)' % (
347 node, ast.dump(node), filename,
348 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200349
Edward Lesmes6c24d372018-03-28 12:52:29 -0400350 if len(node.targets) != 1:
351 raise ValueError(
352 'invalid assignment: use exactly one target (file %r, line %s)' % (
353 filename, getattr(node, 'lineno', '<unknown>')))
354
355 target = node.targets[0]
356 if not isinstance(target, ast.Name):
357 raise ValueError(
358 'invalid assignment: target should be a name (file %r, line %s)' % (
359 filename, getattr(node, 'lineno', '<unknown>')))
360 if target.id in local_scope:
361 raise ValueError(
362 'invalid assignment: overrides var %r (file %r, line %s)' % (
363 target.id, filename, getattr(node, 'lineno', '<unknown>')))
364
365 node_or_string = ast.parse(content, filename=filename, mode='exec')
366 if isinstance(node_or_string, ast.Expression):
367 node_or_string = node_or_string.body
368
369 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200370 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200371 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200372 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200373 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200374 filename,
375 getattr(node_or_string, 'lineno', '<unknown>')))
376
Edward Lesmes6c24d372018-03-28 12:52:29 -0400377 statements = {}
378 for statement in node_or_string.body:
379 _validate_statement(statement, statements)
380 statements[statement.targets[0].id] = statement.value
381
Raul Tambreb946b232019-03-26 14:48:46 +0000382 # The tokenized representation needs to end with a newline token, otherwise
383 # untokenization will trigger an assert later on.
384 # In Python 2.7 on Windows we need to ensure the input ends with a newline
385 # for a newline token to be generated.
386 # In other cases a newline token is always generated during tokenization so
387 # this has no effect.
388 # TODO: Remove this workaround after migrating to Python 3.
389 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400390 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000391 token[2]: list(token) for token in tokenize.generate_tokens(
392 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400393 }
Raul Tambreb946b232019-03-26 14:48:46 +0000394
Edward Lesmes6c24d372018-03-28 12:52:29 -0400395 local_scope = _NodeDict({}, tokens)
396
397 # Process vars first, so we can expand variables in the rest of the DEPS file.
398 vars_dict = {}
399 if 'vars' in statements:
400 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000401 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400402 local_scope.SetNode('vars', value, vars_statement)
403 # Update the parsed vars with the overrides, but only if they are already
404 # present (overrides do not introduce new variables).
405 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000406
407 if builtin_vars:
408 vars_dict.update(builtin_vars)
409
410 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000411 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400412
Raul Tambreb946b232019-03-26 14:48:46 +0000413 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000414 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400415 local_scope.SetNode(name, value, node)
416
Edward Lemur67cabcd2020-03-03 19:31:15 +0000417 try:
418 return _GCLIENT_SCHEMA.validate(local_scope)
419 except schema.SchemaError as e:
420 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400421
422
Edward Lemur16f4bad2018-05-16 16:53:49 -0400423def _StandardizeDeps(deps_dict, vars_dict):
424 """"Standardizes the deps_dict.
425
426 For each dependency:
427 - Expands the variable in the dependency name.
428 - Ensures the dependency is a dictionary.
429 - Set's the 'dep_type' to be 'git' by default.
430 """
431 new_deps_dict = {}
432 for dep_name, dep_info in deps_dict.items():
433 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000434 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400435 dep_info = {'url': dep_info}
436 dep_info.setdefault('dep_type', 'git')
437 new_deps_dict[dep_name] = dep_info
438 return new_deps_dict
439
440
441def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
442 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
443
444 The dependencies in os_deps_dict are transformed into conditional dependencies
445 using |'checkout_' + os_name|.
446 If the dependency is already present, the URL and revision must coincide.
447 """
448 for dep_name, dep_info in os_deps_dict.items():
449 # Make this condition very visible, so it's not a silent failure.
450 # It's unclear how to support None override in deps_os.
451 if dep_info['url'] is None:
452 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
453 continue
454
455 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
456 UpdateCondition(dep_info, 'and', os_condition)
457
458 if dep_name in deps_dict:
459 if deps_dict[dep_name]['url'] != dep_info['url']:
460 raise gclient_utils.Error(
461 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
462 'entry (%r).' % (
463 os_name, dep_name, dep_info, deps_dict[dep_name]))
464
465 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
466
467 deps_dict[dep_name] = dep_info
468
469
470def UpdateCondition(info_dict, op, new_condition):
471 """Updates info_dict's condition with |new_condition|.
472
473 An absent value is treated as implicitly True.
474 """
475 curr_condition = info_dict.get('condition')
476 # Easy case: Both are present.
477 if curr_condition and new_condition:
478 info_dict['condition'] = '(%s) %s (%s)' % (
479 curr_condition, op, new_condition)
480 # If |op| == 'and', and at least one condition is present, then use it.
481 elif op == 'and' and (curr_condition or new_condition):
482 info_dict['condition'] = curr_condition or new_condition
483 # Otherwise, no condition should be set
484 elif curr_condition:
485 del info_dict['condition']
486
487
Edward Lemur67cabcd2020-03-03 19:31:15 +0000488def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400489 """Parses DEPS strings.
490
491 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000492 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400493 variable expansion.
494
495 Args:
496 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400497 filename: str. The name of the DEPS file, or a string describing the source
498 of the content, e.g. '<string>', '<unknown>'.
499 vars_override: dict, optional. A dictionary with overrides for the variables
500 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000501 builtin_vars: dict, optional. A dictionary with variables that are provided
502 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400503
504 Returns:
505 A Python dict with the parsed contents of the DEPS file, as specified by the
506 schema above.
507 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000508 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400509
510 vars_dict = result.get('vars', {})
511 if 'deps' in result:
512 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
513
514 if 'deps_os' in result:
515 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000516 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400517 os_deps = _StandardizeDeps(os_deps, vars_dict)
518 _MergeDepsOs(deps, os_deps, os_name)
519 del result['deps_os']
520
521 if 'hooks_os' in result:
522 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000523 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400524 for hook in os_hooks:
525 UpdateCondition(hook, 'and', 'checkout_' + os_name)
526 hooks.extend(os_hooks)
527 del result['hooks_os']
528
529 return result
530
531
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200532def EvaluateCondition(condition, variables, referenced_variables=None):
533 """Safely evaluates a boolean condition. Returns the result."""
534 if not referenced_variables:
535 referenced_variables = set()
536 _allowed_names = {'None': None, 'True': True, 'False': False}
537 main_node = ast.parse(condition, mode='eval')
538 if isinstance(main_node, ast.Expression):
539 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000540 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200541 if isinstance(node, ast.Str):
542 return node.s
Ben Pastenea541b282019-05-24 00:25:12 +0000543 elif isinstance(node, ast.Tuple) and allow_tuple:
544 return tuple(map(_convert, node.elts))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200545 elif isinstance(node, ast.Name):
546 if node.id in referenced_variables:
547 raise ValueError(
548 'invalid cyclic reference to %r (inside %r)' % (
549 node.id, condition))
550 elif node.id in _allowed_names:
551 return _allowed_names[node.id]
552 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200553 value = variables[node.id]
554
555 # Allow using "native" types, without wrapping everything in strings.
556 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000557 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200558 return value
559
560 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200561 return EvaluateCondition(
562 variables[node.id],
563 variables,
564 referenced_variables.union([node.id]))
565 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200566 # Implicitly convert unrecognized names to strings.
567 # If we want to change this, we'll need to explicitly distinguish
568 # between arguments for GN to be passed verbatim, and ones to
569 # be evaluated.
570 return node.id
Edward Lemurba1b1f72019-07-27 00:41:59 +0000571 elif not sys.version_info[:2] < (3, 4) and isinstance(
572 node, ast.NameConstant): # Since Python 3.4
573 return node.value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200574 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000575 bool_values = []
576 for value in node.values:
577 bool_values.append(_convert(value))
578 if not isinstance(bool_values[-1], bool):
579 raise ValueError(
580 'invalid "or" operand %r (inside %r)' % (
581 bool_values[-1], condition))
582 return any(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200583 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000584 bool_values = []
585 for value in node.values:
586 bool_values.append(_convert(value))
587 if not isinstance(bool_values[-1], bool):
588 raise ValueError(
589 'invalid "and" operand %r (inside %r)' % (
590 bool_values[-1], condition))
591 return all(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200592 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200593 value = _convert(node.operand)
594 if not isinstance(value, bool):
595 raise ValueError(
596 'invalid "not" operand %r (inside %r)' % (value, condition))
597 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200598 elif isinstance(node, ast.Compare):
599 if len(node.ops) != 1:
600 raise ValueError(
601 'invalid compare: exactly 1 operator required (inside %r)' % (
602 condition))
603 if len(node.comparators) != 1:
604 raise ValueError(
605 'invalid compare: exactly 1 comparator required (inside %r)' % (
606 condition))
607
608 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000609 right = _convert(
610 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200611
612 if isinstance(node.ops[0], ast.Eq):
613 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700614 if isinstance(node.ops[0], ast.NotEq):
615 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000616 if isinstance(node.ops[0], ast.In):
617 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200618
619 raise ValueError(
620 'unexpected operator: %s %s (inside %r)' % (
621 node.ops[0], ast.dump(node), condition))
622 else:
623 raise ValueError(
624 'unexpected AST node: %s %s (inside %r)' % (
625 node, ast.dump(node), condition))
626 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400627
628
629def RenderDEPSFile(gclient_dict):
630 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000631 # The last token is a newline, which we ensure in Exec() for compatibility.
632 # However tests pass in inputs not ending with a newline and expect the same
633 # back, so for backwards compatibility need to remove that newline character.
634 # TODO: Fix tests to expect the newline
635 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400636
637
638def _UpdateAstString(tokens, node, value):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000639 if isinstance(node, ast.Call):
640 node = node.args[0]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400641 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000642 quote_char = ''
643 if isinstance(node, ast.Str):
644 quote_char = tokens[position][1][0]
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000645 value = value.encode('unicode_escape').decode('utf-8')
Edward Lesmes62af4e42018-03-30 18:15:44 -0400646 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400647 node.s = value
648
649
Edward Lesmes3d993812018-04-02 12:52:49 -0400650def _ShiftLinesInTokens(tokens, delta, start):
651 new_tokens = {}
652 for token in tokens.values():
653 if token[2][0] >= start:
654 token[2] = token[2][0] + delta, token[2][1]
655 token[3] = token[3][0] + delta, token[3][1]
656 new_tokens[token[2]] = token
657 return new_tokens
658
659
660def AddVar(gclient_dict, var_name, value):
661 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
662 raise ValueError(
663 "Can't use SetVar for the given gclient dict. It contains no "
664 "formatting information.")
665
666 if 'vars' not in gclient_dict:
667 raise KeyError("vars dict is not defined.")
668
669 if var_name in gclient_dict['vars']:
670 raise ValueError(
671 "%s has already been declared in the vars dict. Consider using SetVar "
672 "instead." % var_name)
673
674 if not gclient_dict['vars']:
675 raise ValueError('vars dict is empty. This is not yet supported.')
676
Edward Lesmes8d626572018-04-05 17:53:10 -0400677 # We will attempt to add the var right after 'vars = {'.
678 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400679 if node is None:
680 raise ValueError(
681 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400682 line = node.lineno + 1
683
684 # We will try to match the new var's indentation to the next variable.
685 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400686
687 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000688 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400689 var_ast = ast.parse(var_content).body[0].value
690
691 # Set the ast nodes for the key and value.
692 vars_node = gclient_dict.GetNode('vars')
693
694 var_name_node = var_ast.keys[0]
695 var_name_node.lineno += line - 2
696 vars_node.keys.insert(0, var_name_node)
697
698 value_node = var_ast.values[0]
699 value_node.lineno += line - 2
700 vars_node.values.insert(0, value_node)
701
702 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000703 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400704 var_tokens = {
705 token[2]: list(token)
706 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000707 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400708 }
709
710 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
711 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
712
713
Edward Lesmes6f64a052018-03-20 17:35:49 -0400714def SetVar(gclient_dict, var_name, value):
715 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
716 raise ValueError(
717 "Can't use SetVar for the given gclient dict. It contains no "
718 "formatting information.")
719 tokens = gclient_dict.tokens
720
Edward Lesmes3d993812018-04-02 12:52:49 -0400721 if 'vars' not in gclient_dict:
722 raise KeyError("vars dict is not defined.")
723
724 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400725 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400726 "%s has not been declared in the vars dict. Consider using AddVar "
727 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400728
729 node = gclient_dict['vars'].GetNode(var_name)
730 if node is None:
731 raise ValueError(
732 "The vars entry for %s has no formatting information." % var_name)
733
734 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400735 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400736
737
Edward Lemura1e4d482018-12-17 19:01:03 +0000738def _GetVarName(node):
739 if isinstance(node, ast.Call):
740 return node.args[0].s
741 elif node.s.endswith('}'):
742 last_brace = node.s.rfind('{')
743 return node.s[last_brace+1:-1]
744 return None
745
746
Edward Lesmes6f64a052018-03-20 17:35:49 -0400747def SetCIPD(gclient_dict, dep_name, package_name, new_version):
748 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
749 raise ValueError(
750 "Can't use SetCIPD for the given gclient dict. It contains no "
751 "formatting information.")
752 tokens = gclient_dict.tokens
753
754 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400755 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400756 "Could not find any dependency called %s." % dep_name)
757
758 # Find the package with the given name
759 packages = [
760 package
761 for package in gclient_dict['deps'][dep_name]['packages']
762 if package['package'] == package_name
763 ]
764 if len(packages) != 1:
765 raise ValueError(
766 "There must be exactly one package with the given name (%s), "
767 "%s were found." % (package_name, len(packages)))
768
769 # TODO(ehmaldonado): Support Var in package's version.
770 node = packages[0].GetNode('version')
771 if node is None:
772 raise ValueError(
773 "The deps entry for %s:%s has no formatting information." %
774 (dep_name, package_name))
775
Edward Lemura1e4d482018-12-17 19:01:03 +0000776 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
777 raise ValueError(
778 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000779 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000780
781 var_name = _GetVarName(node)
782 if var_name is not None:
783 SetVar(gclient_dict, var_name, new_version)
784 else:
785 _UpdateAstString(tokens, node, new_version)
786 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400787
788
Edward Lesmes9f531292018-03-20 21:27:15 -0400789def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400790 def _UpdateRevision(dep_dict, dep_key, new_revision):
791 dep_node = dep_dict.GetNode(dep_key)
792 if dep_node is None:
793 raise ValueError(
794 "The deps entry for %s has no formatting information." % dep_name)
795
796 node = dep_node
797 if isinstance(node, ast.BinOp):
798 node = node.right
799
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000800 if isinstance(node, ast.Str):
801 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
802 if token != node.s:
803 raise ValueError(
804 'Can\'t update value for %s. Multiline strings and implicitly '
805 'concatenated strings are not supported.\n'
806 'Consider reformatting the DEPS file.' % dep_key)
Edward Lemur3c117942020-03-12 17:21:12 +0000807
808
Edward Lesmes62af4e42018-03-30 18:15:44 -0400809 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
810 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000811 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000812 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400813
814 var_name = _GetVarName(node)
815 if var_name is not None:
816 SetVar(gclient_dict, var_name, new_revision)
817 else:
818 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400819 # '@' is part of the last string, which we want to modify. Discard
820 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400821 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400822 elif '@' not in dep_dict[dep_key]:
823 # '@' is not part of the URL at all. This mean the dependency is
824 # unpinned and we should pin it.
825 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400826 _UpdateAstString(tokens, node, new_revision)
827 dep_dict.SetNode(dep_key, new_revision, node)
828
Edward Lesmes6f64a052018-03-20 17:35:49 -0400829 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
830 raise ValueError(
831 "Can't use SetRevision for the given gclient dict. It contains no "
832 "formatting information.")
833 tokens = gclient_dict.tokens
834
835 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400836 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400837 "Could not find any dependency called %s." % dep_name)
838
Edward Lesmes6f64a052018-03-20 17:35:49 -0400839 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400840 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400841 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400842 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400843
844
845def GetVar(gclient_dict, var_name):
846 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
847 raise KeyError(
848 "Could not find any variable called %s." % var_name)
849
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000850 val = gclient_dict['vars'][var_name]
851 if isinstance(val, ConstantString):
852 return val.value
853 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400854
855
856def GetCIPD(gclient_dict, dep_name, package_name):
857 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
858 raise KeyError(
859 "Could not find any dependency called %s." % dep_name)
860
861 # Find the package with the given name
862 packages = [
863 package
864 for package in gclient_dict['deps'][dep_name]['packages']
865 if package['package'] == package_name
866 ]
867 if len(packages) != 1:
868 raise ValueError(
869 "There must be exactly one package with the given name (%s), "
870 "%s were found." % (package_name, len(packages)))
871
Edward Lemura92b9612018-07-03 02:34:32 +0000872 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400873
874
875def GetRevision(gclient_dict, dep_name):
876 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
877 raise KeyError(
878 "Could not find any dependency called %s." % dep_name)
879
880 dep = gclient_dict['deps'][dep_name]
881 if dep is None:
882 return None
883 elif isinstance(dep, basestring):
884 _, _, revision = dep.partition('@')
885 return revision or None
Raul Tambre6693d092020-02-19 20:36:45 +0000886 elif isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400887 _, _, revision = dep['url'].partition('@')
888 return revision or None
889 else:
890 raise ValueError(
891 '%s is not a valid git dependency.' % dep_name)