blob: 89e7351e302eb0fa0039813b2809fe3443c4ced5 [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
15
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +000016# git_dependencies migration states. Used within the DEPS file to indicate
17# the current migration state.
18DEPS = 'DEPS'
19SYNC = 'SYNC'
20SUBMODULES = 'SUBMODULES'
21
22
Dirk Prankefdd2cd62020-06-30 23:30:47 +000023class ConstantString(object):
24 def __init__(self, value):
25 self.value = value
26
27 def __format__(self, format_spec):
28 del format_spec
29 return self.value
30
31 def __repr__(self):
32 return "Str('" + self.value + "')"
33
34 def __eq__(self, other):
35 if isinstance(other, ConstantString):
36 return self.value == other.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +000037
38 return self.value == other
Dirk Prankefdd2cd62020-06-30 23:30:47 +000039
40 def __hash__(self):
Bruce Dawson03af44a2022-12-27 19:37:58 +000041 return self.value.__hash__()
Dirk Prankefdd2cd62020-06-30 23:30:47 +000042
43
Gavin Mak65c49b12023-08-24 18:06:42 +000044class _NodeDict(collections.abc.MutableMapping):
Edward Lesmes6f64a052018-03-20 17:35:49 -040045 """Dict-like type that also stores information on AST nodes and tokens."""
Edward Lemurc00ac8d2020-03-04 23:37:57 +000046 def __init__(self, data=None, tokens=None):
47 self.data = collections.OrderedDict(data or [])
Edward Lesmes6f64a052018-03-20 17:35:49 -040048 self.tokens = tokens
49
50 def __str__(self):
Raul Tambreb946b232019-03-26 14:48:46 +000051 return str({k: v[0] for k, v in self.data.items()})
Edward Lesmes6f64a052018-03-20 17:35:49 -040052
Edward Lemura1e4d482018-12-17 19:01:03 +000053 def __repr__(self):
54 return self.__str__()
55
Edward Lesmes6f64a052018-03-20 17:35:49 -040056 def __getitem__(self, key):
57 return self.data[key][0]
58
59 def __setitem__(self, key, value):
60 self.data[key] = (value, None)
61
62 def __delitem__(self, key):
63 del self.data[key]
64
65 def __iter__(self):
66 return iter(self.data)
67
68 def __len__(self):
69 return len(self.data)
70
Edward Lesmes3d993812018-04-02 12:52:49 -040071 def MoveTokens(self, origin, delta):
72 if self.tokens:
73 new_tokens = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000074 for pos, token in self.tokens.items():
Edward Lesmes3d993812018-04-02 12:52:49 -040075 if pos[0] >= origin:
76 pos = (pos[0] + delta, pos[1])
77 token = token[:2] + (pos,) + token[3:]
78 new_tokens[pos] = token
79
80 for value, node in self.data.values():
81 if node.lineno >= origin:
82 node.lineno += delta
83 if isinstance(value, _NodeDict):
84 value.MoveTokens(origin, delta)
85
Edward Lesmes6f64a052018-03-20 17:35:49 -040086 def GetNode(self, key):
87 return self.data[key][1]
88
Edward Lesmes6c24d372018-03-28 12:52:29 -040089 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040090 self.data[key] = (value, node)
91
92
93def _NodeDictSchema(dict_schema):
94 """Validate dict_schema after converting _NodeDict to a regular dict."""
95 def validate(d):
96 schema.Schema(dict_schema).validate(dict(d))
97 return True
98 return validate
99
100
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200101# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400102_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Gavin Mak65c49b12023-08-24 18:06:42 +0000103 schema.Optional(str):
104 schema.Or(
105 None,
106 str,
107 _NodeDictSchema({
108 # Repo and revision to check out under the path
109 # (same as if no dict was used).
110 'url':
111 schema.Or(None, str),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200112
Gavin Mak65c49b12023-08-24 18:06:42 +0000113 # Optional condition string. The dep will only be processed
114 # if the condition evaluates to True.
115 schema.Optional('condition'):
116 str,
117 schema.Optional('dep_type', default='git'):
118 str,
119 }),
120 # CIPD package.
121 _NodeDictSchema({
122 'packages': [_NodeDictSchema({
123 'package': str,
124 'version': str,
125 })],
126 schema.Optional('condition'):
127 str,
128 schema.Optional('dep_type', default='cipd'):
129 str,
130 }),
131 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400132})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200133
Raul Tambreb946b232019-03-26 14:48:46 +0000134_GCLIENT_HOOKS_SCHEMA = [
135 _NodeDictSchema({
136 # Hook action: list of command-line arguments to invoke.
Gavin Mak65c49b12023-08-24 18:06:42 +0000137 'action': [schema.Or(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200138
Raul Tambreb946b232019-03-26 14:48:46 +0000139 # Name of the hook. Doesn't affect operation.
Gavin Mak65c49b12023-08-24 18:06:42 +0000140 schema.Optional('name'):
141 str,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200142
Raul Tambreb946b232019-03-26 14:48:46 +0000143 # Hook pattern (regex). Originally intended to limit some hooks to run
144 # only when files matching the pattern have changed. In practice, with
145 # git, gclient runs all the hooks regardless of this field.
Gavin Mak65c49b12023-08-24 18:06:42 +0000146 schema.Optional('pattern'):
147 str,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200148
Raul Tambreb946b232019-03-26 14:48:46 +0000149 # Working directory where to execute the hook.
Gavin Mak65c49b12023-08-24 18:06:42 +0000150 schema.Optional('cwd'):
151 str,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200152
Raul Tambreb946b232019-03-26 14:48:46 +0000153 # Optional condition string. The hook will only be run
154 # if the condition evaluates to True.
Gavin Mak65c49b12023-08-24 18:06:42 +0000155 schema.Optional('condition'):
156 str,
Raul Tambreb946b232019-03-26 14:48:46 +0000157 })
158]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200159
Raul Tambreb946b232019-03-26 14:48:46 +0000160_GCLIENT_SCHEMA = schema.Schema(
161 _NodeDictSchema({
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000162 # Current state of the git submodule migration.
163 # git_dependencies = [DEPS (default) | SUBMODULES | SYNC]
164 schema.Optional('git_dependencies'):
165 schema.Or(DEPS, SYNC, SUBMODULES),
166
Ayu Ishii09858612020-06-26 18:00:52 +0000167 # List of host names from which dependencies are allowed (allowlist).
Raul Tambreb946b232019-03-26 14:48:46 +0000168 # NOTE: when not present, all hosts are allowed.
169 # NOTE: scoped to current DEPS file, not recursive.
Gavin Mak65c49b12023-08-24 18:06:42 +0000170 schema.Optional('allowed_hosts'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200171
Raul Tambreb946b232019-03-26 14:48:46 +0000172 # Mapping from paths to repo and revision to check out under that path.
173 # Applying this mapping to the on-disk checkout is the main purpose
174 # of gclient, and also why the config file is called DEPS.
175 #
176 # The following functions are allowed:
177 #
178 # Var(): allows variable substitution (either from 'vars' dict below,
179 # or command-line override)
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000180 schema.Optional('deps'):
181 _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200182
Raul Tambreb946b232019-03-26 14:48:46 +0000183 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
184 # Also see 'target_os'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000185 schema.Optional('deps_os'):
186 _NodeDictSchema({
Gavin Mak65c49b12023-08-24 18:06:42 +0000187 schema.Optional(str): _GCLIENT_DEPS_SCHEMA,
Aaron Gableac9b0f32019-04-18 17:38:37 +0000188 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200189
Raul Tambreb946b232019-03-26 14:48:46 +0000190 # Dependency to get gclient_gn_args* settings from. This allows these
191 # values to be set in a recursedeps file, rather than requiring that
192 # they exist in the top-level solution.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000193 schema.Optional('gclient_gn_args_from'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000194 str,
Michael Moss848c86e2018-05-03 16:05:50 -0700195
Raul Tambreb946b232019-03-26 14:48:46 +0000196 # Path to GN args file to write selected variables.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000197 schema.Optional('gclient_gn_args_file'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000198 str,
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200199
Raul Tambreb946b232019-03-26 14:48:46 +0000200 # Subset of variables to write to the GN args file (see above).
Gavin Mak65c49b12023-08-24 18:06:42 +0000201 schema.Optional('gclient_gn_args'): [schema.Optional(str)],
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200202
Raul Tambreb946b232019-03-26 14:48:46 +0000203 # Hooks executed after gclient sync (unless suppressed), or explicitly
204 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
205 # Also see 'pre_deps_hooks'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000206 schema.Optional('hooks'):
207 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200208
Raul Tambreb946b232019-03-26 14:48:46 +0000209 # Similar to 'hooks', also keyed by OS.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000210 schema.Optional('hooks_os'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000211 _NodeDictSchema({schema.Optional(str): _GCLIENT_HOOKS_SCHEMA}),
Scott Grahamc4826742017-05-11 16:59:23 -0700212
Raul Tambreb946b232019-03-26 14:48:46 +0000213 # Rules which #includes are allowed in the directory.
214 # Also see 'skip_child_includes' and 'specific_include_rules'.
Gavin Mak65c49b12023-08-24 18:06:42 +0000215 schema.Optional('include_rules'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200216
Yuki Shiinoa0422642022-08-04 08:14:15 +0000217 # Optionally discards rules from parent directories, similar to
218 # "noparent" in OWNERS files. For example, if
219 # //base/allocator/partition_allocator has "noparent = True" then it
220 # will not inherit rules from //base/DEPS and //base/allocator/DEPS,
221 # forcing each //base/allocator/partition_allocator/{foo,bar,...} to
222 # declare all its dependencies.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000223 schema.Optional('noparent'):
224 bool,
Yuki Shiinoa0422642022-08-04 08:14:15 +0000225
Raul Tambreb946b232019-03-26 14:48:46 +0000226 # Hooks executed before processing DEPS. See 'hooks' for more details.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000227 schema.Optional('pre_deps_hooks'):
228 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200229
Raul Tambreb946b232019-03-26 14:48:46 +0000230 # Recursion limit for nested DEPS.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000231 schema.Optional('recursion'):
232 int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200233
Ayu Ishii09858612020-06-26 18:00:52 +0000234 # Allowlists deps for which recursion should be enabled.
Raul Tambreb946b232019-03-26 14:48:46 +0000235 schema.Optional('recursedeps'): [
Gavin Mak65c49b12023-08-24 18:06:42 +0000236 schema.Optional(schema.Or(str, (str, str), [str, str])),
Raul Tambreb946b232019-03-26 14:48:46 +0000237 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200238
Ayu Ishii09858612020-06-26 18:00:52 +0000239 # Blocklists directories for checking 'include_rules'.
Gavin Mak65c49b12023-08-24 18:06:42 +0000240 schema.Optional('skip_child_includes'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200241
Raul Tambreb946b232019-03-26 14:48:46 +0000242 # Mapping from paths to include rules specific for that path.
243 # See 'include_rules' for more details.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000244 schema.Optional('specific_include_rules'):
Gavin Mak65c49b12023-08-24 18:06:42 +0000245 _NodeDictSchema({schema.Optional(str): [str]}),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200246
Raul Tambreb946b232019-03-26 14:48:46 +0000247 # List of additional OS names to consider when selecting dependencies
248 # from deps_os.
Gavin Mak65c49b12023-08-24 18:06:42 +0000249 schema.Optional('target_os'): [schema.Optional(str)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200250
Raul Tambreb946b232019-03-26 14:48:46 +0000251 # For recursed-upon sub-dependencies, check out their own dependencies
252 # relative to the parent's path, rather than relative to the .gclient
253 # file.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000254 schema.Optional('use_relative_paths'):
255 bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200256
Michael Spang0e99b9b2020-08-12 13:34:48 +0000257 # For recursed-upon sub-dependencies, run their hooks relative to the
258 # parent's path instead of relative to the .gclient file.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000259 schema.Optional('use_relative_hooks'):
260 bool,
Michael Spang0e99b9b2020-08-12 13:34:48 +0000261
Raul Tambreb946b232019-03-26 14:48:46 +0000262 # Variables that can be referenced using Var() - see 'deps'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000263 schema.Optional('vars'):
264 _NodeDictSchema({
Gavin Mak65c49b12023-08-24 18:06:42 +0000265 schema.Optional(str):
266 schema.Or(ConstantString, str, bool),
Aaron Gableac9b0f32019-04-18 17:38:37 +0000267 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000268 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200269
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200270
Edward Lemure05f18d2018-06-08 17:36:53 +0000271def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200272 """Safely evaluates a single expression. Returns the result."""
273 _allowed_names = {'None': None, 'True': True, 'False': False}
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000274 if isinstance(node_or_string, ConstantString):
275 return node_or_string.value
Gavin Mak65c49b12023-08-24 18:06:42 +0000276 if isinstance(node_or_string, str):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200277 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
278 if isinstance(node_or_string, ast.Expression):
279 node_or_string = node_or_string.body
280 def _convert(node):
281 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000282 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000283 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400284 try:
285 return node.s.format(**vars_dict)
286 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000287 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400288 '%s was used as a variable, but was not declared in the vars dict '
289 '(file %r, line %s)' % (
Edward Lemurba1b1f72019-07-27 00:41:59 +0000290 e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200291 elif isinstance(node, ast.Num):
292 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200293 elif isinstance(node, ast.Tuple):
294 return tuple(map(_convert, node.elts))
295 elif isinstance(node, ast.List):
296 return list(map(_convert, node.elts))
297 elif isinstance(node, ast.Dict):
Edward Lemurc00ac8d2020-03-04 23:37:57 +0000298 node_dict = _NodeDict()
299 for key_node, value_node in zip(node.keys, node.values):
300 key = _convert(key_node)
301 if key in node_dict:
302 raise ValueError(
303 'duplicate key in dictionary: %s (file %r, line %s)' % (
304 key, filename, getattr(key_node, 'lineno', '<unknown>')))
305 node_dict.SetNode(key, _convert(value_node), value_node)
306 return node_dict
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200307 elif isinstance(node, ast.Name):
308 if node.id not in _allowed_names:
309 raise ValueError(
310 'invalid name %r (file %r, line %s)' % (
311 node.id, filename, getattr(node, 'lineno', '<unknown>')))
312 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000313 elif not sys.version_info[:2] < (3, 4) and isinstance(
314 node, ast.NameConstant): # Since Python 3.4
315 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200316 elif isinstance(node, ast.Call):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000317 if (not isinstance(node.func, ast.Name) or
318 (node.func.id not in ('Str', 'Var'))):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200319 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000320 'Str and Var are the only allowed functions (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200321 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000322 if node.keywords or getattr(node, 'starargs', None) or getattr(
323 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200324 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000325 '%s takes exactly one argument (file %r, line %s)' % (
326 node.func.id, filename, getattr(node, 'lineno', '<unknown>')))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000327
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000328 if node.func.id == 'Str':
329 if isinstance(node.args[0], ast.Str):
330 return ConstantString(node.args[0].s)
331 raise ValueError('Passed a non-string to Str() (file %r, line%s)' % (
332 filename, getattr(node, 'lineno', '<unknown>')))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000333
334 arg = _convert(node.args[0])
Gavin Mak65c49b12023-08-24 18:06:42 +0000335 if not isinstance(arg, str):
Edward Lesmes9f531292018-03-20 21:27:15 -0400336 raise ValueError(
337 'Var\'s argument must be a variable name (file %r, line %s)' % (
338 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400339 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000340 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400341 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000342 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400343 '%s was used as a variable, but was not declared in the vars dict '
344 '(file %r, line %s)' % (
345 arg, filename, getattr(node, 'lineno', '<unknown>')))
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000346 val = vars_dict[arg]
347 if isinstance(val, ConstantString):
348 val = val.value
349 return val
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200350 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
351 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200352 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
353 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200354 else:
355 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200356 'unexpected AST node: %s %s (file %r, line %s)' % (
357 node, ast.dump(node), filename,
358 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200359 return _convert(node_or_string)
360
361
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000362def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400363 """Safely execs a set of assignments."""
364 def _validate_statement(node, local_scope):
365 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200366 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200367 'unexpected AST node: %s %s (file %r, line %s)' % (
368 node, ast.dump(node), filename,
369 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200370
Edward Lesmes6c24d372018-03-28 12:52:29 -0400371 if len(node.targets) != 1:
372 raise ValueError(
373 'invalid assignment: use exactly one target (file %r, line %s)' % (
374 filename, getattr(node, 'lineno', '<unknown>')))
375
376 target = node.targets[0]
377 if not isinstance(target, ast.Name):
378 raise ValueError(
379 'invalid assignment: target should be a name (file %r, line %s)' % (
380 filename, getattr(node, 'lineno', '<unknown>')))
381 if target.id in local_scope:
382 raise ValueError(
383 'invalid assignment: overrides var %r (file %r, line %s)' % (
384 target.id, filename, getattr(node, 'lineno', '<unknown>')))
385
386 node_or_string = ast.parse(content, filename=filename, mode='exec')
387 if isinstance(node_or_string, ast.Expression):
388 node_or_string = node_or_string.body
389
390 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200391 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200392 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200393 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200394 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200395 filename,
396 getattr(node_or_string, 'lineno', '<unknown>')))
397
Edward Lesmes6c24d372018-03-28 12:52:29 -0400398 statements = {}
399 for statement in node_or_string.body:
400 _validate_statement(statement, statements)
401 statements[statement.targets[0].id] = statement.value
402
Raul Tambreb946b232019-03-26 14:48:46 +0000403 # The tokenized representation needs to end with a newline token, otherwise
404 # untokenization will trigger an assert later on.
405 # In Python 2.7 on Windows we need to ensure the input ends with a newline
406 # for a newline token to be generated.
407 # In other cases a newline token is always generated during tokenization so
408 # this has no effect.
409 # TODO: Remove this workaround after migrating to Python 3.
410 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400411 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000412 token[2]: list(token) for token in tokenize.generate_tokens(
413 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400414 }
Raul Tambreb946b232019-03-26 14:48:46 +0000415
Edward Lesmes6c24d372018-03-28 12:52:29 -0400416 local_scope = _NodeDict({}, tokens)
417
418 # Process vars first, so we can expand variables in the rest of the DEPS file.
419 vars_dict = {}
420 if 'vars' in statements:
421 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000422 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400423 local_scope.SetNode('vars', value, vars_statement)
424 # Update the parsed vars with the overrides, but only if they are already
425 # present (overrides do not introduce new variables).
426 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000427
428 if builtin_vars:
429 vars_dict.update(builtin_vars)
430
431 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000432 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400433
Raul Tambreb946b232019-03-26 14:48:46 +0000434 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000435 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400436 local_scope.SetNode(name, value, node)
437
Edward Lemur67cabcd2020-03-03 19:31:15 +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):
445 """"Standardizes the deps_dict.
446
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 """
452 new_deps_dict = {}
453 for dep_name, dep_info in deps_dict.items():
454 dep_name = dep_name.format(**vars_dict)
Gavin Mak65c49b12023-08-24 18:06:42 +0000455 if not isinstance(dep_info, collections.abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400456 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
460
461
462def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
463 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
464
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 """
469 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, os_name)
474 continue
475
476 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
477 UpdateCondition(dep_info, 'and', os_condition)
478
479 if dep_name in deps_dict:
480 if deps_dict[dep_name]['url'] != dep_info['url']:
481 raise gclient_utils.Error(
482 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
483 'entry (%r).' % (
484 os_name, dep_name, dep_info, deps_dict[dep_name]))
485
486 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
487
488 deps_dict[dep_name] = dep_info
489
490
491def UpdateCondition(info_dict, op, new_condition):
492 """Updates info_dict's condition with |new_condition|.
493
494 An absent value is treated as implicitly True.
495 """
496 curr_condition = info_dict.get('condition')
497 # Easy case: Both are present.
498 if curr_condition and new_condition:
499 info_dict['condition'] = '(%s) %s (%s)' % (
500 curr_condition, op, new_condition)
501 # If |op| == 'and', and at least one condition is present, then use it.
502 elif op == 'and' and (curr_condition or new_condition):
503 info_dict['condition'] = curr_condition or new_condition
504 # Otherwise, no condition should be set
505 elif curr_condition:
506 del info_dict['condition']
507
508
Edward Lemur67cabcd2020-03-03 19:31:15 +0000509def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400510 """Parses DEPS strings.
511
512 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000513 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400514 variable expansion.
515
516 Args:
517 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400518 filename: str. The name of the DEPS file, or a string describing the source
519 of the content, e.g. '<string>', '<unknown>'.
520 vars_override: dict, optional. A dictionary with overrides for the variables
521 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000522 builtin_vars: dict, optional. A dictionary with variables that are provided
523 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400524
525 Returns:
526 A Python dict with the parsed contents of the DEPS file, as specified by the
527 schema above.
528 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000529 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400530
531 vars_dict = result.get('vars', {})
532 if 'deps' in result:
533 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
534
535 if 'deps_os' in result:
536 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000537 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400538 os_deps = _StandardizeDeps(os_deps, vars_dict)
539 _MergeDepsOs(deps, os_deps, os_name)
540 del result['deps_os']
541
542 if 'hooks_os' in result:
543 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000544 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400545 for hook in os_hooks:
546 UpdateCondition(hook, 'and', 'checkout_' + os_name)
547 hooks.extend(os_hooks)
548 del result['hooks_os']
549
550 return result
551
552
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200553def EvaluateCondition(condition, variables, referenced_variables=None):
554 """Safely evaluates a boolean condition. Returns the result."""
555 if not referenced_variables:
556 referenced_variables = set()
557 _allowed_names = {'None': None, 'True': True, 'False': False}
558 main_node = ast.parse(condition, mode='eval')
559 if isinstance(main_node, ast.Expression):
560 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000561 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200562 if isinstance(node, ast.Str):
563 return node.s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000564
565 if isinstance(node, ast.Tuple) and allow_tuple:
Ben Pastenea541b282019-05-24 00:25:12 +0000566 return tuple(map(_convert, node.elts))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000567
568 if isinstance(node, ast.Name):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200569 if node.id in referenced_variables:
570 raise ValueError(
571 'invalid cyclic reference to %r (inside %r)' % (
572 node.id, condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000573
574 if node.id in _allowed_names:
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200575 return _allowed_names[node.id]
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000576
577 if node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200578 value = variables[node.id]
579
580 # Allow using "native" types, without wrapping everything in strings.
581 # Note that schema constraints still apply to variables.
Gavin Mak65c49b12023-08-24 18:06:42 +0000582 if not isinstance(value, str):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200583 return value
584
585 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200586 return EvaluateCondition(
587 variables[node.id],
588 variables,
589 referenced_variables.union([node.id]))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000590
591 # Implicitly convert unrecognized names to strings.
592 # If we want to change this, we'll need to explicitly distinguish
593 # between arguments for GN to be passed verbatim, and ones to
594 # be evaluated.
595 return node.id
596
597 if not sys.version_info[:2] < (3, 4) and isinstance(
Edward Lemurba1b1f72019-07-27 00:41:59 +0000598 node, ast.NameConstant): # Since Python 3.4
599 return node.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000600
601 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000602 bool_values = []
603 for value in node.values:
604 bool_values.append(_convert(value))
605 if not isinstance(bool_values[-1], bool):
606 raise ValueError(
607 'invalid "or" operand %r (inside %r)' % (
608 bool_values[-1], condition))
609 return any(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000610
611 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000612 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(
617 'invalid "and" operand %r (inside %r)' % (
618 bool_values[-1], condition))
619 return all(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000620
621 if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200622 value = _convert(node.operand)
623 if not isinstance(value, bool):
624 raise ValueError(
625 'invalid "not" operand %r (inside %r)' % (value, condition))
626 return not value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000627
628 if isinstance(node, ast.Compare):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200629 if len(node.ops) != 1:
630 raise ValueError(
631 'invalid compare: exactly 1 operator required (inside %r)' % (
632 condition))
633 if len(node.comparators) != 1:
634 raise ValueError(
635 'invalid compare: exactly 1 comparator required (inside %r)' % (
636 condition))
637
638 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000639 right = _convert(
640 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200641
642 if isinstance(node.ops[0], ast.Eq):
643 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700644 if isinstance(node.ops[0], ast.NotEq):
645 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000646 if isinstance(node.ops[0], ast.In):
647 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200648
649 raise ValueError(
650 'unexpected operator: %s %s (inside %r)' % (
651 node.ops[0], ast.dump(node), condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000652
653 raise ValueError(
654 'unexpected AST node: %s %s (inside %r)' % (
655 node, ast.dump(node), condition))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200656 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400657
658
659def RenderDEPSFile(gclient_dict):
660 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000661 # The last token is a newline, which we ensure in Exec() for compatibility.
662 # However tests pass in inputs not ending with a newline and expect the same
663 # back, so for backwards compatibility need to remove that newline character.
664 # TODO: Fix tests to expect the newline
665 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400666
667
668def _UpdateAstString(tokens, node, value):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000669 if isinstance(node, ast.Call):
670 node = node.args[0]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400671 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000672 quote_char = ''
673 if isinstance(node, ast.Str):
674 quote_char = tokens[position][1][0]
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000675 value = value.encode('unicode_escape').decode('utf-8')
Edward Lesmes62af4e42018-03-30 18:15:44 -0400676 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400677 node.s = value
678
679
Edward Lesmes3d993812018-04-02 12:52:49 -0400680def _ShiftLinesInTokens(tokens, delta, start):
681 new_tokens = {}
682 for token in tokens.values():
683 if token[2][0] >= start:
684 token[2] = token[2][0] + delta, token[2][1]
685 token[3] = token[3][0] + delta, token[3][1]
686 new_tokens[token[2]] = token
687 return new_tokens
688
689
690def AddVar(gclient_dict, var_name, value):
691 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
692 raise ValueError(
693 "Can't use SetVar for the given gclient dict. It contains no "
694 "formatting information.")
695
696 if 'vars' not in gclient_dict:
697 raise KeyError("vars dict is not defined.")
698
699 if var_name in gclient_dict['vars']:
700 raise ValueError(
701 "%s has already been declared in the vars dict. Consider using SetVar "
702 "instead." % var_name)
703
704 if not gclient_dict['vars']:
705 raise ValueError('vars dict is empty. This is not yet supported.')
706
Edward Lesmes8d626572018-04-05 17:53:10 -0400707 # We will attempt to add the var right after 'vars = {'.
708 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400709 if node is None:
710 raise ValueError(
711 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400712 line = node.lineno + 1
713
714 # We will try to match the new var's indentation to the next variable.
715 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400716
717 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000718 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400719 var_ast = ast.parse(var_content).body[0].value
720
721 # Set the ast nodes for the key and value.
722 vars_node = gclient_dict.GetNode('vars')
723
724 var_name_node = var_ast.keys[0]
725 var_name_node.lineno += line - 2
726 vars_node.keys.insert(0, var_name_node)
727
728 value_node = var_ast.values[0]
729 value_node.lineno += line - 2
730 vars_node.values.insert(0, value_node)
731
732 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000733 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400734 var_tokens = {
735 token[2]: list(token)
736 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000737 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400738 }
739
740 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
741 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
742
743
Edward Lesmes6f64a052018-03-20 17:35:49 -0400744def SetVar(gclient_dict, var_name, value):
745 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
746 raise ValueError(
747 "Can't use SetVar for the given gclient dict. It contains no "
748 "formatting information.")
749 tokens = gclient_dict.tokens
750
Edward Lesmes3d993812018-04-02 12:52:49 -0400751 if 'vars' not in gclient_dict:
752 raise KeyError("vars dict is not defined.")
753
754 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400755 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400756 "%s has not been declared in the vars dict. Consider using AddVar "
757 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400758
759 node = gclient_dict['vars'].GetNode(var_name)
760 if node is None:
761 raise ValueError(
762 "The vars entry for %s has no formatting information." % var_name)
763
764 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400765 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400766
767
Edward Lemura1e4d482018-12-17 19:01:03 +0000768def _GetVarName(node):
769 if isinstance(node, ast.Call):
770 return node.args[0].s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000771
772 if node.s.endswith('}'):
Edward Lemura1e4d482018-12-17 19:01:03 +0000773 last_brace = node.s.rfind('{')
774 return node.s[last_brace+1:-1]
775 return None
776
777
Edward Lesmes6f64a052018-03-20 17:35:49 -0400778def SetCIPD(gclient_dict, dep_name, package_name, new_version):
779 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
780 raise ValueError(
781 "Can't use SetCIPD for the given gclient dict. It contains no "
782 "formatting information.")
783 tokens = gclient_dict.tokens
784
785 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400786 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400787 "Could not find any dependency called %s." % dep_name)
788
789 # Find the package with the given name
790 packages = [
791 package
792 for package in gclient_dict['deps'][dep_name]['packages']
793 if package['package'] == package_name
794 ]
795 if len(packages) != 1:
796 raise ValueError(
797 "There must be exactly one package with the given name (%s), "
798 "%s were found." % (package_name, len(packages)))
799
800 # TODO(ehmaldonado): Support Var in package's version.
801 node = packages[0].GetNode('version')
802 if node is None:
803 raise ValueError(
804 "The deps entry for %s:%s has no formatting information." %
805 (dep_name, package_name))
806
Edward Lemura1e4d482018-12-17 19:01:03 +0000807 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
808 raise ValueError(
809 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000810 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000811
812 var_name = _GetVarName(node)
813 if var_name is not None:
814 SetVar(gclient_dict, var_name, new_version)
815 else:
816 _UpdateAstString(tokens, node, new_version)
817 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400818
819
Edward Lesmes9f531292018-03-20 21:27:15 -0400820def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400821 def _UpdateRevision(dep_dict, dep_key, new_revision):
822 dep_node = dep_dict.GetNode(dep_key)
823 if dep_node is None:
824 raise ValueError(
825 "The deps entry for %s has no formatting information." % dep_name)
826
827 node = dep_node
828 if isinstance(node, ast.BinOp):
829 node = node.right
830
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000831 if isinstance(node, ast.Str):
832 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
833 if token != node.s:
834 raise ValueError(
835 'Can\'t update value for %s. Multiline strings and implicitly '
836 'concatenated strings are not supported.\n'
837 'Consider reformatting the DEPS file.' % dep_key)
Edward Lemur3c117942020-03-12 17:21:12 +0000838
839
Edward Lesmes62af4e42018-03-30 18:15:44 -0400840 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
841 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000842 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000843 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400844
845 var_name = _GetVarName(node)
846 if var_name is not None:
847 SetVar(gclient_dict, var_name, new_revision)
848 else:
849 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400850 # '@' is part of the last string, which we want to modify. Discard
851 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400852 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400853 elif '@' not in dep_dict[dep_key]:
854 # '@' is not part of the URL at all. This mean the dependency is
855 # unpinned and we should pin it.
856 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400857 _UpdateAstString(tokens, node, new_revision)
858 dep_dict.SetNode(dep_key, new_revision, node)
859
Edward Lesmes6f64a052018-03-20 17:35:49 -0400860 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
861 raise ValueError(
862 "Can't use SetRevision for the given gclient dict. It contains no "
863 "formatting information.")
864 tokens = gclient_dict.tokens
865
866 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400867 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400868 "Could not find any dependency called %s." % dep_name)
869
Edward Lesmes6f64a052018-03-20 17:35:49 -0400870 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400871 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400872 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400873 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400874
875
876def GetVar(gclient_dict, var_name):
877 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
878 raise KeyError(
879 "Could not find any variable called %s." % var_name)
880
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000881 val = gclient_dict['vars'][var_name]
882 if isinstance(val, ConstantString):
883 return val.value
884 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400885
886
887def GetCIPD(gclient_dict, dep_name, package_name):
888 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
889 raise KeyError(
890 "Could not find any dependency called %s." % dep_name)
891
892 # Find the package with the given name
893 packages = [
894 package
895 for package in gclient_dict['deps'][dep_name]['packages']
896 if package['package'] == package_name
897 ]
898 if len(packages) != 1:
899 raise ValueError(
900 "There must be exactly one package with the given name (%s), "
901 "%s were found." % (package_name, len(packages)))
902
Edward Lemura92b9612018-07-03 02:34:32 +0000903 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400904
905
906def GetRevision(gclient_dict, dep_name):
907 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Bruce Dawson03af44a2022-12-27 19:37:58 +0000908 suggestions = []
909 if 'deps' in gclient_dict:
910 for key in gclient_dict['deps']:
911 if dep_name in key:
912 suggestions.append(key)
913 if suggestions:
914 raise KeyError(
915 "Could not find any dependency called %s. Did you mean %s" %
916 (dep_name, ' or '.join(suggestions)))
Edward Lesmes411041f2018-04-05 20:12:55 -0400917 raise KeyError(
918 "Could not find any dependency called %s." % dep_name)
919
920 dep = gclient_dict['deps'][dep_name]
921 if dep is None:
922 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000923
Gavin Mak65c49b12023-08-24 18:06:42 +0000924 if isinstance(dep, str):
Edward Lesmes411041f2018-04-05 20:12:55 -0400925 _, _, revision = dep.partition('@')
926 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000927
Gavin Mak65c49b12023-08-24 18:06:42 +0000928 if isinstance(dep, collections.abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400929 _, _, revision = dep['url'].partition('@')
930 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000931
932 raise ValueError(
933 '%s is not a valid git dependency.' % dep_name)