blob: bc3427cc5e7a1a7e2347fabfe4617bb000e0babe [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 # The tokenized representation needs to end with a newline token, otherwise
409 # untokenization will trigger an assert later on.
410 # In Python 2.7 on Windows we need to ensure the input ends with a newline
411 # for a newline token to be generated.
412 # In other cases a newline token is always generated during tokenization so
413 # this has no effect.
414 # TODO: Remove this workaround after migrating to Python 3.
415 content += '\n'
416 tokens = {
417 token[2]: list(token)
418 for token in tokenize.generate_tokens(StringIO(content).readline)
419 }
Raul Tambreb946b232019-03-26 14:48:46 +0000420
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000421 local_scope = _NodeDict({}, tokens)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400422
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000423 # Process vars first, so we can expand variables in the rest of the DEPS
424 # file.
425 vars_dict = {}
426 if 'vars' in statements:
427 vars_statement = statements['vars']
428 value = _gclient_eval(vars_statement, filename)
429 local_scope.SetNode('vars', value, vars_statement)
430 # Update the parsed vars with the overrides, but only if they are
431 # already present (overrides do not introduce new variables).
432 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000433
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000434 if builtin_vars:
435 vars_dict.update(builtin_vars)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000436
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000437 if vars_override:
438 vars_dict.update(
439 {k: v
440 for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400441
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000442 for name, node in statements.items():
443 value = _gclient_eval(node, filename, vars_dict)
444 local_scope.SetNode(name, value, node)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400445
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000446 try:
447 return _GCLIENT_SCHEMA.validate(local_scope)
448 except schema.SchemaError as e:
449 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400450
451
Edward Lemur16f4bad2018-05-16 16:53:49 -0400452def _StandardizeDeps(deps_dict, vars_dict):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000453 """"Standardizes the deps_dict.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400454
455 For each dependency:
456 - Expands the variable in the dependency name.
457 - Ensures the dependency is a dictionary.
458 - Set's the 'dep_type' to be 'git' by default.
459 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000460 new_deps_dict = {}
461 for dep_name, dep_info in deps_dict.items():
462 dep_name = dep_name.format(**vars_dict)
463 if not isinstance(dep_info, collections.abc.Mapping):
464 dep_info = {'url': dep_info}
465 dep_info.setdefault('dep_type', 'git')
466 new_deps_dict[dep_name] = dep_info
467 return new_deps_dict
Edward Lemur16f4bad2018-05-16 16:53:49 -0400468
469
470def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000471 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400472
473 The dependencies in os_deps_dict are transformed into conditional dependencies
474 using |'checkout_' + os_name|.
475 If the dependency is already present, the URL and revision must coincide.
476 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000477 for dep_name, dep_info in os_deps_dict.items():
478 # Make this condition very visible, so it's not a silent failure.
479 # It's unclear how to support None override in deps_os.
480 if dep_info['url'] is None:
481 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info,
482 os_name)
483 continue
Edward Lemur16f4bad2018-05-16 16:53:49 -0400484
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000485 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
486 UpdateCondition(dep_info, 'and', os_condition)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400487
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000488 if dep_name in deps_dict:
489 if deps_dict[dep_name]['url'] != dep_info['url']:
490 raise gclient_utils.Error(
491 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
492 'entry (%r).' %
493 (os_name, dep_name, dep_info, deps_dict[dep_name]))
Edward Lemur16f4bad2018-05-16 16:53:49 -0400494
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000495 UpdateCondition(dep_info, 'or',
496 deps_dict[dep_name].get('condition'))
Edward Lemur16f4bad2018-05-16 16:53:49 -0400497
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000498 deps_dict[dep_name] = dep_info
Edward Lemur16f4bad2018-05-16 16:53:49 -0400499
500
501def UpdateCondition(info_dict, op, new_condition):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000502 """Updates info_dict's condition with |new_condition|.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400503
504 An absent value is treated as implicitly True.
505 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000506 curr_condition = info_dict.get('condition')
507 # Easy case: Both are present.
508 if curr_condition and new_condition:
509 info_dict['condition'] = '(%s) %s (%s)' % (curr_condition, op,
510 new_condition)
511 # If |op| == 'and', and at least one condition is present, then use it.
512 elif op == 'and' and (curr_condition or new_condition):
513 info_dict['condition'] = curr_condition or new_condition
514 # Otherwise, no condition should be set
515 elif curr_condition:
516 del info_dict['condition']
Edward Lemur16f4bad2018-05-16 16:53:49 -0400517
518
Edward Lemur67cabcd2020-03-03 19:31:15 +0000519def Parse(content, filename, vars_override=None, builtin_vars=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000520 """Parses DEPS strings.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400521
522 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000523 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400524 variable expansion.
525
526 Args:
527 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400528 filename: str. The name of the DEPS file, or a string describing the source
529 of the content, e.g. '<string>', '<unknown>'.
530 vars_override: dict, optional. A dictionary with overrides for the variables
531 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000532 builtin_vars: dict, optional. A dictionary with variables that are provided
533 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400534
535 Returns:
536 A Python dict with the parsed contents of the DEPS file, as specified by the
537 schema above.
538 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000539 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400540
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000541 vars_dict = result.get('vars', {})
542 if 'deps' in result:
543 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400544
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000545 if 'deps_os' in result:
546 deps = result.setdefault('deps', {})
547 for os_name, os_deps in result['deps_os'].items():
548 os_deps = _StandardizeDeps(os_deps, vars_dict)
549 _MergeDepsOs(deps, os_deps, os_name)
550 del result['deps_os']
Edward Lemur16f4bad2018-05-16 16:53:49 -0400551
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000552 if 'hooks_os' in result:
553 hooks = result.setdefault('hooks', [])
554 for os_name, os_hooks in result['hooks_os'].items():
555 for hook in os_hooks:
556 UpdateCondition(hook, 'and', 'checkout_' + os_name)
557 hooks.extend(os_hooks)
558 del result['hooks_os']
Edward Lemur16f4bad2018-05-16 16:53:49 -0400559
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000560 return result
Edward Lemur16f4bad2018-05-16 16:53:49 -0400561
562
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200563def EvaluateCondition(condition, variables, referenced_variables=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000564 """Safely evaluates a boolean condition. Returns the result."""
565 if not referenced_variables:
566 referenced_variables = set()
567 _allowed_names = {'None': None, 'True': True, 'False': False}
568 main_node = ast.parse(condition, mode='eval')
569 if isinstance(main_node, ast.Expression):
570 main_node = main_node.body
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000571
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000572 def _convert(node, allow_tuple=False):
573 if isinstance(node, ast.Str):
574 return node.s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000575
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000576 if isinstance(node, ast.Tuple) and allow_tuple:
577 return tuple(map(_convert, node.elts))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000578
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000579 if isinstance(node, ast.Name):
580 if node.id in referenced_variables:
581 raise ValueError('invalid cyclic reference to %r (inside %r)' %
582 (node.id, condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000583
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000584 if node.id in _allowed_names:
585 return _allowed_names[node.id]
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200586
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000587 if node.id in variables:
588 value = variables[node.id]
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200589
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000590 # Allow using "native" types, without wrapping everything in
591 # strings. Note that schema constraints still apply to
592 # variables.
593 if not isinstance(value, str):
594 return value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000595
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000596 # Recursively evaluate the variable reference.
597 return EvaluateCondition(variables[node.id], variables,
598 referenced_variables.union([node.id]))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000599
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000600 # Implicitly convert unrecognized names to strings.
601 # If we want to change this, we'll need to explicitly distinguish
602 # between arguments for GN to be passed verbatim, and ones to
603 # be evaluated.
604 return node.id
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000605
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000606 if not sys.version_info[:2] < (3, 4) and isinstance(
607 node, ast.NameConstant): # Since Python 3.4
608 return node.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000609
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000610 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
611 bool_values = []
612 for value in node.values:
613 bool_values.append(_convert(value))
614 if not isinstance(bool_values[-1], bool):
615 raise ValueError('invalid "or" operand %r (inside %r)' %
616 (bool_values[-1], condition))
617 return any(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000618
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000619 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
620 bool_values = []
621 for value in node.values:
622 bool_values.append(_convert(value))
623 if not isinstance(bool_values[-1], bool):
624 raise ValueError('invalid "and" operand %r (inside %r)' %
625 (bool_values[-1], condition))
626 return all(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000627
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000628 if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
629 value = _convert(node.operand)
630 if not isinstance(value, bool):
631 raise ValueError('invalid "not" operand %r (inside %r)' %
632 (value, condition))
633 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200634
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000635 if isinstance(node, ast.Compare):
636 if len(node.ops) != 1:
637 raise ValueError(
638 'invalid compare: exactly 1 operator required (inside %r)' %
639 (condition))
640 if len(node.comparators) != 1:
641 raise ValueError(
642 'invalid compare: exactly 1 comparator required (inside %r)'
643 % (condition))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200644
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000645 left = _convert(node.left)
646 right = _convert(node.comparators[0],
647 allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200648
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000649 if isinstance(node.ops[0], ast.Eq):
650 return left == right
651 if isinstance(node.ops[0], ast.NotEq):
652 return left != right
653 if isinstance(node.ops[0], ast.In):
654 return left in right
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000655
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000656 raise ValueError('unexpected operator: %s %s (inside %r)' %
657 (node.ops[0], ast.dump(node), condition))
658
659 raise ValueError('unexpected AST node: %s %s (inside %r)' %
660 (node, ast.dump(node), condition))
661
662 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400663
664
665def RenderDEPSFile(gclient_dict):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000666 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
667 # The last token is a newline, which we ensure in Exec() for compatibility.
668 # However tests pass in inputs not ending with a newline and expect the same
669 # back, so for backwards compatibility need to remove that newline
670 # character. TODO: Fix tests to expect the newline
671 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400672
673
674def _UpdateAstString(tokens, node, value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000675 if isinstance(node, ast.Call):
676 node = node.args[0]
677 position = node.lineno, node.col_offset
678 quote_char = ''
679 if isinstance(node, ast.Str):
680 quote_char = tokens[position][1][0]
681 value = value.encode('unicode_escape').decode('utf-8')
682 tokens[position][1] = quote_char + value + quote_char
683 node.s = value
Edward Lesmes6f64a052018-03-20 17:35:49 -0400684
685
Edward Lesmes3d993812018-04-02 12:52:49 -0400686def _ShiftLinesInTokens(tokens, delta, start):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000687 new_tokens = {}
688 for token in tokens.values():
689 if token[2][0] >= start:
690 token[2] = token[2][0] + delta, token[2][1]
691 token[3] = token[3][0] + delta, token[3][1]
692 new_tokens[token[2]] = token
693 return new_tokens
Edward Lesmes3d993812018-04-02 12:52:49 -0400694
695
696def AddVar(gclient_dict, var_name, value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000697 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
698 raise ValueError(
699 "Can't use SetVar for the given gclient dict. It contains no "
700 "formatting information.")
Edward Lesmes3d993812018-04-02 12:52:49 -0400701
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000702 if 'vars' not in gclient_dict:
703 raise KeyError("vars dict is not defined.")
Edward Lesmes3d993812018-04-02 12:52:49 -0400704
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000705 if var_name in gclient_dict['vars']:
706 raise ValueError(
707 "%s has already been declared in the vars dict. Consider using SetVar "
708 "instead." % var_name)
Edward Lesmes3d993812018-04-02 12:52:49 -0400709
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000710 if not gclient_dict['vars']:
711 raise ValueError('vars dict is empty. This is not yet supported.')
Edward Lesmes3d993812018-04-02 12:52:49 -0400712
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000713 # We will attempt to add the var right after 'vars = {'.
714 node = gclient_dict.GetNode('vars')
715 if node is None:
716 raise ValueError("The vars dict has no formatting information." %
717 var_name)
718 line = node.lineno + 1
Edward Lesmes8d626572018-04-05 17:53:10 -0400719
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000720 # We will try to match the new var's indentation to the next variable.
721 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400722
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000723 # We use a minimal Python dictionary, so that ast can parse it.
724 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
725 var_ast = ast.parse(var_content).body[0].value
Edward Lesmes3d993812018-04-02 12:52:49 -0400726
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000727 # Set the ast nodes for the key and value.
728 vars_node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400729
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000730 var_name_node = var_ast.keys[0]
731 var_name_node.lineno += line - 2
732 vars_node.keys.insert(0, var_name_node)
Edward Lesmes3d993812018-04-02 12:52:49 -0400733
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000734 value_node = var_ast.values[0]
735 value_node.lineno += line - 2
736 vars_node.values.insert(0, value_node)
Edward Lesmes3d993812018-04-02 12:52:49 -0400737
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000738 # Update the tokens.
739 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
740 var_tokens = {
741 token[2]: list(token)
742 # Ignore the tokens corresponding to braces and new lines.
743 for token in var_tokens[2:-3]
744 }
Edward Lesmes3d993812018-04-02 12:52:49 -0400745
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000746 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
747 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
Edward Lesmes3d993812018-04-02 12:52:49 -0400748
749
Edward Lesmes6f64a052018-03-20 17:35:49 -0400750def SetVar(gclient_dict, var_name, value):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000751 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
752 raise ValueError(
753 "Can't use SetVar for the given gclient dict. It contains no "
754 "formatting information.")
755 tokens = gclient_dict.tokens
Edward Lesmes6f64a052018-03-20 17:35:49 -0400756
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000757 if 'vars' not in gclient_dict:
758 raise KeyError("vars dict is not defined.")
Edward Lesmes3d993812018-04-02 12:52:49 -0400759
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000760 if var_name not in gclient_dict['vars']:
761 raise ValueError(
762 "%s has not been declared in the vars dict. Consider using AddVar "
763 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400764
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000765 node = gclient_dict['vars'].GetNode(var_name)
766 if node is None:
767 raise ValueError(
768 "The vars entry for %s has no formatting information." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400769
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000770 _UpdateAstString(tokens, node, value)
771 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400772
773
Edward Lemura1e4d482018-12-17 19:01:03 +0000774def _GetVarName(node):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000775 if isinstance(node, ast.Call):
776 return node.args[0].s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000777
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000778 if node.s.endswith('}'):
779 last_brace = node.s.rfind('{')
780 return node.s[last_brace + 1:-1]
781 return None
Edward Lemura1e4d482018-12-17 19:01:03 +0000782
783
Edward Lesmes6f64a052018-03-20 17:35:49 -0400784def SetCIPD(gclient_dict, dep_name, package_name, new_version):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000785 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000786 raise ValueError(
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000787 "Can't use SetCIPD for the given gclient dict. It contains no "
788 "formatting information.")
789 tokens = gclient_dict.tokens
Edward Lemur3c117942020-03-12 17:21:12 +0000790
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000791 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
792 raise KeyError("Could not find any dependency called %s." % dep_name)
793
794 # Find the package with the given name
795 packages = [
796 package for package in gclient_dict['deps'][dep_name]['packages']
797 if package['package'] == package_name
798 ]
799 if len(packages) != 1:
800 raise ValueError(
801 "There must be exactly one package with the given name (%s), "
802 "%s were found." % (package_name, len(packages)))
803
804 # TODO(ehmaldonado): Support Var in package's version.
805 node = packages[0].GetNode('version')
806 if node is None:
807 raise ValueError(
808 "The deps entry for %s:%s has no formatting information." %
809 (dep_name, package_name))
Edward Lemur3c117942020-03-12 17:21:12 +0000810
Edward Lesmes62af4e42018-03-30 18:15:44 -0400811 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000812 raise ValueError(
813 "Unsupported dependency revision format. Please file a bug to the "
814 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400815
816 var_name = _GetVarName(node)
817 if var_name is not None:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000818 SetVar(gclient_dict, var_name, new_version)
Edward Lesmes62af4e42018-03-30 18:15:44 -0400819 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000820 _UpdateAstString(tokens, node, new_version)
821 packages[0].SetNode('version', new_version, node)
Edward Lesmes62af4e42018-03-30 18:15:44 -0400822
Edward Lesmes6f64a052018-03-20 17:35:49 -0400823
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000824def SetRevision(gclient_dict, dep_name, new_revision):
825 def _UpdateRevision(dep_dict, dep_key, new_revision):
826 dep_node = dep_dict.GetNode(dep_key)
827 if dep_node is None:
828 raise ValueError(
829 "The deps entry for %s has no formatting information." %
830 dep_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400831
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000832 node = dep_node
833 if isinstance(node, ast.BinOp):
834 node = node.right
835
836 if isinstance(node, ast.Str):
837 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
838 if token != node.s:
839 raise ValueError(
840 'Can\'t update value for %s. Multiline strings and implicitly '
841 'concatenated strings are not supported.\n'
842 'Consider reformatting the DEPS file.' % dep_key)
843
844 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
845 raise ValueError(
846 "Unsupported dependency revision format. Please file a bug to the "
847 "Infra>SDK component in crbug.com")
848
849 var_name = _GetVarName(node)
850 if var_name is not None:
851 SetVar(gclient_dict, var_name, new_revision)
852 else:
853 if '@' in node.s:
854 # '@' is part of the last string, which we want to modify.
855 # Discard whatever was after the '@' and put the new revision in
856 # its place.
857 new_revision = node.s.split('@')[0] + '@' + new_revision
858 elif '@' not in dep_dict[dep_key]:
859 # '@' is not part of the URL at all. This mean the dependency is
860 # unpinned and we should pin it.
861 new_revision = node.s + '@' + new_revision
862 _UpdateAstString(tokens, node, new_revision)
863 dep_dict.SetNode(dep_key, new_revision, node)
864
865 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
866 raise ValueError(
867 "Can't use SetRevision for the given gclient dict. It contains no "
868 "formatting information.")
869 tokens = gclient_dict.tokens
870
871 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
872 raise KeyError("Could not find any dependency called %s." % dep_name)
873
874 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
875 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
876 else:
877 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400878
879
880def GetVar(gclient_dict, var_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000881 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
882 raise KeyError("Could not find any variable called %s." % var_name)
Edward Lesmes411041f2018-04-05 20:12:55 -0400883
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000884 val = gclient_dict['vars'][var_name]
885 if isinstance(val, ConstantString):
886 return val.value
887 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400888
889
890def GetCIPD(gclient_dict, dep_name, package_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000891 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
892 raise KeyError("Could not find any dependency called %s." % dep_name)
Edward Lesmes411041f2018-04-05 20:12:55 -0400893
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000894 # Find the package with the given name
895 packages = [
896 package for package in gclient_dict['deps'][dep_name]['packages']
897 if package['package'] == package_name
898 ]
899 if len(packages) != 1:
900 raise ValueError(
901 "There must be exactly one package with the given name (%s), "
902 "%s were found." % (package_name, len(packages)))
Edward Lesmes411041f2018-04-05 20:12:55 -0400903
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000904 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400905
906
907def GetRevision(gclient_dict, dep_name):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000908 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
909 suggestions = []
910 if 'deps' in gclient_dict:
911 for key in gclient_dict['deps']:
912 if dep_name in key:
913 suggestions.append(key)
914 if suggestions:
915 raise KeyError(
916 "Could not find any dependency called %s. Did you mean %s" %
917 (dep_name, ' or '.join(suggestions)))
918 raise KeyError("Could not find any dependency called %s." % dep_name)
Edward Lesmes411041f2018-04-05 20:12:55 -0400919
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000920 dep = gclient_dict['deps'][dep_name]
921 if dep is None:
922 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000923
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000924 if isinstance(dep, str):
925 _, _, revision = dep.partition('@')
926 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000927
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000928 if isinstance(dep, collections.abc.Mapping) and 'url' in dep:
929 _, _, revision = dep['url'].partition('@')
930 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000931
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000932 raise ValueError('%s is not a valid git dependency.' % dep_name)