blob: d01b52aa1a3cb50660a8a758654d7c83a9e3adde [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
Gavin Mak65c49b12023-08-24 18:06:42 +00007from io import StringIO
Edward Lemur16f4bad2018-05-16 16:53:49 -04008import logging
Raul Tambreb946b232019-03-26 14:48:46 +00009import sys
Edward Lesmes6f64a052018-03-20 17:35:49 -040010import tokenize
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +020011
Edward Lemur16f4bad2018-05-16 16:53:49 -040012import gclient_utils
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020013from third_party import schema
Aaron Gableac9b0f32019-04-18 17:38:37 +000014
Mike Frysinger124bb8e2023-09-06 05:48:55 +000015# TODO: Should fix these warnings.
16# pylint: disable=line-too-long
Aaron Gableac9b0f32019-04-18 17:38:37 +000017
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +000018# git_dependencies migration states. Used within the DEPS file to indicate
19# the current migration state.
20DEPS = 'DEPS'
21SYNC = 'SYNC'
22SUBMODULES = 'SUBMODULES'
23
24
Dirk Prankefdd2cd62020-06-30 23:30:47 +000025class ConstantString(object):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000026 def __init__(self, value):
27 self.value = value
Dirk Prankefdd2cd62020-06-30 23:30:47 +000028
Mike Frysinger124bb8e2023-09-06 05:48:55 +000029 def __format__(self, format_spec):
30 del format_spec
31 return self.value
Dirk Prankefdd2cd62020-06-30 23:30:47 +000032
Mike Frysinger124bb8e2023-09-06 05:48:55 +000033 def __repr__(self):
34 return "Str('" + self.value + "')"
Dirk Prankefdd2cd62020-06-30 23:30:47 +000035
Mike Frysinger124bb8e2023-09-06 05:48:55 +000036 def __eq__(self, other):
37 if isinstance(other, ConstantString):
38 return self.value == other.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +000039
Mike Frysinger124bb8e2023-09-06 05:48:55 +000040 return self.value == other
Dirk Prankefdd2cd62020-06-30 23:30:47 +000041
Mike Frysinger124bb8e2023-09-06 05:48:55 +000042 def __hash__(self):
43 return self.value.__hash__()
Dirk Prankefdd2cd62020-06-30 23:30:47 +000044
45
Gavin Mak65c49b12023-08-24 18:06:42 +000046class _NodeDict(collections.abc.MutableMapping):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000047 """Dict-like type that also stores information on AST nodes and tokens."""
48 def __init__(self, data=None, tokens=None):
49 self.data = collections.OrderedDict(data or [])
50 self.tokens = tokens
Edward Lesmes6f64a052018-03-20 17:35:49 -040051
Mike Frysinger124bb8e2023-09-06 05:48:55 +000052 def __str__(self):
53 return str({k: v[0] for k, v in self.data.items()})
Edward Lesmes6f64a052018-03-20 17:35:49 -040054
Mike Frysinger124bb8e2023-09-06 05:48:55 +000055 def __repr__(self):
56 return self.__str__()
Edward Lemura1e4d482018-12-17 19:01:03 +000057
Mike Frysinger124bb8e2023-09-06 05:48:55 +000058 def __getitem__(self, key):
59 return self.data[key][0]
Edward Lesmes6f64a052018-03-20 17:35:49 -040060
Mike Frysinger124bb8e2023-09-06 05:48:55 +000061 def __setitem__(self, key, value):
62 self.data[key] = (value, None)
Edward Lesmes6f64a052018-03-20 17:35:49 -040063
Mike Frysinger124bb8e2023-09-06 05:48:55 +000064 def __delitem__(self, key):
65 del self.data[key]
Edward Lesmes6f64a052018-03-20 17:35:49 -040066
Mike Frysinger124bb8e2023-09-06 05:48:55 +000067 def __iter__(self):
68 return iter(self.data)
Edward Lesmes6f64a052018-03-20 17:35:49 -040069
Mike Frysinger124bb8e2023-09-06 05:48:55 +000070 def __len__(self):
71 return len(self.data)
Edward Lesmes6f64a052018-03-20 17:35:49 -040072
Mike Frysinger124bb8e2023-09-06 05:48:55 +000073 def MoveTokens(self, origin, delta):
74 if self.tokens:
75 new_tokens = {}
76 for pos, token in self.tokens.items():
77 if pos[0] >= origin:
78 pos = (pos[0] + delta, pos[1])
79 token = token[:2] + (pos, ) + token[3:]
80 new_tokens[pos] = token
Edward Lesmes3d993812018-04-02 12:52:49 -040081
Mike Frysinger124bb8e2023-09-06 05:48:55 +000082 for value, node in self.data.values():
83 if node.lineno >= origin:
84 node.lineno += delta
85 if isinstance(value, _NodeDict):
86 value.MoveTokens(origin, delta)
Edward Lesmes3d993812018-04-02 12:52:49 -040087
Mike Frysinger124bb8e2023-09-06 05:48:55 +000088 def GetNode(self, key):
89 return self.data[key][1]
Edward Lesmes6f64a052018-03-20 17:35:49 -040090
Mike Frysinger124bb8e2023-09-06 05:48:55 +000091 def SetNode(self, key, value, node):
92 self.data[key] = (value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -040093
94
95def _NodeDictSchema(dict_schema):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000096 """Validate dict_schema after converting _NodeDict to a regular dict."""
97 def validate(d):
98 schema.Schema(dict_schema).validate(dict(d))
99 return True
100
101 return validate
Edward Lesmes6f64a052018-03-20 17:35:49 -0400102
103
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200104# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400105_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Gavin Mak65c49b12023-08-24 18:06:42 +0000106 schema.Optional(str):
107 schema.Or(
108 None,
109 str,
110 _NodeDictSchema({
111 # Repo and revision to check out under the path
112 # (same as if no dict was used).
113 'url':
114 schema.Or(None, str),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200115
Gavin Mak65c49b12023-08-24 18:06:42 +0000116 # Optional condition string. The dep will only be processed
117 # if the condition evaluates to True.
118 schema.Optional('condition'):
119 str,
120 schema.Optional('dep_type', default='git'):
121 str,
122 }),
123 # CIPD package.
124 _NodeDictSchema({
125 'packages': [_NodeDictSchema({
126 'package': str,
127 'version': str,
128 })],
129 schema.Optional('condition'):
130 str,
131 schema.Optional('dep_type', default='cipd'):
132 str,
133 }),
134 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400135})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200136
Raul Tambreb946b232019-03-26 14:48:46 +0000137_GCLIENT_HOOKS_SCHEMA = [
138 _NodeDictSchema({
139 # Hook action: list of command-line arguments to invoke.
Gavin Mak65c49b12023-08-24 18:06:42 +0000140 'action': [schema.Or(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200141
Raul Tambreb946b232019-03-26 14:48:46 +0000142 # Name of the hook. Doesn't affect operation.
Gavin Mak65c49b12023-08-24 18:06:42 +0000143 schema.Optional('name'):
144 str,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200145
Raul Tambreb946b232019-03-26 14:48:46 +0000146 # Hook pattern (regex). Originally intended to limit some hooks to run
147 # only when files matching the pattern have changed. In practice, with
148 # git, gclient runs all the hooks regardless of this field.
Gavin Mak65c49b12023-08-24 18:06:42 +0000149 schema.Optional('pattern'):
150 str,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200151
Raul Tambreb946b232019-03-26 14:48:46 +0000152 # Working directory where to execute the hook.
Gavin Mak65c49b12023-08-24 18:06:42 +0000153 schema.Optional('cwd'):
154 str,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200155
Raul Tambreb946b232019-03-26 14:48:46 +0000156 # Optional condition string. The hook will only be run
157 # if the condition evaluates to True.
Gavin Mak65c49b12023-08-24 18:06:42 +0000158 schema.Optional('condition'):
159 str,
Raul Tambreb946b232019-03-26 14:48:46 +0000160 })
161]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200162
Raul Tambreb946b232019-03-26 14:48:46 +0000163_GCLIENT_SCHEMA = schema.Schema(
164 _NodeDictSchema({
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000165 # Current state of the git submodule migration.
166 # git_dependencies = [DEPS (default) | SUBMODULES | SYNC]
167 schema.Optional('git_dependencies'):
168 schema.Or(DEPS, SYNC, SUBMODULES),
169
Ayu Ishii09858612020-06-26 18:00:52 +0000170 # List of host names from which dependencies are allowed (allowlist).
Raul Tambreb946b232019-03-26 14:48:46 +0000171 # NOTE: when not present, all hosts are allowed.
172 # NOTE: scoped to current DEPS file, not recursive.
Gavin Mak65c49b12023-08-24 18:06:42 +0000173 schema.Optional('allowed_hosts'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200174
Raul Tambreb946b232019-03-26 14:48:46 +0000175 # Mapping from paths to repo and revision to check out under that path.
176 # Applying this mapping to the on-disk checkout is the main purpose
177 # of gclient, and also why the config file is called DEPS.
178 #
179 # The following functions are allowed:
180 #
181 # Var(): allows variable substitution (either from 'vars' dict below,
182 # or command-line override)
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000183 schema.Optional('deps'):
184 _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200185
Raul Tambreb946b232019-03-26 14:48:46 +0000186 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
187 # Also see 'target_os'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000188 schema.Optional('deps_os'):
189 _NodeDictSchema({
Gavin Mak65c49b12023-08-24 18:06:42 +0000190 schema.Optional(str): _GCLIENT_DEPS_SCHEMA,
Aaron Gableac9b0f32019-04-18 17:38:37 +0000191 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200192
Raul Tambreb946b232019-03-26 14:48:46 +0000193 # Dependency to get gclient_gn_args* settings from. This allows these
194 # values to be set in a recursedeps file, rather than requiring that
195 # they exist in the top-level solution.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000196 schema.Optional('gclient_gn_args_from'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000197 str,
Michael Moss848c86e2018-05-03 16:05:50 -0700198
Raul Tambreb946b232019-03-26 14:48:46 +0000199 # Path to GN args file to write selected variables.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000200 schema.Optional('gclient_gn_args_file'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000201 str,
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200202
Raul Tambreb946b232019-03-26 14:48:46 +0000203 # Subset of variables to write to the GN args file (see above).
Gavin Mak65c49b12023-08-24 18:06:42 +0000204 schema.Optional('gclient_gn_args'): [schema.Optional(str)],
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200205
Raul Tambreb946b232019-03-26 14:48:46 +0000206 # Hooks executed after gclient sync (unless suppressed), or explicitly
207 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
208 # Also see 'pre_deps_hooks'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000209 schema.Optional('hooks'):
210 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200211
Raul Tambreb946b232019-03-26 14:48:46 +0000212 # Similar to 'hooks', also keyed by OS.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000213 schema.Optional('hooks_os'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000214 _NodeDictSchema({schema.Optional(str): _GCLIENT_HOOKS_SCHEMA}),
Scott Grahamc4826742017-05-11 16:59:23 -0700215
Raul Tambreb946b232019-03-26 14:48:46 +0000216 # Rules which #includes are allowed in the directory.
217 # Also see 'skip_child_includes' and 'specific_include_rules'.
Gavin Mak65c49b12023-08-24 18:06:42 +0000218 schema.Optional('include_rules'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200219
Yuki Shiinoa0422642022-08-04 08:14:15 +0000220 # Optionally discards rules from parent directories, similar to
221 # "noparent" in OWNERS files. For example, if
222 # //base/allocator/partition_allocator has "noparent = True" then it
223 # will not inherit rules from //base/DEPS and //base/allocator/DEPS,
224 # forcing each //base/allocator/partition_allocator/{foo,bar,...} to
225 # declare all its dependencies.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000226 schema.Optional('noparent'):
227 bool,
Yuki Shiinoa0422642022-08-04 08:14:15 +0000228
Raul Tambreb946b232019-03-26 14:48:46 +0000229 # Hooks executed before processing DEPS. See 'hooks' for more details.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000230 schema.Optional('pre_deps_hooks'):
231 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200232
Raul Tambreb946b232019-03-26 14:48:46 +0000233 # Recursion limit for nested DEPS.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000234 schema.Optional('recursion'):
235 int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200236
Ayu Ishii09858612020-06-26 18:00:52 +0000237 # Allowlists deps for which recursion should be enabled.
Raul Tambreb946b232019-03-26 14:48:46 +0000238 schema.Optional('recursedeps'): [
Gavin Mak65c49b12023-08-24 18:06:42 +0000239 schema.Optional(schema.Or(str, (str, str), [str, str])),
Raul Tambreb946b232019-03-26 14:48:46 +0000240 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200241
Ayu Ishii09858612020-06-26 18:00:52 +0000242 # Blocklists directories for checking 'include_rules'.
Gavin Mak65c49b12023-08-24 18:06:42 +0000243 schema.Optional('skip_child_includes'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200244
Raul Tambreb946b232019-03-26 14:48:46 +0000245 # Mapping from paths to include rules specific for that path.
246 # See 'include_rules' for more details.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000247 schema.Optional('specific_include_rules'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000248 _NodeDictSchema({schema.Optional(str): [str]}),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200249
Raul Tambreb946b232019-03-26 14:48:46 +0000250 # List of additional OS names to consider when selecting dependencies
251 # from deps_os.
Gavin Mak65c49b12023-08-24 18:06:42 +0000252 schema.Optional('target_os'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200253
Raul Tambreb946b232019-03-26 14:48:46 +0000254 # For recursed-upon sub-dependencies, check out their own dependencies
255 # relative to the parent's path, rather than relative to the .gclient
256 # file.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000257 schema.Optional('use_relative_paths'):
258 bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200259
Michael Spang0e99b9b2020-08-12 13:34:48 +0000260 # For recursed-upon sub-dependencies, run their hooks relative to the
261 # parent's path instead of relative to the .gclient file.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000262 schema.Optional('use_relative_hooks'):
263 bool,
Michael Spang0e99b9b2020-08-12 13:34:48 +0000264
Raul Tambreb946b232019-03-26 14:48:46 +0000265 # Variables that can be referenced using Var() - see 'deps'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000266 schema.Optional('vars'):
267 _NodeDictSchema({
Gavin Mak65c49b12023-08-24 18:06:42 +0000268 schema.Optional(str):
269 schema.Or(ConstantString, str, bool),
Aaron Gableac9b0f32019-04-18 17:38:37 +0000270 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000271 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200272
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200273
Edward Lemure05f18d2018-06-08 17:36:53 +0000274def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000275 """Safely evaluates a single expression. Returns the result."""
276 _allowed_names = {'None': None, 'True': True, 'False': False}
277 if isinstance(node_or_string, ConstantString):
278 return node_or_string.value
279 if isinstance(node_or_string, str):
280 node_or_string = ast.parse(node_or_string,
281 filename=filename,
282 mode='eval')
283 if isinstance(node_or_string, ast.Expression):
284 node_or_string = node_or_string.body
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000285
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000286 def _convert(node):
287 if isinstance(node, ast.Str):
288 if vars_dict is None:
289 return node.s
290 try:
291 return node.s.format(**vars_dict)
292 except KeyError as e:
293 raise KeyError(
294 '%s was used as a variable, but was not declared in the vars dict '
295 '(file %r, line %s)' %
296 (e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
297 elif isinstance(node, ast.Num):
298 return node.n
299 elif isinstance(node, ast.Tuple):
300 return tuple(map(_convert, node.elts))
301 elif isinstance(node, ast.List):
302 return list(map(_convert, node.elts))
303 elif isinstance(node, ast.Dict):
304 node_dict = _NodeDict()
305 for key_node, value_node in zip(node.keys, node.values):
306 key = _convert(key_node)
307 if key in node_dict:
308 raise ValueError(
309 'duplicate key in dictionary: %s (file %r, line %s)' %
310 (key, filename, getattr(key_node, 'lineno',
311 '<unknown>')))
312 node_dict.SetNode(key, _convert(value_node), value_node)
313 return node_dict
314 elif isinstance(node, ast.Name):
315 if node.id not in _allowed_names:
316 raise ValueError(
317 'invalid name %r (file %r, line %s)' %
318 (node.id, filename, getattr(node, 'lineno', '<unknown>')))
319 return _allowed_names[node.id]
320 elif not sys.version_info[:2] < (3, 4) and isinstance(
321 node, ast.NameConstant): # Since Python 3.4
322 return node.value
323 elif isinstance(node, ast.Call):
324 if (not isinstance(node.func, ast.Name)
325 or (node.func.id not in ('Str', 'Var'))):
326 raise ValueError(
327 'Str and Var are the only allowed functions (file %r, line %s)'
328 % (filename, getattr(node, 'lineno', '<unknown>')))
329 if node.keywords or getattr(node, 'starargs', None) or getattr(
330 node, 'kwargs', None) or len(node.args) != 1:
331 raise ValueError(
332 '%s takes exactly one argument (file %r, line %s)' %
333 (node.func.id, filename, getattr(node, 'lineno',
334 '<unknown>')))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000335
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000336 if node.func.id == 'Str':
337 if isinstance(node.args[0], ast.Str):
338 return ConstantString(node.args[0].s)
339 raise ValueError(
340 'Passed a non-string to Str() (file %r, line%s)' %
341 (filename, getattr(node, 'lineno', '<unknown>')))
342
343 arg = _convert(node.args[0])
344 if not isinstance(arg, str):
345 raise ValueError(
346 'Var\'s argument must be a variable name (file %r, line %s)'
347 % (filename, getattr(node, 'lineno', '<unknown>')))
348 if vars_dict is None:
349 return '{' + arg + '}'
350 if arg not in vars_dict:
351 raise KeyError(
352 '%s was used as a variable, but was not declared in the vars dict '
353 '(file %r, line %s)' %
354 (arg, filename, getattr(node, 'lineno', '<unknown>')))
355 val = vars_dict[arg]
356 if isinstance(val, ConstantString):
357 val = val.value
358 return val
359 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
360 return _convert(node.left) + _convert(node.right)
361 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
362 return _convert(node.left) % _convert(node.right)
363 else:
364 raise ValueError('unexpected AST node: %s %s (file %r, line %s)' %
365 (node, ast.dump(node), filename,
366 getattr(node, 'lineno', '<unknown>')))
367
368 return _convert(node_or_string)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200369
370
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000371def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000372 """Safely execs a set of assignments."""
373 def _validate_statement(node, local_scope):
374 if not isinstance(node, ast.Assign):
375 raise ValueError('unexpected AST node: %s %s (file %r, line %s)' %
376 (node, ast.dump(node), filename,
377 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200378
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000379 if len(node.targets) != 1:
380 raise ValueError(
381 'invalid assignment: use exactly one target (file %r, line %s)'
382 % (filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400383
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000384 target = node.targets[0]
385 if not isinstance(target, ast.Name):
386 raise ValueError(
387 'invalid assignment: target should be a name (file %r, line %s)'
388 % (filename, getattr(node, 'lineno', '<unknown>')))
389 if target.id in local_scope:
390 raise ValueError(
391 'invalid assignment: overrides var %r (file %r, line %s)' %
392 (target.id, filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400393
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000394 node_or_string = ast.parse(content, filename=filename, mode='exec')
395 if isinstance(node_or_string, ast.Expression):
396 node_or_string = node_or_string.body
Edward Lesmes6c24d372018-03-28 12:52:29 -0400397
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000398 if not isinstance(node_or_string, ast.Module):
399 raise ValueError('unexpected AST node: %s %s (file %r, line %s)' %
400 (node_or_string, ast.dump(node_or_string), filename,
401 getattr(node_or_string, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200402
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000403 statements = {}
404 for statement in node_or_string.body:
405 _validate_statement(statement, statements)
406 statements[statement.targets[0].id] = statement.value
Edward Lesmes6c24d372018-03-28 12:52:29 -0400407
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000408 tokens = {
409 token[2]: list(token)
410 for token in tokenize.generate_tokens(StringIO(content).readline)
411 }
Raul Tambreb946b232019-03-26 14:48:46 +0000412
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000413 local_scope = _NodeDict({}, tokens)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400414
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000415 # Process vars first, so we can expand variables in the rest of the DEPS
416 # file.
417 vars_dict = {}
418 if 'vars' in statements:
419 vars_statement = statements['vars']
420 value = _gclient_eval(vars_statement, filename)
421 local_scope.SetNode('vars', value, vars_statement)
422 # Update the parsed vars with the overrides, but only if they are
423 # already present (overrides do not introduce new variables).
424 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000425
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000426 if builtin_vars:
427 vars_dict.update(builtin_vars)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000428
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000429 if vars_override:
430 vars_dict.update(
431 {k: v
432 for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400433
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000434 for name, node in statements.items():
435 value = _gclient_eval(node, filename, vars_dict)
436 local_scope.SetNode(name, value, node)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400437
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000438 try:
439 return _GCLIENT_SCHEMA.validate(local_scope)
440 except schema.SchemaError as e:
441 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400442
443
Edward Lemur16f4bad2018-05-16 16:53:49 -0400444def _StandardizeDeps(deps_dict, vars_dict):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000445 """"Standardizes the deps_dict.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400446
447 For each dependency:
448 - Expands the variable in the dependency name.
449 - Ensures the dependency is a dictionary.
450 - Set's the 'dep_type' to be 'git' by default.
451 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000452 new_deps_dict = {}
453 for dep_name, dep_info in deps_dict.items():
454 dep_name = dep_name.format(**vars_dict)
455 if not isinstance(dep_info, collections.abc.Mapping):
456 dep_info = {'url': dep_info}
457 dep_info.setdefault('dep_type', 'git')
458 new_deps_dict[dep_name] = dep_info
459 return new_deps_dict
Edward Lemur16f4bad2018-05-16 16:53:49 -0400460
461
462def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000463 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400464
465 The dependencies in os_deps_dict are transformed into conditional dependencies
466 using |'checkout_' + os_name|.
467 If the dependency is already present, the URL and revision must coincide.
468 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000469 for dep_name, dep_info in os_deps_dict.items():
470 # Make this condition very visible, so it's not a silent failure.
471 # It's unclear how to support None override in deps_os.
472 if dep_info['url'] is None:
473 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info,
474 os_name)
475 continue
Edward Lemur16f4bad2018-05-16 16:53:49 -0400476
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000477 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
478 UpdateCondition(dep_info, 'and', os_condition)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400479
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000480 if dep_name in deps_dict:
481 if deps_dict[dep_name]['url'] != dep_info['url']:
482 raise gclient_utils.Error(
483 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
484 'entry (%r).' %
485 (os_name, dep_name, dep_info, deps_dict[dep_name]))
Edward Lemur16f4bad2018-05-16 16:53:49 -0400486
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000487 UpdateCondition(dep_info, 'or',
488 deps_dict[dep_name].get('condition'))
Edward Lemur16f4bad2018-05-16 16:53:49 -0400489
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000490 deps_dict[dep_name] = dep_info
Edward Lemur16f4bad2018-05-16 16:53:49 -0400491
492
493def UpdateCondition(info_dict, op, new_condition):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000494 """Updates info_dict's condition with |new_condition|.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400495
496 An absent value is treated as implicitly True.
497 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000498 curr_condition = info_dict.get('condition')
499 # Easy case: Both are present.
500 if curr_condition and new_condition:
501 info_dict['condition'] = '(%s) %s (%s)' % (curr_condition, op,
502 new_condition)
503 # If |op| == 'and', and at least one condition is present, then use it.
504 elif op == 'and' and (curr_condition or new_condition):
505 info_dict['condition'] = curr_condition or new_condition
506 # Otherwise, no condition should be set
507 elif curr_condition:
508 del info_dict['condition']
Edward Lemur16f4bad2018-05-16 16:53:49 -0400509
510
Edward Lemur67cabcd2020-03-03 19:31:15 +0000511def Parse(content, filename, vars_override=None, builtin_vars=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000512 """Parses DEPS strings.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400513
514 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000515 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400516 variable expansion.
517
518 Args:
519 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400520 filename: str. The name of the DEPS file, or a string describing the source
521 of the content, e.g. '<string>', '<unknown>'.
522 vars_override: dict, optional. A dictionary with overrides for the variables
523 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000524 builtin_vars: dict, optional. A dictionary with variables that are provided
525 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400526
527 Returns:
528 A Python dict with the parsed contents of the DEPS file, as specified by the
529 schema above.
530 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000531 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400532
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000533 vars_dict = result.get('vars', {})
534 if 'deps' in result:
535 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400536
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000537 if 'deps_os' in result:
538 deps = result.setdefault('deps', {})
539 for os_name, os_deps in result['deps_os'].items():
540 os_deps = _StandardizeDeps(os_deps, vars_dict)
541 _MergeDepsOs(deps, os_deps, os_name)
542 del result['deps_os']
Edward Lemur16f4bad2018-05-16 16:53:49 -0400543
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000544 if 'hooks_os' in result:
545 hooks = result.setdefault('hooks', [])
546 for os_name, os_hooks in result['hooks_os'].items():
547 for hook in os_hooks:
548 UpdateCondition(hook, 'and', 'checkout_' + os_name)
549 hooks.extend(os_hooks)
550 del result['hooks_os']
Edward Lemur16f4bad2018-05-16 16:53:49 -0400551
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000552 return result
Edward Lemur16f4bad2018-05-16 16:53:49 -0400553
554
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200555def EvaluateCondition(condition, variables, referenced_variables=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000556 """Safely evaluates a boolean condition. Returns the result."""
557 if not referenced_variables:
558 referenced_variables = set()
559 _allowed_names = {'None': None, 'True': True, 'False': False}
560 main_node = ast.parse(condition, mode='eval')
561 if isinstance(main_node, ast.Expression):
562 main_node = main_node.body
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000563
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000564 def _convert(node, allow_tuple=False):
565 if isinstance(node, ast.Str):
566 return node.s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000567
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000568 if isinstance(node, ast.Tuple) and allow_tuple:
569 return tuple(map(_convert, node.elts))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000570
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000571 if isinstance(node, ast.Name):
572 if node.id in referenced_variables:
573 raise ValueError('invalid cyclic reference to %r (inside %r)' %
574 (node.id, condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000575
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000576 if node.id in _allowed_names:
577 return _allowed_names[node.id]
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200578
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000579 if node.id in variables:
580 value = variables[node.id]
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200581
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000582 # Allow using "native" types, without wrapping everything in
583 # strings. Note that schema constraints still apply to
584 # variables.
585 if not isinstance(value, str):
586 return value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000587
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000588 # Recursively evaluate the variable reference.
589 return EvaluateCondition(variables[node.id], variables,
590 referenced_variables.union([node.id]))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000591
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000592 # Implicitly convert unrecognized names to strings.
593 # If we want to change this, we'll need to explicitly distinguish
594 # between arguments for GN to be passed verbatim, and ones to
595 # be evaluated.
596 return node.id
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000597
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000598 if not sys.version_info[:2] < (3, 4) and isinstance(
599 node, ast.NameConstant): # Since Python 3.4
600 return node.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000601
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000602 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
603 bool_values = []
604 for value in node.values:
605 bool_values.append(_convert(value))
606 if not isinstance(bool_values[-1], bool):
607 raise ValueError('invalid "or" operand %r (inside %r)' %
608 (bool_values[-1], condition))
609 return any(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000610
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000611 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
612 bool_values = []
613 for value in node.values:
614 bool_values.append(_convert(value))
615 if not isinstance(bool_values[-1], bool):
616 raise ValueError('invalid "and" operand %r (inside %r)' %
617 (bool_values[-1], condition))
618 return all(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000619
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000620 if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
621 value = _convert(node.operand)
622 if not isinstance(value, bool):
623 raise ValueError('invalid "not" operand %r (inside %r)' %
624 (value, condition))
625 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200626
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000627 if isinstance(node, ast.Compare):
628 if len(node.ops) != 1:
629 raise ValueError(
630 'invalid compare: exactly 1 operator required (inside %r)' %
631 (condition))
632 if len(node.comparators) != 1:
633 raise ValueError(
634 'invalid compare: exactly 1 comparator required (inside %r)'
635 % (condition))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200636
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000637 left = _convert(node.left)
638 right = _convert(node.comparators[0],
639 allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200640
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000641 if isinstance(node.ops[0], ast.Eq):
642 return left == right
643 if isinstance(node.ops[0], ast.NotEq):
644 return left != right
645 if isinstance(node.ops[0], ast.In):
646 return left in right
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000647
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000648 raise ValueError('unexpected operator: %s %s (inside %r)' %
649 (node.ops[0], ast.dump(node), condition))
650
651 raise ValueError('unexpected AST node: %s %s (inside %r)' %
652 (node, ast.dump(node), condition))
653
654 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400655
656
657def RenderDEPSFile(gclient_dict):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000658 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Gavin Mak7f5b53f2023-09-07 18:13:01 +0000659 return tokenize.untokenize(contents)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400660
661
662def _UpdateAstString(tokens, node, value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000663 if isinstance(node, ast.Call):
664 node = node.args[0]
665 position = node.lineno, node.col_offset
666 quote_char = ''
667 if isinstance(node, ast.Str):
668 quote_char = tokens[position][1][0]
669 value = value.encode('unicode_escape').decode('utf-8')
670 tokens[position][1] = quote_char + value + quote_char
671 node.s = value
Edward Lesmes6f64a052018-03-20 17:35:49 -0400672
673
Edward Lesmes3d993812018-04-02 12:52:49 -0400674def _ShiftLinesInTokens(tokens, delta, start):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000675 new_tokens = {}
676 for token in tokens.values():
677 if token[2][0] >= start:
678 token[2] = token[2][0] + delta, token[2][1]
679 token[3] = token[3][0] + delta, token[3][1]
680 new_tokens[token[2]] = token
681 return new_tokens
Edward Lesmes3d993812018-04-02 12:52:49 -0400682
683
684def AddVar(gclient_dict, var_name, value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000685 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
686 raise ValueError(
687 "Can't use SetVar for the given gclient dict. It contains no "
688 "formatting information.")
Edward Lesmes3d993812018-04-02 12:52:49 -0400689
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000690 if 'vars' not in gclient_dict:
691 raise KeyError("vars dict is not defined.")
Edward Lesmes3d993812018-04-02 12:52:49 -0400692
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000693 if var_name in gclient_dict['vars']:
694 raise ValueError(
695 "%s has already been declared in the vars dict. Consider using SetVar "
696 "instead." % var_name)
Edward Lesmes3d993812018-04-02 12:52:49 -0400697
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000698 if not gclient_dict['vars']:
699 raise ValueError('vars dict is empty. This is not yet supported.')
Edward Lesmes3d993812018-04-02 12:52:49 -0400700
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000701 # We will attempt to add the var right after 'vars = {'.
702 node = gclient_dict.GetNode('vars')
703 if node is None:
704 raise ValueError("The vars dict has no formatting information." %
705 var_name)
706 line = node.lineno + 1
Edward Lesmes8d626572018-04-05 17:53:10 -0400707
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000708 # We will try to match the new var's indentation to the next variable.
709 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400710
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000711 # We use a minimal Python dictionary, so that ast can parse it.
712 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
713 var_ast = ast.parse(var_content).body[0].value
Edward Lesmes3d993812018-04-02 12:52:49 -0400714
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000715 # Set the ast nodes for the key and value.
716 vars_node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400717
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000718 var_name_node = var_ast.keys[0]
719 var_name_node.lineno += line - 2
720 vars_node.keys.insert(0, var_name_node)
Edward Lesmes3d993812018-04-02 12:52:49 -0400721
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000722 value_node = var_ast.values[0]
723 value_node.lineno += line - 2
724 vars_node.values.insert(0, value_node)
Edward Lesmes3d993812018-04-02 12:52:49 -0400725
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000726 # Update the tokens.
727 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
728 var_tokens = {
729 token[2]: list(token)
730 # Ignore the tokens corresponding to braces and new lines.
731 for token in var_tokens[2:-3]
732 }
Edward Lesmes3d993812018-04-02 12:52:49 -0400733
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000734 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
735 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
Edward Lesmes3d993812018-04-02 12:52:49 -0400736
737
Edward Lesmes6f64a052018-03-20 17:35:49 -0400738def SetVar(gclient_dict, var_name, value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000739 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
740 raise ValueError(
741 "Can't use SetVar for the given gclient dict. It contains no "
742 "formatting information.")
743 tokens = gclient_dict.tokens
Edward Lesmes6f64a052018-03-20 17:35:49 -0400744
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000745 if 'vars' not in gclient_dict:
746 raise KeyError("vars dict is not defined.")
Edward Lesmes3d993812018-04-02 12:52:49 -0400747
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000748 if var_name not in gclient_dict['vars']:
749 raise ValueError(
750 "%s has not been declared in the vars dict. Consider using AddVar "
751 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400752
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000753 node = gclient_dict['vars'].GetNode(var_name)
754 if node is None:
755 raise ValueError(
756 "The vars entry for %s has no formatting information." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400757
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000758 _UpdateAstString(tokens, node, value)
759 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400760
761
Edward Lemura1e4d482018-12-17 19:01:03 +0000762def _GetVarName(node):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000763 if isinstance(node, ast.Call):
764 return node.args[0].s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000765
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000766 if node.s.endswith('}'):
767 last_brace = node.s.rfind('{')
768 return node.s[last_brace + 1:-1]
769 return None
Edward Lemura1e4d482018-12-17 19:01:03 +0000770
771
Edward Lesmes6f64a052018-03-20 17:35:49 -0400772def SetCIPD(gclient_dict, dep_name, package_name, new_version):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000773 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000774 raise ValueError(
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000775 "Can't use SetCIPD for the given gclient dict. It contains no "
776 "formatting information.")
777 tokens = gclient_dict.tokens
Edward Lemur3c117942020-03-12 17:21:12 +0000778
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000779 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
780 raise KeyError("Could not find any dependency called %s." % dep_name)
781
782 # Find the package with the given name
783 packages = [
784 package for package in gclient_dict['deps'][dep_name]['packages']
785 if package['package'] == package_name
786 ]
787 if len(packages) != 1:
788 raise ValueError(
789 "There must be exactly one package with the given name (%s), "
790 "%s were found." % (package_name, len(packages)))
791
792 # TODO(ehmaldonado): Support Var in package's version.
793 node = packages[0].GetNode('version')
794 if node is None:
795 raise ValueError(
796 "The deps entry for %s:%s has no formatting information." %
797 (dep_name, package_name))
Edward Lemur3c117942020-03-12 17:21:12 +0000798
Edward Lesmes62af4e42018-03-30 18:15:44 -0400799 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000800 raise ValueError(
801 "Unsupported dependency revision format. Please file a bug to the "
802 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400803
804 var_name = _GetVarName(node)
805 if var_name is not None:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000806 SetVar(gclient_dict, var_name, new_version)
Edward Lesmes62af4e42018-03-30 18:15:44 -0400807 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000808 _UpdateAstString(tokens, node, new_version)
809 packages[0].SetNode('version', new_version, node)
Edward Lesmes62af4e42018-03-30 18:15:44 -0400810
Edward Lesmes6f64a052018-03-20 17:35:49 -0400811
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000812def SetRevision(gclient_dict, dep_name, new_revision):
813 def _UpdateRevision(dep_dict, dep_key, new_revision):
814 dep_node = dep_dict.GetNode(dep_key)
815 if dep_node is None:
816 raise ValueError(
817 "The deps entry for %s has no formatting information." %
818 dep_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400819
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000820 node = dep_node
821 if isinstance(node, ast.BinOp):
822 node = node.right
823
824 if isinstance(node, ast.Str):
825 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
826 if token != node.s:
827 raise ValueError(
828 'Can\'t update value for %s. Multiline strings and implicitly '
829 'concatenated strings are not supported.\n'
830 'Consider reformatting the DEPS file.' % dep_key)
831
832 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
833 raise ValueError(
834 "Unsupported dependency revision format. Please file a bug to the "
835 "Infra>SDK component in crbug.com")
836
837 var_name = _GetVarName(node)
838 if var_name is not None:
839 SetVar(gclient_dict, var_name, new_revision)
840 else:
841 if '@' in node.s:
842 # '@' is part of the last string, which we want to modify.
843 # Discard whatever was after the '@' and put the new revision in
844 # its place.
845 new_revision = node.s.split('@')[0] + '@' + new_revision
846 elif '@' not in dep_dict[dep_key]:
847 # '@' is not part of the URL at all. This mean the dependency is
848 # unpinned and we should pin it.
849 new_revision = node.s + '@' + new_revision
850 _UpdateAstString(tokens, node, new_revision)
851 dep_dict.SetNode(dep_key, new_revision, node)
852
853 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
854 raise ValueError(
855 "Can't use SetRevision for the given gclient dict. It contains no "
856 "formatting information.")
857 tokens = gclient_dict.tokens
858
859 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
860 raise KeyError("Could not find any dependency called %s." % dep_name)
861
862 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
863 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
864 else:
865 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400866
867
868def GetVar(gclient_dict, var_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000869 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
870 raise KeyError("Could not find any variable called %s." % var_name)
Edward Lesmes411041f2018-04-05 20:12:55 -0400871
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000872 val = gclient_dict['vars'][var_name]
873 if isinstance(val, ConstantString):
874 return val.value
875 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400876
877
878def GetCIPD(gclient_dict, dep_name, package_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000879 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
880 raise KeyError("Could not find any dependency called %s." % dep_name)
Edward Lesmes411041f2018-04-05 20:12:55 -0400881
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000882 # Find the package with the given name
883 packages = [
884 package for package in gclient_dict['deps'][dep_name]['packages']
885 if package['package'] == package_name
886 ]
887 if len(packages) != 1:
888 raise ValueError(
889 "There must be exactly one package with the given name (%s), "
890 "%s were found." % (package_name, len(packages)))
Edward Lesmes411041f2018-04-05 20:12:55 -0400891
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000892 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400893
894
895def GetRevision(gclient_dict, dep_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000896 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
897 suggestions = []
898 if 'deps' in gclient_dict:
899 for key in gclient_dict['deps']:
900 if dep_name in key:
901 suggestions.append(key)
902 if suggestions:
903 raise KeyError(
904 "Could not find any dependency called %s. Did you mean %s" %
905 (dep_name, ' or '.join(suggestions)))
906 raise KeyError("Could not find any dependency called %s." % dep_name)
Edward Lesmes411041f2018-04-05 20:12:55 -0400907
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000908 dep = gclient_dict['deps'][dep_name]
909 if dep is None:
910 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000911
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000912 if isinstance(dep, str):
913 _, _, revision = dep.partition('@')
914 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000915
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000916 if isinstance(dep, collections.abc.Mapping) and 'url' in dep:
917 _, _, revision = dep['url'].partition('@')
918 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000919
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000920 raise ValueError('%s is not a valid git dependency.' % dep_name)