blob: 5571946c47eb55ab98c0f83637b5193e6801a5aa [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 Vasudevanc5f0cbb2022-01-24 23:56:57 +000041
42 return self.value == other
Dirk Prankefdd2cd62020-06-30 23:30:47 +000043
44 def __hash__(self):
Bruce Dawson03af44a2022-12-27 19:37:58 +000045 return self.value.__hash__()
Dirk Prankefdd2cd62020-06-30 23:30:47 +000046
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
Yuki Shiinoa0422642022-08-04 08:14:15 +0000205 # Optionally discards rules from parent directories, similar to
206 # "noparent" in OWNERS files. For example, if
207 # //base/allocator/partition_allocator has "noparent = True" then it
208 # will not inherit rules from //base/DEPS and //base/allocator/DEPS,
209 # forcing each //base/allocator/partition_allocator/{foo,bar,...} to
210 # declare all its dependencies.
211 schema.Optional('noparent'): bool,
212
Raul Tambreb946b232019-03-26 14:48:46 +0000213 # Hooks executed before processing DEPS. See 'hooks' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000214 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200215
Raul Tambreb946b232019-03-26 14:48:46 +0000216 # Recursion limit for nested DEPS.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000217 schema.Optional('recursion'): int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200218
Ayu Ishii09858612020-06-26 18:00:52 +0000219 # Allowlists deps for which recursion should be enabled.
Raul Tambreb946b232019-03-26 14:48:46 +0000220 schema.Optional('recursedeps'): [
Aaron Gableac9b0f32019-04-18 17:38:37 +0000221 schema.Optional(schema.Or(
222 basestring,
223 (basestring, basestring),
224 [basestring, basestring]
225 )),
Raul Tambreb946b232019-03-26 14:48:46 +0000226 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200227
Ayu Ishii09858612020-06-26 18:00:52 +0000228 # Blocklists directories for checking 'include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000229 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200230
Raul Tambreb946b232019-03-26 14:48:46 +0000231 # Mapping from paths to include rules specific for that path.
232 # See 'include_rules' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000233 schema.Optional('specific_include_rules'): _NodeDictSchema({
234 schema.Optional(basestring): [basestring]
235 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200236
Raul Tambreb946b232019-03-26 14:48:46 +0000237 # List of additional OS names to consider when selecting dependencies
238 # from deps_os.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000239 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200240
Raul Tambreb946b232019-03-26 14:48:46 +0000241 # For recursed-upon sub-dependencies, check out their own dependencies
242 # relative to the parent's path, rather than relative to the .gclient
243 # file.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000244 schema.Optional('use_relative_paths'): bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200245
Michael Spang0e99b9b2020-08-12 13:34:48 +0000246 # For recursed-upon sub-dependencies, run their hooks relative to the
247 # parent's path instead of relative to the .gclient file.
248 schema.Optional('use_relative_hooks'): bool,
249
Raul Tambreb946b232019-03-26 14:48:46 +0000250 # Variables that can be referenced using Var() - see 'deps'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000251 schema.Optional('vars'): _NodeDictSchema({
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000252 schema.Optional(basestring): schema.Or(ConstantString,
253 basestring,
254 bool),
Aaron Gableac9b0f32019-04-18 17:38:37 +0000255 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000256 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200257
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200258
Edward Lemure05f18d2018-06-08 17:36:53 +0000259def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200260 """Safely evaluates a single expression. Returns the result."""
261 _allowed_names = {'None': None, 'True': True, 'False': False}
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000262 if isinstance(node_or_string, ConstantString):
263 return node_or_string.value
Aaron Gableac9b0f32019-04-18 17:38:37 +0000264 if isinstance(node_or_string, basestring):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200265 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
266 if isinstance(node_or_string, ast.Expression):
267 node_or_string = node_or_string.body
268 def _convert(node):
269 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000270 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000271 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400272 try:
273 return node.s.format(**vars_dict)
274 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000275 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400276 '%s was used as a variable, but was not declared in the vars dict '
277 '(file %r, line %s)' % (
Edward Lemurba1b1f72019-07-27 00:41:59 +0000278 e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200279 elif isinstance(node, ast.Num):
280 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200281 elif isinstance(node, ast.Tuple):
282 return tuple(map(_convert, node.elts))
283 elif isinstance(node, ast.List):
284 return list(map(_convert, node.elts))
285 elif isinstance(node, ast.Dict):
Edward Lemurc00ac8d2020-03-04 23:37:57 +0000286 node_dict = _NodeDict()
287 for key_node, value_node in zip(node.keys, node.values):
288 key = _convert(key_node)
289 if key in node_dict:
290 raise ValueError(
291 'duplicate key in dictionary: %s (file %r, line %s)' % (
292 key, filename, getattr(key_node, 'lineno', '<unknown>')))
293 node_dict.SetNode(key, _convert(value_node), value_node)
294 return node_dict
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200295 elif isinstance(node, ast.Name):
296 if node.id not in _allowed_names:
297 raise ValueError(
298 'invalid name %r (file %r, line %s)' % (
299 node.id, filename, getattr(node, 'lineno', '<unknown>')))
300 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000301 elif not sys.version_info[:2] < (3, 4) and isinstance(
302 node, ast.NameConstant): # Since Python 3.4
303 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200304 elif isinstance(node, ast.Call):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000305 if (not isinstance(node.func, ast.Name) or
306 (node.func.id not in ('Str', 'Var'))):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200307 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000308 'Str and Var are the only allowed functions (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200309 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000310 if node.keywords or getattr(node, 'starargs', None) or getattr(
311 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200312 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000313 '%s takes exactly one argument (file %r, line %s)' % (
314 node.func.id, filename, getattr(node, 'lineno', '<unknown>')))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000315
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000316 if node.func.id == 'Str':
317 if isinstance(node.args[0], ast.Str):
318 return ConstantString(node.args[0].s)
319 raise ValueError('Passed a non-string to Str() (file %r, line%s)' % (
320 filename, getattr(node, 'lineno', '<unknown>')))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000321
322 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000323 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400324 raise ValueError(
325 'Var\'s argument must be a variable name (file %r, line %s)' % (
326 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400327 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000328 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400329 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000330 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400331 '%s was used as a variable, but was not declared in the vars dict '
332 '(file %r, line %s)' % (
333 arg, filename, getattr(node, 'lineno', '<unknown>')))
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000334 val = vars_dict[arg]
335 if isinstance(val, ConstantString):
336 val = val.value
337 return val
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200338 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
339 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200340 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
341 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200342 else:
343 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200344 'unexpected AST node: %s %s (file %r, line %s)' % (
345 node, ast.dump(node), filename,
346 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200347 return _convert(node_or_string)
348
349
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000350def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400351 """Safely execs a set of assignments."""
352 def _validate_statement(node, local_scope):
353 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200354 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200355 'unexpected AST node: %s %s (file %r, line %s)' % (
356 node, ast.dump(node), filename,
357 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200358
Edward Lesmes6c24d372018-03-28 12:52:29 -0400359 if len(node.targets) != 1:
360 raise ValueError(
361 'invalid assignment: use exactly one target (file %r, line %s)' % (
362 filename, getattr(node, 'lineno', '<unknown>')))
363
364 target = node.targets[0]
365 if not isinstance(target, ast.Name):
366 raise ValueError(
367 'invalid assignment: target should be a name (file %r, line %s)' % (
368 filename, getattr(node, 'lineno', '<unknown>')))
369 if target.id in local_scope:
370 raise ValueError(
371 'invalid assignment: overrides var %r (file %r, line %s)' % (
372 target.id, filename, getattr(node, 'lineno', '<unknown>')))
373
374 node_or_string = ast.parse(content, filename=filename, mode='exec')
375 if isinstance(node_or_string, ast.Expression):
376 node_or_string = node_or_string.body
377
378 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200379 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200380 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200381 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200382 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200383 filename,
384 getattr(node_or_string, 'lineno', '<unknown>')))
385
Edward Lesmes6c24d372018-03-28 12:52:29 -0400386 statements = {}
387 for statement in node_or_string.body:
388 _validate_statement(statement, statements)
389 statements[statement.targets[0].id] = statement.value
390
Raul Tambreb946b232019-03-26 14:48:46 +0000391 # The tokenized representation needs to end with a newline token, otherwise
392 # untokenization will trigger an assert later on.
393 # In Python 2.7 on Windows we need to ensure the input ends with a newline
394 # for a newline token to be generated.
395 # In other cases a newline token is always generated during tokenization so
396 # this has no effect.
397 # TODO: Remove this workaround after migrating to Python 3.
398 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400399 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000400 token[2]: list(token) for token in tokenize.generate_tokens(
401 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400402 }
Raul Tambreb946b232019-03-26 14:48:46 +0000403
Edward Lesmes6c24d372018-03-28 12:52:29 -0400404 local_scope = _NodeDict({}, tokens)
405
406 # Process vars first, so we can expand variables in the rest of the DEPS file.
407 vars_dict = {}
408 if 'vars' in statements:
409 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000410 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400411 local_scope.SetNode('vars', value, vars_statement)
412 # Update the parsed vars with the overrides, but only if they are already
413 # present (overrides do not introduce new variables).
414 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000415
416 if builtin_vars:
417 vars_dict.update(builtin_vars)
418
419 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000420 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400421
Raul Tambreb946b232019-03-26 14:48:46 +0000422 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000423 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400424 local_scope.SetNode(name, value, node)
425
Edward Lemur67cabcd2020-03-03 19:31:15 +0000426 try:
427 return _GCLIENT_SCHEMA.validate(local_scope)
428 except schema.SchemaError as e:
429 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400430
431
Edward Lemur16f4bad2018-05-16 16:53:49 -0400432def _StandardizeDeps(deps_dict, vars_dict):
433 """"Standardizes the deps_dict.
434
435 For each dependency:
436 - Expands the variable in the dependency name.
437 - Ensures the dependency is a dictionary.
438 - Set's the 'dep_type' to be 'git' by default.
439 """
440 new_deps_dict = {}
441 for dep_name, dep_info in deps_dict.items():
442 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000443 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400444 dep_info = {'url': dep_info}
445 dep_info.setdefault('dep_type', 'git')
446 new_deps_dict[dep_name] = dep_info
447 return new_deps_dict
448
449
450def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
451 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
452
453 The dependencies in os_deps_dict are transformed into conditional dependencies
454 using |'checkout_' + os_name|.
455 If the dependency is already present, the URL and revision must coincide.
456 """
457 for dep_name, dep_info in os_deps_dict.items():
458 # Make this condition very visible, so it's not a silent failure.
459 # It's unclear how to support None override in deps_os.
460 if dep_info['url'] is None:
461 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
462 continue
463
464 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
465 UpdateCondition(dep_info, 'and', os_condition)
466
467 if dep_name in deps_dict:
468 if deps_dict[dep_name]['url'] != dep_info['url']:
469 raise gclient_utils.Error(
470 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
471 'entry (%r).' % (
472 os_name, dep_name, dep_info, deps_dict[dep_name]))
473
474 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
475
476 deps_dict[dep_name] = dep_info
477
478
479def UpdateCondition(info_dict, op, new_condition):
480 """Updates info_dict's condition with |new_condition|.
481
482 An absent value is treated as implicitly True.
483 """
484 curr_condition = info_dict.get('condition')
485 # Easy case: Both are present.
486 if curr_condition and new_condition:
487 info_dict['condition'] = '(%s) %s (%s)' % (
488 curr_condition, op, new_condition)
489 # If |op| == 'and', and at least one condition is present, then use it.
490 elif op == 'and' and (curr_condition or new_condition):
491 info_dict['condition'] = curr_condition or new_condition
492 # Otherwise, no condition should be set
493 elif curr_condition:
494 del info_dict['condition']
495
496
Edward Lemur67cabcd2020-03-03 19:31:15 +0000497def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400498 """Parses DEPS strings.
499
500 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000501 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400502 variable expansion.
503
504 Args:
505 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400506 filename: str. The name of the DEPS file, or a string describing the source
507 of the content, e.g. '<string>', '<unknown>'.
508 vars_override: dict, optional. A dictionary with overrides for the variables
509 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000510 builtin_vars: dict, optional. A dictionary with variables that are provided
511 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400512
513 Returns:
514 A Python dict with the parsed contents of the DEPS file, as specified by the
515 schema above.
516 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000517 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400518
519 vars_dict = result.get('vars', {})
520 if 'deps' in result:
521 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
522
523 if 'deps_os' in result:
524 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000525 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400526 os_deps = _StandardizeDeps(os_deps, vars_dict)
527 _MergeDepsOs(deps, os_deps, os_name)
528 del result['deps_os']
529
530 if 'hooks_os' in result:
531 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000532 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400533 for hook in os_hooks:
534 UpdateCondition(hook, 'and', 'checkout_' + os_name)
535 hooks.extend(os_hooks)
536 del result['hooks_os']
537
538 return result
539
540
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200541def EvaluateCondition(condition, variables, referenced_variables=None):
542 """Safely evaluates a boolean condition. Returns the result."""
543 if not referenced_variables:
544 referenced_variables = set()
545 _allowed_names = {'None': None, 'True': True, 'False': False}
546 main_node = ast.parse(condition, mode='eval')
547 if isinstance(main_node, ast.Expression):
548 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000549 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200550 if isinstance(node, ast.Str):
551 return node.s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000552
553 if isinstance(node, ast.Tuple) and allow_tuple:
Ben Pastenea541b282019-05-24 00:25:12 +0000554 return tuple(map(_convert, node.elts))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000555
556 if isinstance(node, ast.Name):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200557 if node.id in referenced_variables:
558 raise ValueError(
559 'invalid cyclic reference to %r (inside %r)' % (
560 node.id, condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000561
562 if node.id in _allowed_names:
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200563 return _allowed_names[node.id]
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000564
565 if node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200566 value = variables[node.id]
567
568 # Allow using "native" types, without wrapping everything in strings.
569 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000570 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200571 return value
572
573 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200574 return EvaluateCondition(
575 variables[node.id],
576 variables,
577 referenced_variables.union([node.id]))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000578
579 # Implicitly convert unrecognized names to strings.
580 # If we want to change this, we'll need to explicitly distinguish
581 # between arguments for GN to be passed verbatim, and ones to
582 # be evaluated.
583 return node.id
584
585 if not sys.version_info[:2] < (3, 4) and isinstance(
Edward Lemurba1b1f72019-07-27 00:41:59 +0000586 node, ast.NameConstant): # Since Python 3.4
587 return node.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000588
589 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000590 bool_values = []
591 for value in node.values:
592 bool_values.append(_convert(value))
593 if not isinstance(bool_values[-1], bool):
594 raise ValueError(
595 'invalid "or" operand %r (inside %r)' % (
596 bool_values[-1], condition))
597 return any(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000598
599 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000600 bool_values = []
601 for value in node.values:
602 bool_values.append(_convert(value))
603 if not isinstance(bool_values[-1], bool):
604 raise ValueError(
605 'invalid "and" operand %r (inside %r)' % (
606 bool_values[-1], condition))
607 return all(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000608
609 if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200610 value = _convert(node.operand)
611 if not isinstance(value, bool):
612 raise ValueError(
613 'invalid "not" operand %r (inside %r)' % (value, condition))
614 return not value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000615
616 if isinstance(node, ast.Compare):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200617 if len(node.ops) != 1:
618 raise ValueError(
619 'invalid compare: exactly 1 operator required (inside %r)' % (
620 condition))
621 if len(node.comparators) != 1:
622 raise ValueError(
623 'invalid compare: exactly 1 comparator required (inside %r)' % (
624 condition))
625
626 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000627 right = _convert(
628 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200629
630 if isinstance(node.ops[0], ast.Eq):
631 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700632 if isinstance(node.ops[0], ast.NotEq):
633 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000634 if isinstance(node.ops[0], ast.In):
635 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200636
637 raise ValueError(
638 'unexpected operator: %s %s (inside %r)' % (
639 node.ops[0], ast.dump(node), condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000640
641 raise ValueError(
642 'unexpected AST node: %s %s (inside %r)' % (
643 node, ast.dump(node), condition))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200644 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400645
646
647def RenderDEPSFile(gclient_dict):
648 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000649 # The last token is a newline, which we ensure in Exec() for compatibility.
650 # However tests pass in inputs not ending with a newline and expect the same
651 # back, so for backwards compatibility need to remove that newline character.
652 # TODO: Fix tests to expect the newline
653 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400654
655
656def _UpdateAstString(tokens, node, value):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000657 if isinstance(node, ast.Call):
658 node = node.args[0]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400659 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000660 quote_char = ''
661 if isinstance(node, ast.Str):
662 quote_char = tokens[position][1][0]
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000663 value = value.encode('unicode_escape').decode('utf-8')
Edward Lesmes62af4e42018-03-30 18:15:44 -0400664 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400665 node.s = value
666
667
Edward Lesmes3d993812018-04-02 12:52:49 -0400668def _ShiftLinesInTokens(tokens, delta, start):
669 new_tokens = {}
670 for token in tokens.values():
671 if token[2][0] >= start:
672 token[2] = token[2][0] + delta, token[2][1]
673 token[3] = token[3][0] + delta, token[3][1]
674 new_tokens[token[2]] = token
675 return new_tokens
676
677
678def AddVar(gclient_dict, var_name, value):
679 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
680 raise ValueError(
681 "Can't use SetVar for the given gclient dict. It contains no "
682 "formatting information.")
683
684 if 'vars' not in gclient_dict:
685 raise KeyError("vars dict is not defined.")
686
687 if var_name in gclient_dict['vars']:
688 raise ValueError(
689 "%s has already been declared in the vars dict. Consider using SetVar "
690 "instead." % var_name)
691
692 if not gclient_dict['vars']:
693 raise ValueError('vars dict is empty. This is not yet supported.')
694
Edward Lesmes8d626572018-04-05 17:53:10 -0400695 # We will attempt to add the var right after 'vars = {'.
696 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400697 if node is None:
698 raise ValueError(
699 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400700 line = node.lineno + 1
701
702 # We will try to match the new var's indentation to the next variable.
703 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400704
705 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000706 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400707 var_ast = ast.parse(var_content).body[0].value
708
709 # Set the ast nodes for the key and value.
710 vars_node = gclient_dict.GetNode('vars')
711
712 var_name_node = var_ast.keys[0]
713 var_name_node.lineno += line - 2
714 vars_node.keys.insert(0, var_name_node)
715
716 value_node = var_ast.values[0]
717 value_node.lineno += line - 2
718 vars_node.values.insert(0, value_node)
719
720 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000721 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400722 var_tokens = {
723 token[2]: list(token)
724 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000725 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400726 }
727
728 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
729 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
730
731
Edward Lesmes6f64a052018-03-20 17:35:49 -0400732def SetVar(gclient_dict, var_name, value):
733 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
734 raise ValueError(
735 "Can't use SetVar for the given gclient dict. It contains no "
736 "formatting information.")
737 tokens = gclient_dict.tokens
738
Edward Lesmes3d993812018-04-02 12:52:49 -0400739 if 'vars' not in gclient_dict:
740 raise KeyError("vars dict is not defined.")
741
742 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400743 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400744 "%s has not been declared in the vars dict. Consider using AddVar "
745 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400746
747 node = gclient_dict['vars'].GetNode(var_name)
748 if node is None:
749 raise ValueError(
750 "The vars entry for %s has no formatting information." % var_name)
751
752 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400753 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400754
755
Edward Lemura1e4d482018-12-17 19:01:03 +0000756def _GetVarName(node):
757 if isinstance(node, ast.Call):
758 return node.args[0].s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000759
760 if node.s.endswith('}'):
Edward Lemura1e4d482018-12-17 19:01:03 +0000761 last_brace = node.s.rfind('{')
762 return node.s[last_brace+1:-1]
763 return None
764
765
Edward Lesmes6f64a052018-03-20 17:35:49 -0400766def SetCIPD(gclient_dict, dep_name, package_name, new_version):
767 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
768 raise ValueError(
769 "Can't use SetCIPD for the given gclient dict. It contains no "
770 "formatting information.")
771 tokens = gclient_dict.tokens
772
773 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400774 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400775 "Could not find any dependency called %s." % dep_name)
776
777 # Find the package with the given name
778 packages = [
779 package
780 for package in gclient_dict['deps'][dep_name]['packages']
781 if package['package'] == package_name
782 ]
783 if len(packages) != 1:
784 raise ValueError(
785 "There must be exactly one package with the given name (%s), "
786 "%s were found." % (package_name, len(packages)))
787
788 # TODO(ehmaldonado): Support Var in package's version.
789 node = packages[0].GetNode('version')
790 if node is None:
791 raise ValueError(
792 "The deps entry for %s:%s has no formatting information." %
793 (dep_name, package_name))
794
Edward Lemura1e4d482018-12-17 19:01:03 +0000795 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
796 raise ValueError(
797 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000798 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000799
800 var_name = _GetVarName(node)
801 if var_name is not None:
802 SetVar(gclient_dict, var_name, new_version)
803 else:
804 _UpdateAstString(tokens, node, new_version)
805 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400806
807
Edward Lesmes9f531292018-03-20 21:27:15 -0400808def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400809 def _UpdateRevision(dep_dict, dep_key, new_revision):
810 dep_node = dep_dict.GetNode(dep_key)
811 if dep_node is None:
812 raise ValueError(
813 "The deps entry for %s has no formatting information." % dep_name)
814
815 node = dep_node
816 if isinstance(node, ast.BinOp):
817 node = node.right
818
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000819 if isinstance(node, ast.Str):
820 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
821 if token != node.s:
822 raise ValueError(
823 'Can\'t update value for %s. Multiline strings and implicitly '
824 'concatenated strings are not supported.\n'
825 'Consider reformatting the DEPS file.' % dep_key)
Edward Lemur3c117942020-03-12 17:21:12 +0000826
827
Edward Lesmes62af4e42018-03-30 18:15:44 -0400828 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
829 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000830 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000831 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400832
833 var_name = _GetVarName(node)
834 if var_name is not None:
835 SetVar(gclient_dict, var_name, new_revision)
836 else:
837 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400838 # '@' is part of the last string, which we want to modify. Discard
839 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400840 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400841 elif '@' not in dep_dict[dep_key]:
842 # '@' is not part of the URL at all. This mean the dependency is
843 # unpinned and we should pin it.
844 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400845 _UpdateAstString(tokens, node, new_revision)
846 dep_dict.SetNode(dep_key, new_revision, node)
847
Edward Lesmes6f64a052018-03-20 17:35:49 -0400848 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
849 raise ValueError(
850 "Can't use SetRevision for the given gclient dict. It contains no "
851 "formatting information.")
852 tokens = gclient_dict.tokens
853
854 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400855 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400856 "Could not find any dependency called %s." % dep_name)
857
Edward Lesmes6f64a052018-03-20 17:35:49 -0400858 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400859 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400860 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400861 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400862
863
864def GetVar(gclient_dict, var_name):
865 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
866 raise KeyError(
867 "Could not find any variable called %s." % var_name)
868
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000869 val = gclient_dict['vars'][var_name]
870 if isinstance(val, ConstantString):
871 return val.value
872 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400873
874
875def GetCIPD(gclient_dict, dep_name, package_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 # Find the package with the given name
881 packages = [
882 package
883 for package in gclient_dict['deps'][dep_name]['packages']
884 if package['package'] == package_name
885 ]
886 if len(packages) != 1:
887 raise ValueError(
888 "There must be exactly one package with the given name (%s), "
889 "%s were found." % (package_name, len(packages)))
890
Edward Lemura92b9612018-07-03 02:34:32 +0000891 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400892
893
894def GetRevision(gclient_dict, dep_name):
895 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Bruce Dawson03af44a2022-12-27 19:37:58 +0000896 suggestions = []
897 if 'deps' in gclient_dict:
898 for key in gclient_dict['deps']:
899 if dep_name in key:
900 suggestions.append(key)
901 if suggestions:
902 raise KeyError(
903 "Could not find any dependency called %s. Did you mean %s" %
904 (dep_name, ' or '.join(suggestions)))
Edward Lesmes411041f2018-04-05 20:12:55 -0400905 raise KeyError(
906 "Could not find any dependency called %s." % dep_name)
907
908 dep = gclient_dict['deps'][dep_name]
909 if dep is None:
910 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000911
912 if isinstance(dep, basestring):
Edward Lesmes411041f2018-04-05 20:12:55 -0400913 _, _, revision = dep.partition('@')
914 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000915
916 if isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400917 _, _, revision = dep['url'].partition('@')
918 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000919
920 raise ValueError(
921 '%s is not a valid git dependency.' % dep_name)