blob: 11141d118cb60bd862291ac751d096e59fa9dd9e [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
Aravind Vasudevan22bf6052022-01-24 21:11:19 +000041
42 return self.value == other
Dirk Prankefdd2cd62020-06-30 23:30:47 +000043
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>')))
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000307
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000308 if node.func.id == 'Str':
309 if isinstance(node.args[0], ast.Str):
310 return ConstantString(node.args[0].s)
311 raise ValueError('Passed a non-string to Str() (file %r, line%s)' % (
312 filename, getattr(node, 'lineno', '<unknown>')))
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000313
314 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000315 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400316 raise ValueError(
317 'Var\'s argument must be a variable name (file %r, line %s)' % (
318 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400319 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000320 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400321 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000322 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400323 '%s was used as a variable, but was not declared in the vars dict '
324 '(file %r, line %s)' % (
325 arg, filename, getattr(node, 'lineno', '<unknown>')))
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000326 val = vars_dict[arg]
327 if isinstance(val, ConstantString):
328 val = val.value
329 return val
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200330 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
331 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200332 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
333 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200334 else:
335 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200336 'unexpected AST node: %s %s (file %r, line %s)' % (
337 node, ast.dump(node), filename,
338 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200339 return _convert(node_or_string)
340
341
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000342def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400343 """Safely execs a set of assignments."""
344 def _validate_statement(node, local_scope):
345 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200346 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200347 'unexpected AST node: %s %s (file %r, line %s)' % (
348 node, ast.dump(node), filename,
349 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200350
Edward Lesmes6c24d372018-03-28 12:52:29 -0400351 if len(node.targets) != 1:
352 raise ValueError(
353 'invalid assignment: use exactly one target (file %r, line %s)' % (
354 filename, getattr(node, 'lineno', '<unknown>')))
355
356 target = node.targets[0]
357 if not isinstance(target, ast.Name):
358 raise ValueError(
359 'invalid assignment: target should be a name (file %r, line %s)' % (
360 filename, getattr(node, 'lineno', '<unknown>')))
361 if target.id in local_scope:
362 raise ValueError(
363 'invalid assignment: overrides var %r (file %r, line %s)' % (
364 target.id, filename, getattr(node, 'lineno', '<unknown>')))
365
366 node_or_string = ast.parse(content, filename=filename, mode='exec')
367 if isinstance(node_or_string, ast.Expression):
368 node_or_string = node_or_string.body
369
370 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200371 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200372 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200373 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200374 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200375 filename,
376 getattr(node_or_string, 'lineno', '<unknown>')))
377
Edward Lesmes6c24d372018-03-28 12:52:29 -0400378 statements = {}
379 for statement in node_or_string.body:
380 _validate_statement(statement, statements)
381 statements[statement.targets[0].id] = statement.value
382
Raul Tambreb946b232019-03-26 14:48:46 +0000383 # The tokenized representation needs to end with a newline token, otherwise
384 # untokenization will trigger an assert later on.
385 # In Python 2.7 on Windows we need to ensure the input ends with a newline
386 # for a newline token to be generated.
387 # In other cases a newline token is always generated during tokenization so
388 # this has no effect.
389 # TODO: Remove this workaround after migrating to Python 3.
390 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400391 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000392 token[2]: list(token) for token in tokenize.generate_tokens(
393 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400394 }
Raul Tambreb946b232019-03-26 14:48:46 +0000395
Edward Lesmes6c24d372018-03-28 12:52:29 -0400396 local_scope = _NodeDict({}, tokens)
397
398 # Process vars first, so we can expand variables in the rest of the DEPS file.
399 vars_dict = {}
400 if 'vars' in statements:
401 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000402 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400403 local_scope.SetNode('vars', value, vars_statement)
404 # Update the parsed vars with the overrides, but only if they are already
405 # present (overrides do not introduce new variables).
406 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000407
408 if builtin_vars:
409 vars_dict.update(builtin_vars)
410
411 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000412 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400413
Raul Tambreb946b232019-03-26 14:48:46 +0000414 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000415 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400416 local_scope.SetNode(name, value, node)
417
Edward Lemur67cabcd2020-03-03 19:31:15 +0000418 try:
419 return _GCLIENT_SCHEMA.validate(local_scope)
420 except schema.SchemaError as e:
421 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400422
423
Edward Lemur16f4bad2018-05-16 16:53:49 -0400424def _StandardizeDeps(deps_dict, vars_dict):
425 """"Standardizes the deps_dict.
426
427 For each dependency:
428 - Expands the variable in the dependency name.
429 - Ensures the dependency is a dictionary.
430 - Set's the 'dep_type' to be 'git' by default.
431 """
432 new_deps_dict = {}
433 for dep_name, dep_info in deps_dict.items():
434 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000435 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400436 dep_info = {'url': dep_info}
437 dep_info.setdefault('dep_type', 'git')
438 new_deps_dict[dep_name] = dep_info
439 return new_deps_dict
440
441
442def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
443 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
444
445 The dependencies in os_deps_dict are transformed into conditional dependencies
446 using |'checkout_' + os_name|.
447 If the dependency is already present, the URL and revision must coincide.
448 """
449 for dep_name, dep_info in os_deps_dict.items():
450 # Make this condition very visible, so it's not a silent failure.
451 # It's unclear how to support None override in deps_os.
452 if dep_info['url'] is None:
453 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
454 continue
455
456 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
457 UpdateCondition(dep_info, 'and', os_condition)
458
459 if dep_name in deps_dict:
460 if deps_dict[dep_name]['url'] != dep_info['url']:
461 raise gclient_utils.Error(
462 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
463 'entry (%r).' % (
464 os_name, dep_name, dep_info, deps_dict[dep_name]))
465
466 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
467
468 deps_dict[dep_name] = dep_info
469
470
471def UpdateCondition(info_dict, op, new_condition):
472 """Updates info_dict's condition with |new_condition|.
473
474 An absent value is treated as implicitly True.
475 """
476 curr_condition = info_dict.get('condition')
477 # Easy case: Both are present.
478 if curr_condition and new_condition:
479 info_dict['condition'] = '(%s) %s (%s)' % (
480 curr_condition, op, new_condition)
481 # If |op| == 'and', and at least one condition is present, then use it.
482 elif op == 'and' and (curr_condition or new_condition):
483 info_dict['condition'] = curr_condition or new_condition
484 # Otherwise, no condition should be set
485 elif curr_condition:
486 del info_dict['condition']
487
488
Edward Lemur67cabcd2020-03-03 19:31:15 +0000489def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400490 """Parses DEPS strings.
491
492 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000493 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400494 variable expansion.
495
496 Args:
497 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400498 filename: str. The name of the DEPS file, or a string describing the source
499 of the content, e.g. '<string>', '<unknown>'.
500 vars_override: dict, optional. A dictionary with overrides for the variables
501 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000502 builtin_vars: dict, optional. A dictionary with variables that are provided
503 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400504
505 Returns:
506 A Python dict with the parsed contents of the DEPS file, as specified by the
507 schema above.
508 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000509 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400510
511 vars_dict = result.get('vars', {})
512 if 'deps' in result:
513 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
514
515 if 'deps_os' in result:
516 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000517 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400518 os_deps = _StandardizeDeps(os_deps, vars_dict)
519 _MergeDepsOs(deps, os_deps, os_name)
520 del result['deps_os']
521
522 if 'hooks_os' in result:
523 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000524 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400525 for hook in os_hooks:
526 UpdateCondition(hook, 'and', 'checkout_' + os_name)
527 hooks.extend(os_hooks)
528 del result['hooks_os']
529
530 return result
531
532
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200533def EvaluateCondition(condition, variables, referenced_variables=None):
534 """Safely evaluates a boolean condition. Returns the result."""
535 if not referenced_variables:
536 referenced_variables = set()
537 _allowed_names = {'None': None, 'True': True, 'False': False}
538 main_node = ast.parse(condition, mode='eval')
539 if isinstance(main_node, ast.Expression):
540 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000541 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200542 if isinstance(node, ast.Str):
543 return node.s
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000544
545 if isinstance(node, ast.Tuple) and allow_tuple:
Ben Pastenea541b282019-05-24 00:25:12 +0000546 return tuple(map(_convert, node.elts))
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000547
548 if isinstance(node, ast.Name):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200549 if node.id in referenced_variables:
550 raise ValueError(
551 'invalid cyclic reference to %r (inside %r)' % (
552 node.id, condition))
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000553
554 if node.id in _allowed_names:
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200555 return _allowed_names[node.id]
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000556
557 if node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200558 value = variables[node.id]
559
560 # Allow using "native" types, without wrapping everything in strings.
561 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000562 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200563 return value
564
565 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200566 return EvaluateCondition(
567 variables[node.id],
568 variables,
569 referenced_variables.union([node.id]))
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000570
571 # Implicitly convert unrecognized names to strings.
572 # If we want to change this, we'll need to explicitly distinguish
573 # between arguments for GN to be passed verbatim, and ones to
574 # be evaluated.
575 return node.id
576
577 if not sys.version_info[:2] < (3, 4) and isinstance(
Edward Lemurba1b1f72019-07-27 00:41:59 +0000578 node, ast.NameConstant): # Since Python 3.4
579 return node.value
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000580
581 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000582 bool_values = []
583 for value in node.values:
584 bool_values.append(_convert(value))
585 if not isinstance(bool_values[-1], bool):
586 raise ValueError(
587 'invalid "or" operand %r (inside %r)' % (
588 bool_values[-1], condition))
589 return any(bool_values)
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000590
591 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000592 bool_values = []
593 for value in node.values:
594 bool_values.append(_convert(value))
595 if not isinstance(bool_values[-1], bool):
596 raise ValueError(
597 'invalid "and" operand %r (inside %r)' % (
598 bool_values[-1], condition))
599 return all(bool_values)
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000600
601 if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200602 value = _convert(node.operand)
603 if not isinstance(value, bool):
604 raise ValueError(
605 'invalid "not" operand %r (inside %r)' % (value, condition))
606 return not value
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000607
608 if isinstance(node, ast.Compare):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200609 if len(node.ops) != 1:
610 raise ValueError(
611 'invalid compare: exactly 1 operator required (inside %r)' % (
612 condition))
613 if len(node.comparators) != 1:
614 raise ValueError(
615 'invalid compare: exactly 1 comparator required (inside %r)' % (
616 condition))
617
618 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000619 right = _convert(
620 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200621
622 if isinstance(node.ops[0], ast.Eq):
623 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700624 if isinstance(node.ops[0], ast.NotEq):
625 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000626 if isinstance(node.ops[0], ast.In):
627 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200628
629 raise ValueError(
630 'unexpected operator: %s %s (inside %r)' % (
631 node.ops[0], ast.dump(node), condition))
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000632
633 raise ValueError(
634 'unexpected AST node: %s %s (inside %r)' % (
635 node, ast.dump(node), condition))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200636 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400637
638
639def RenderDEPSFile(gclient_dict):
640 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000641 # The last token is a newline, which we ensure in Exec() for compatibility.
642 # However tests pass in inputs not ending with a newline and expect the same
643 # back, so for backwards compatibility need to remove that newline character.
644 # TODO: Fix tests to expect the newline
645 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400646
647
648def _UpdateAstString(tokens, node, value):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000649 if isinstance(node, ast.Call):
650 node = node.args[0]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400651 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000652 quote_char = ''
653 if isinstance(node, ast.Str):
654 quote_char = tokens[position][1][0]
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000655 value = value.encode('unicode_escape').decode('utf-8')
Edward Lesmes62af4e42018-03-30 18:15:44 -0400656 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400657 node.s = value
658
659
Edward Lesmes3d993812018-04-02 12:52:49 -0400660def _ShiftLinesInTokens(tokens, delta, start):
661 new_tokens = {}
662 for token in tokens.values():
663 if token[2][0] >= start:
664 token[2] = token[2][0] + delta, token[2][1]
665 token[3] = token[3][0] + delta, token[3][1]
666 new_tokens[token[2]] = token
667 return new_tokens
668
669
670def AddVar(gclient_dict, var_name, value):
671 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
672 raise ValueError(
673 "Can't use SetVar for the given gclient dict. It contains no "
674 "formatting information.")
675
676 if 'vars' not in gclient_dict:
677 raise KeyError("vars dict is not defined.")
678
679 if var_name in gclient_dict['vars']:
680 raise ValueError(
681 "%s has already been declared in the vars dict. Consider using SetVar "
682 "instead." % var_name)
683
684 if not gclient_dict['vars']:
685 raise ValueError('vars dict is empty. This is not yet supported.')
686
Edward Lesmes8d626572018-04-05 17:53:10 -0400687 # We will attempt to add the var right after 'vars = {'.
688 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400689 if node is None:
690 raise ValueError(
691 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400692 line = node.lineno + 1
693
694 # We will try to match the new var's indentation to the next variable.
695 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400696
697 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000698 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400699 var_ast = ast.parse(var_content).body[0].value
700
701 # Set the ast nodes for the key and value.
702 vars_node = gclient_dict.GetNode('vars')
703
704 var_name_node = var_ast.keys[0]
705 var_name_node.lineno += line - 2
706 vars_node.keys.insert(0, var_name_node)
707
708 value_node = var_ast.values[0]
709 value_node.lineno += line - 2
710 vars_node.values.insert(0, value_node)
711
712 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000713 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400714 var_tokens = {
715 token[2]: list(token)
716 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000717 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400718 }
719
720 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
721 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
722
723
Edward Lesmes6f64a052018-03-20 17:35:49 -0400724def SetVar(gclient_dict, var_name, value):
725 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
726 raise ValueError(
727 "Can't use SetVar for the given gclient dict. It contains no "
728 "formatting information.")
729 tokens = gclient_dict.tokens
730
Edward Lesmes3d993812018-04-02 12:52:49 -0400731 if 'vars' not in gclient_dict:
732 raise KeyError("vars dict is not defined.")
733
734 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400735 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400736 "%s has not been declared in the vars dict. Consider using AddVar "
737 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400738
739 node = gclient_dict['vars'].GetNode(var_name)
740 if node is None:
741 raise ValueError(
742 "The vars entry for %s has no formatting information." % var_name)
743
744 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400745 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400746
747
Edward Lemura1e4d482018-12-17 19:01:03 +0000748def _GetVarName(node):
749 if isinstance(node, ast.Call):
750 return node.args[0].s
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000751
752 if node.s.endswith('}'):
Edward Lemura1e4d482018-12-17 19:01:03 +0000753 last_brace = node.s.rfind('{')
754 return node.s[last_brace+1:-1]
755 return None
756
757
Edward Lesmes6f64a052018-03-20 17:35:49 -0400758def SetCIPD(gclient_dict, dep_name, package_name, new_version):
759 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
760 raise ValueError(
761 "Can't use SetCIPD for the given gclient dict. It contains no "
762 "formatting information.")
763 tokens = gclient_dict.tokens
764
765 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400766 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400767 "Could not find any dependency called %s." % dep_name)
768
769 # Find the package with the given name
770 packages = [
771 package
772 for package in gclient_dict['deps'][dep_name]['packages']
773 if package['package'] == package_name
774 ]
775 if len(packages) != 1:
776 raise ValueError(
777 "There must be exactly one package with the given name (%s), "
778 "%s were found." % (package_name, len(packages)))
779
780 # TODO(ehmaldonado): Support Var in package's version.
781 node = packages[0].GetNode('version')
782 if node is None:
783 raise ValueError(
784 "The deps entry for %s:%s has no formatting information." %
785 (dep_name, package_name))
786
Edward Lemura1e4d482018-12-17 19:01:03 +0000787 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
788 raise ValueError(
789 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000790 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000791
792 var_name = _GetVarName(node)
793 if var_name is not None:
794 SetVar(gclient_dict, var_name, new_version)
795 else:
796 _UpdateAstString(tokens, node, new_version)
797 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400798
799
Edward Lesmes9f531292018-03-20 21:27:15 -0400800def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400801 def _UpdateRevision(dep_dict, dep_key, new_revision):
802 dep_node = dep_dict.GetNode(dep_key)
803 if dep_node is None:
804 raise ValueError(
805 "The deps entry for %s has no formatting information." % dep_name)
806
807 node = dep_node
808 if isinstance(node, ast.BinOp):
809 node = node.right
810
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000811 if isinstance(node, ast.Str):
812 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
813 if token != node.s:
814 raise ValueError(
815 'Can\'t update value for %s. Multiline strings and implicitly '
816 'concatenated strings are not supported.\n'
817 'Consider reformatting the DEPS file.' % dep_key)
Edward Lemur3c117942020-03-12 17:21:12 +0000818
819
Edward Lesmes62af4e42018-03-30 18:15:44 -0400820 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
821 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000822 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000823 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400824
825 var_name = _GetVarName(node)
826 if var_name is not None:
827 SetVar(gclient_dict, var_name, new_revision)
828 else:
829 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400830 # '@' is part of the last string, which we want to modify. Discard
831 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400832 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400833 elif '@' not in dep_dict[dep_key]:
834 # '@' is not part of the URL at all. This mean the dependency is
835 # unpinned and we should pin it.
836 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400837 _UpdateAstString(tokens, node, new_revision)
838 dep_dict.SetNode(dep_key, new_revision, node)
839
Edward Lesmes6f64a052018-03-20 17:35:49 -0400840 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
841 raise ValueError(
842 "Can't use SetRevision for the given gclient dict. It contains no "
843 "formatting information.")
844 tokens = gclient_dict.tokens
845
846 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400847 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400848 "Could not find any dependency called %s." % dep_name)
849
Edward Lesmes6f64a052018-03-20 17:35:49 -0400850 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400851 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400852 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400853 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400854
855
856def GetVar(gclient_dict, var_name):
857 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
858 raise KeyError(
859 "Could not find any variable called %s." % var_name)
860
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000861 val = gclient_dict['vars'][var_name]
862 if isinstance(val, ConstantString):
863 return val.value
864 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400865
866
867def GetCIPD(gclient_dict, dep_name, package_name):
868 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
869 raise KeyError(
870 "Could not find any dependency called %s." % dep_name)
871
872 # Find the package with the given name
873 packages = [
874 package
875 for package in gclient_dict['deps'][dep_name]['packages']
876 if package['package'] == package_name
877 ]
878 if len(packages) != 1:
879 raise ValueError(
880 "There must be exactly one package with the given name (%s), "
881 "%s were found." % (package_name, len(packages)))
882
Edward Lemura92b9612018-07-03 02:34:32 +0000883 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400884
885
886def GetRevision(gclient_dict, dep_name):
887 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
888 raise KeyError(
889 "Could not find any dependency called %s." % dep_name)
890
891 dep = gclient_dict['deps'][dep_name]
892 if dep is None:
893 return None
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000894
895 if isinstance(dep, basestring):
Edward Lesmes411041f2018-04-05 20:12:55 -0400896 _, _, revision = dep.partition('@')
897 return revision or None
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000898
899 if isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400900 _, _, revision = dep['url'].partition('@')
901 return revision or None
Aravind Vasudevan22bf6052022-01-24 21:11:19 +0000902
903 raise ValueError(
904 '%s is not a valid git dependency.' % dep_name)