blob: ac4f49bbb529f758e15b34e49ea7561ad980d706 [file] [log] [blame]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +02001# Copyright 2017 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import ast
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +02006import collections
Edward Lemur16f4bad2018-05-16 16:53:49 -04007import logging
Raul Tambreb946b232019-03-26 14:48:46 +00008import sys
Edward Lesmes6f64a052018-03-20 17:35:49 -04009import tokenize
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +020010
Edward Lemur16f4bad2018-05-16 16:53:49 -040011import gclient_utils
12
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020013from third_party import schema
James Darpinianf994d872019-08-06 18:57:40 +000014from third_party import six
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020015
Edward Lemurba1b1f72019-07-27 00:41:59 +000016if six.PY2:
Raul Tambreb946b232019-03-26 14:48:46 +000017 # We use cStringIO.StringIO because it is equivalent to Py3's io.StringIO.
18 from cStringIO import StringIO
Raul Tambre6693d092020-02-19 20:36:45 +000019 import collections as collections_abc
Raul Tambreb946b232019-03-26 14:48:46 +000020else:
Raul Tambre6693d092020-02-19 20:36:45 +000021 from collections import abc as collections_abc
Raul Tambreb946b232019-03-26 14:48:46 +000022 from io import StringIO
Aaron Gableac9b0f32019-04-18 17:38:37 +000023 # pylint: disable=redefined-builtin
24 basestring = str
25
26
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +000027# git_dependencies migration states. Used within the DEPS file to indicate
28# the current migration state.
29DEPS = 'DEPS'
30SYNC = 'SYNC'
31SUBMODULES = 'SUBMODULES'
32
33
Dirk Prankefdd2cd62020-06-30 23:30:47 +000034class ConstantString(object):
35 def __init__(self, value):
36 self.value = value
37
38 def __format__(self, format_spec):
39 del format_spec
40 return self.value
41
42 def __repr__(self):
43 return "Str('" + self.value + "')"
44
45 def __eq__(self, other):
46 if isinstance(other, ConstantString):
47 return self.value == other.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +000048
49 return self.value == other
Dirk Prankefdd2cd62020-06-30 23:30:47 +000050
51 def __hash__(self):
Bruce Dawson03af44a2022-12-27 19:37:58 +000052 return self.value.__hash__()
Dirk Prankefdd2cd62020-06-30 23:30:47 +000053
54
Raul Tambre6693d092020-02-19 20:36:45 +000055class _NodeDict(collections_abc.MutableMapping):
Edward Lesmes6f64a052018-03-20 17:35:49 -040056 """Dict-like type that also stores information on AST nodes and tokens."""
Edward Lemurc00ac8d2020-03-04 23:37:57 +000057 def __init__(self, data=None, tokens=None):
58 self.data = collections.OrderedDict(data or [])
Edward Lesmes6f64a052018-03-20 17:35:49 -040059 self.tokens = tokens
60
61 def __str__(self):
Raul Tambreb946b232019-03-26 14:48:46 +000062 return str({k: v[0] for k, v in self.data.items()})
Edward Lesmes6f64a052018-03-20 17:35:49 -040063
Edward Lemura1e4d482018-12-17 19:01:03 +000064 def __repr__(self):
65 return self.__str__()
66
Edward Lesmes6f64a052018-03-20 17:35:49 -040067 def __getitem__(self, key):
68 return self.data[key][0]
69
70 def __setitem__(self, key, value):
71 self.data[key] = (value, None)
72
73 def __delitem__(self, key):
74 del self.data[key]
75
76 def __iter__(self):
77 return iter(self.data)
78
79 def __len__(self):
80 return len(self.data)
81
Edward Lesmes3d993812018-04-02 12:52:49 -040082 def MoveTokens(self, origin, delta):
83 if self.tokens:
84 new_tokens = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000085 for pos, token in self.tokens.items():
Edward Lesmes3d993812018-04-02 12:52:49 -040086 if pos[0] >= origin:
87 pos = (pos[0] + delta, pos[1])
88 token = token[:2] + (pos,) + token[3:]
89 new_tokens[pos] = token
90
91 for value, node in self.data.values():
92 if node.lineno >= origin:
93 node.lineno += delta
94 if isinstance(value, _NodeDict):
95 value.MoveTokens(origin, delta)
96
Edward Lesmes6f64a052018-03-20 17:35:49 -040097 def GetNode(self, key):
98 return self.data[key][1]
99
Edward Lesmes6c24d372018-03-28 12:52:29 -0400100 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400101 self.data[key] = (value, node)
102
103
104def _NodeDictSchema(dict_schema):
105 """Validate dict_schema after converting _NodeDict to a regular dict."""
106 def validate(d):
107 schema.Schema(dict_schema).validate(dict(d))
108 return True
109 return validate
110
111
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200112# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -0400113_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +0000114 schema.Optional(basestring):
Raul Tambreb946b232019-03-26 14:48:46 +0000115 schema.Or(
116 None,
Aaron Gableac9b0f32019-04-18 17:38:37 +0000117 basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000118 _NodeDictSchema({
119 # Repo and revision to check out under the path
120 # (same as if no dict was used).
Aaron Gableac9b0f32019-04-18 17:38:37 +0000121 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200122
Raul Tambreb946b232019-03-26 14:48:46 +0000123 # Optional condition string. The dep will only be processed
124 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000125 schema.Optional('condition'): basestring,
126 schema.Optional('dep_type', default='git'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000127 }),
128 # CIPD package.
129 _NodeDictSchema({
130 'packages': [
131 _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +0000132 'package': basestring,
133 'version': basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000134 })
135 ],
Aaron Gableac9b0f32019-04-18 17:38:37 +0000136 schema.Optional('condition'): basestring,
137 schema.Optional('dep_type', default='cipd'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000138 }),
139 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400140})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200141
Raul Tambreb946b232019-03-26 14:48:46 +0000142_GCLIENT_HOOKS_SCHEMA = [
143 _NodeDictSchema({
144 # Hook action: list of command-line arguments to invoke.
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000145 'action': [schema.Or(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200146
Raul Tambreb946b232019-03-26 14:48:46 +0000147 # Name of the hook. Doesn't affect operation.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000148 schema.Optional('name'): basestring,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200149
Raul Tambreb946b232019-03-26 14:48:46 +0000150 # Hook pattern (regex). Originally intended to limit some hooks to run
151 # only when files matching the pattern have changed. In practice, with
152 # git, gclient runs all the hooks regardless of this field.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000153 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200154
Raul Tambreb946b232019-03-26 14:48:46 +0000155 # Working directory where to execute the hook.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000156 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200157
Raul Tambreb946b232019-03-26 14:48:46 +0000158 # Optional condition string. The hook will only be run
159 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000160 schema.Optional('condition'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000161 })
162]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200163
Raul Tambreb946b232019-03-26 14:48:46 +0000164_GCLIENT_SCHEMA = schema.Schema(
165 _NodeDictSchema({
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000166 # Current state of the git submodule migration.
167 # git_dependencies = [DEPS (default) | SUBMODULES | SYNC]
168 schema.Optional('git_dependencies'):
169 schema.Or(DEPS, SYNC, SUBMODULES),
170
Ayu Ishii09858612020-06-26 18:00:52 +0000171 # List of host names from which dependencies are allowed (allowlist).
Raul Tambreb946b232019-03-26 14:48:46 +0000172 # NOTE: when not present, all hosts are allowed.
173 # NOTE: scoped to current DEPS file, not recursive.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000174 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200175
Raul Tambreb946b232019-03-26 14:48:46 +0000176 # Mapping from paths to repo and revision to check out under that path.
177 # Applying this mapping to the on-disk checkout is the main purpose
178 # of gclient, and also why the config file is called DEPS.
179 #
180 # The following functions are allowed:
181 #
182 # Var(): allows variable substitution (either from 'vars' dict below,
183 # or command-line override)
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000184 schema.Optional('deps'):
185 _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200186
Raul Tambreb946b232019-03-26 14:48:46 +0000187 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
188 # Also see 'target_os'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000189 schema.Optional('deps_os'):
190 _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +0000191 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
192 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200193
Raul Tambreb946b232019-03-26 14:48:46 +0000194 # Dependency to get gclient_gn_args* settings from. This allows these
195 # values to be set in a recursedeps file, rather than requiring that
196 # they exist in the top-level solution.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000197 schema.Optional('gclient_gn_args_from'):
198 basestring,
Michael Moss848c86e2018-05-03 16:05:50 -0700199
Raul Tambreb946b232019-03-26 14:48:46 +0000200 # Path to GN args file to write selected variables.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000201 schema.Optional('gclient_gn_args_file'):
202 basestring,
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200203
Raul Tambreb946b232019-03-26 14:48:46 +0000204 # Subset of variables to write to the GN args file (see above).
Aaron Gableac9b0f32019-04-18 17:38:37 +0000205 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200206
Raul Tambreb946b232019-03-26 14:48:46 +0000207 # Hooks executed after gclient sync (unless suppressed), or explicitly
208 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
209 # Also see 'pre_deps_hooks'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000210 schema.Optional('hooks'):
211 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200212
Raul Tambreb946b232019-03-26 14:48:46 +0000213 # Similar to 'hooks', also keyed by OS.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000214 schema.Optional('hooks_os'):
215 _NodeDictSchema({schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA}),
Scott Grahamc4826742017-05-11 16:59:23 -0700216
Raul Tambreb946b232019-03-26 14:48:46 +0000217 # Rules which #includes are allowed in the directory.
218 # Also see 'skip_child_includes' and 'specific_include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000219 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200220
Yuki Shiinoa0422642022-08-04 08:14:15 +0000221 # Optionally discards rules from parent directories, similar to
222 # "noparent" in OWNERS files. For example, if
223 # //base/allocator/partition_allocator has "noparent = True" then it
224 # will not inherit rules from //base/DEPS and //base/allocator/DEPS,
225 # forcing each //base/allocator/partition_allocator/{foo,bar,...} to
226 # declare all its dependencies.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000227 schema.Optional('noparent'):
228 bool,
Yuki Shiinoa0422642022-08-04 08:14:15 +0000229
Raul Tambreb946b232019-03-26 14:48:46 +0000230 # Hooks executed before processing DEPS. See 'hooks' for more details.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000231 schema.Optional('pre_deps_hooks'):
232 _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200233
Raul Tambreb946b232019-03-26 14:48:46 +0000234 # Recursion limit for nested DEPS.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000235 schema.Optional('recursion'):
236 int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200237
Ayu Ishii09858612020-06-26 18:00:52 +0000238 # Allowlists deps for which recursion should be enabled.
Raul Tambreb946b232019-03-26 14:48:46 +0000239 schema.Optional('recursedeps'): [
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000240 schema.Optional(
241 schema.Or(basestring, (basestring, basestring),
242 [basestring, basestring])),
Raul Tambreb946b232019-03-26 14:48:46 +0000243 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200244
Ayu Ishii09858612020-06-26 18:00:52 +0000245 # Blocklists directories for checking 'include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000246 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200247
Raul Tambreb946b232019-03-26 14:48:46 +0000248 # Mapping from paths to include rules specific for that path.
249 # See 'include_rules' for more details.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000250 schema.Optional('specific_include_rules'):
251 _NodeDictSchema({schema.Optional(basestring): [basestring]}),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200252
Raul Tambreb946b232019-03-26 14:48:46 +0000253 # List of additional OS names to consider when selecting dependencies
254 # from deps_os.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000255 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200256
Raul Tambreb946b232019-03-26 14:48:46 +0000257 # For recursed-upon sub-dependencies, check out their own dependencies
258 # relative to the parent's path, rather than relative to the .gclient
259 # file.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000260 schema.Optional('use_relative_paths'):
261 bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200262
Michael Spang0e99b9b2020-08-12 13:34:48 +0000263 # For recursed-upon sub-dependencies, run their hooks relative to the
264 # parent's path instead of relative to the .gclient file.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000265 schema.Optional('use_relative_hooks'):
266 bool,
Michael Spang0e99b9b2020-08-12 13:34:48 +0000267
Raul Tambreb946b232019-03-26 14:48:46 +0000268 # Variables that can be referenced using Var() - see 'deps'.
Aravind Vasudevanb6eaed22023-07-06 20:50:42 +0000269 schema.Optional('vars'):
270 _NodeDictSchema({
271 schema.Optional(basestring):
272 schema.Or(ConstantString, basestring, bool),
Aaron Gableac9b0f32019-04-18 17:38:37 +0000273 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000274 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200275
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200276
Edward Lemure05f18d2018-06-08 17:36:53 +0000277def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200278 """Safely evaluates a single expression. Returns the result."""
279 _allowed_names = {'None': None, 'True': True, 'False': False}
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000280 if isinstance(node_or_string, ConstantString):
281 return node_or_string.value
Aaron Gableac9b0f32019-04-18 17:38:37 +0000282 if isinstance(node_or_string, basestring):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200283 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
284 if isinstance(node_or_string, ast.Expression):
285 node_or_string = node_or_string.body
286 def _convert(node):
287 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000288 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000289 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400290 try:
291 return node.s.format(**vars_dict)
292 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000293 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400294 '%s was used as a variable, but was not declared in the vars dict '
295 '(file %r, line %s)' % (
Edward Lemurba1b1f72019-07-27 00:41:59 +0000296 e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200297 elif isinstance(node, ast.Num):
298 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200299 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):
Edward Lemurc00ac8d2020-03-04 23:37:57 +0000304 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', '<unknown>')))
311 node_dict.SetNode(key, _convert(value_node), value_node)
312 return node_dict
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200313 elif isinstance(node, ast.Name):
314 if node.id not in _allowed_names:
315 raise ValueError(
316 'invalid name %r (file %r, line %s)' % (
317 node.id, filename, getattr(node, 'lineno', '<unknown>')))
318 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000319 elif not sys.version_info[:2] < (3, 4) and isinstance(
320 node, ast.NameConstant): # Since Python 3.4
321 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200322 elif isinstance(node, ast.Call):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000323 if (not isinstance(node.func, ast.Name) or
324 (node.func.id not in ('Str', 'Var'))):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200325 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000326 'Str and Var are the only allowed functions (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200327 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000328 if node.keywords or getattr(node, 'starargs', None) or getattr(
329 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200330 raise ValueError(
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000331 '%s takes exactly one argument (file %r, line %s)' % (
332 node.func.id, filename, getattr(node, 'lineno', '<unknown>')))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000333
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000334 if node.func.id == 'Str':
335 if isinstance(node.args[0], ast.Str):
336 return ConstantString(node.args[0].s)
337 raise ValueError('Passed a non-string to Str() (file %r, line%s)' % (
338 filename, getattr(node, 'lineno', '<unknown>')))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000339
340 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000341 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400342 raise ValueError(
343 'Var\'s argument must be a variable name (file %r, line %s)' % (
344 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400345 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000346 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400347 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000348 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400349 '%s was used as a variable, but was not declared in the vars dict '
350 '(file %r, line %s)' % (
351 arg, filename, getattr(node, 'lineno', '<unknown>')))
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000352 val = vars_dict[arg]
353 if isinstance(val, ConstantString):
354 val = val.value
355 return val
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200356 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
357 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200358 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
359 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200360 else:
361 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200362 'unexpected AST node: %s %s (file %r, line %s)' % (
363 node, ast.dump(node), filename,
364 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200365 return _convert(node_or_string)
366
367
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000368def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400369 """Safely execs a set of assignments."""
370 def _validate_statement(node, local_scope):
371 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200372 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200373 'unexpected AST node: %s %s (file %r, line %s)' % (
374 node, ast.dump(node), filename,
375 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200376
Edward Lesmes6c24d372018-03-28 12:52:29 -0400377 if len(node.targets) != 1:
378 raise ValueError(
379 'invalid assignment: use exactly one target (file %r, line %s)' % (
380 filename, getattr(node, 'lineno', '<unknown>')))
381
382 target = node.targets[0]
383 if not isinstance(target, ast.Name):
384 raise ValueError(
385 'invalid assignment: target should be a name (file %r, line %s)' % (
386 filename, getattr(node, 'lineno', '<unknown>')))
387 if target.id in local_scope:
388 raise ValueError(
389 'invalid assignment: overrides var %r (file %r, line %s)' % (
390 target.id, filename, getattr(node, 'lineno', '<unknown>')))
391
392 node_or_string = ast.parse(content, filename=filename, mode='exec')
393 if isinstance(node_or_string, ast.Expression):
394 node_or_string = node_or_string.body
395
396 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200397 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200398 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200399 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200400 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200401 filename,
402 getattr(node_or_string, 'lineno', '<unknown>')))
403
Edward Lesmes6c24d372018-03-28 12:52:29 -0400404 statements = {}
405 for statement in node_or_string.body:
406 _validate_statement(statement, statements)
407 statements[statement.targets[0].id] = statement.value
408
Raul Tambreb946b232019-03-26 14:48:46 +0000409 # The tokenized representation needs to end with a newline token, otherwise
410 # untokenization will trigger an assert later on.
411 # In Python 2.7 on Windows we need to ensure the input ends with a newline
412 # for a newline token to be generated.
413 # In other cases a newline token is always generated during tokenization so
414 # this has no effect.
415 # TODO: Remove this workaround after migrating to Python 3.
416 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400417 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000418 token[2]: list(token) for token in tokenize.generate_tokens(
419 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400420 }
Raul Tambreb946b232019-03-26 14:48:46 +0000421
Edward Lesmes6c24d372018-03-28 12:52:29 -0400422 local_scope = _NodeDict({}, tokens)
423
424 # Process vars first, so we can expand variables in the rest of the DEPS file.
425 vars_dict = {}
426 if 'vars' in statements:
427 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000428 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400429 local_scope.SetNode('vars', value, vars_statement)
430 # Update the parsed vars with the overrides, but only if they are already
431 # present (overrides do not introduce new variables).
432 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000433
434 if builtin_vars:
435 vars_dict.update(builtin_vars)
436
437 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000438 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400439
Raul Tambreb946b232019-03-26 14:48:46 +0000440 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000441 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400442 local_scope.SetNode(name, value, node)
443
Edward Lemur67cabcd2020-03-03 19:31:15 +0000444 try:
445 return _GCLIENT_SCHEMA.validate(local_scope)
446 except schema.SchemaError as e:
447 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400448
449
Edward Lemur16f4bad2018-05-16 16:53:49 -0400450def _StandardizeDeps(deps_dict, vars_dict):
451 """"Standardizes the deps_dict.
452
453 For each dependency:
454 - Expands the variable in the dependency name.
455 - Ensures the dependency is a dictionary.
456 - Set's the 'dep_type' to be 'git' by default.
457 """
458 new_deps_dict = {}
459 for dep_name, dep_info in deps_dict.items():
460 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000461 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400462 dep_info = {'url': dep_info}
463 dep_info.setdefault('dep_type', 'git')
464 new_deps_dict[dep_name] = dep_info
465 return new_deps_dict
466
467
468def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
469 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
470
471 The dependencies in os_deps_dict are transformed into conditional dependencies
472 using |'checkout_' + os_name|.
473 If the dependency is already present, the URL and revision must coincide.
474 """
475 for dep_name, dep_info in os_deps_dict.items():
476 # Make this condition very visible, so it's not a silent failure.
477 # It's unclear how to support None override in deps_os.
478 if dep_info['url'] is None:
479 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
480 continue
481
482 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
483 UpdateCondition(dep_info, 'and', os_condition)
484
485 if dep_name in deps_dict:
486 if deps_dict[dep_name]['url'] != dep_info['url']:
487 raise gclient_utils.Error(
488 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
489 'entry (%r).' % (
490 os_name, dep_name, dep_info, deps_dict[dep_name]))
491
492 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
493
494 deps_dict[dep_name] = dep_info
495
496
497def UpdateCondition(info_dict, op, new_condition):
498 """Updates info_dict's condition with |new_condition|.
499
500 An absent value is treated as implicitly True.
501 """
502 curr_condition = info_dict.get('condition')
503 # Easy case: Both are present.
504 if curr_condition and new_condition:
505 info_dict['condition'] = '(%s) %s (%s)' % (
506 curr_condition, op, new_condition)
507 # If |op| == 'and', and at least one condition is present, then use it.
508 elif op == 'and' and (curr_condition or new_condition):
509 info_dict['condition'] = curr_condition or new_condition
510 # Otherwise, no condition should be set
511 elif curr_condition:
512 del info_dict['condition']
513
514
Edward Lemur67cabcd2020-03-03 19:31:15 +0000515def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400516 """Parses DEPS strings.
517
518 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000519 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400520 variable expansion.
521
522 Args:
523 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400524 filename: str. The name of the DEPS file, or a string describing the source
525 of the content, e.g. '<string>', '<unknown>'.
526 vars_override: dict, optional. A dictionary with overrides for the variables
527 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000528 builtin_vars: dict, optional. A dictionary with variables that are provided
529 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400530
531 Returns:
532 A Python dict with the parsed contents of the DEPS file, as specified by the
533 schema above.
534 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000535 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400536
537 vars_dict = result.get('vars', {})
538 if 'deps' in result:
539 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
540
541 if 'deps_os' in result:
542 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000543 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400544 os_deps = _StandardizeDeps(os_deps, vars_dict)
545 _MergeDepsOs(deps, os_deps, os_name)
546 del result['deps_os']
547
548 if 'hooks_os' in result:
549 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000550 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400551 for hook in os_hooks:
552 UpdateCondition(hook, 'and', 'checkout_' + os_name)
553 hooks.extend(os_hooks)
554 del result['hooks_os']
555
556 return result
557
558
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200559def EvaluateCondition(condition, variables, referenced_variables=None):
560 """Safely evaluates a boolean condition. Returns the result."""
561 if not referenced_variables:
562 referenced_variables = set()
563 _allowed_names = {'None': None, 'True': True, 'False': False}
564 main_node = ast.parse(condition, mode='eval')
565 if isinstance(main_node, ast.Expression):
566 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000567 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200568 if isinstance(node, ast.Str):
569 return node.s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000570
571 if isinstance(node, ast.Tuple) and allow_tuple:
Ben Pastenea541b282019-05-24 00:25:12 +0000572 return tuple(map(_convert, node.elts))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000573
574 if isinstance(node, ast.Name):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200575 if node.id in referenced_variables:
576 raise ValueError(
577 'invalid cyclic reference to %r (inside %r)' % (
578 node.id, condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000579
580 if node.id in _allowed_names:
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200581 return _allowed_names[node.id]
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000582
583 if node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200584 value = variables[node.id]
585
586 # Allow using "native" types, without wrapping everything in strings.
587 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000588 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200589 return value
590
591 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200592 return EvaluateCondition(
593 variables[node.id],
594 variables,
595 referenced_variables.union([node.id]))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000596
597 # Implicitly convert unrecognized names to strings.
598 # If we want to change this, we'll need to explicitly distinguish
599 # between arguments for GN to be passed verbatim, and ones to
600 # be evaluated.
601 return node.id
602
603 if not sys.version_info[:2] < (3, 4) and isinstance(
Edward Lemurba1b1f72019-07-27 00:41:59 +0000604 node, ast.NameConstant): # Since Python 3.4
605 return node.value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000606
607 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000608 bool_values = []
609 for value in node.values:
610 bool_values.append(_convert(value))
611 if not isinstance(bool_values[-1], bool):
612 raise ValueError(
613 'invalid "or" operand %r (inside %r)' % (
614 bool_values[-1], condition))
615 return any(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000616
617 if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000618 bool_values = []
619 for value in node.values:
620 bool_values.append(_convert(value))
621 if not isinstance(bool_values[-1], bool):
622 raise ValueError(
623 'invalid "and" operand %r (inside %r)' % (
624 bool_values[-1], condition))
625 return all(bool_values)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000626
627 if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200628 value = _convert(node.operand)
629 if not isinstance(value, bool):
630 raise ValueError(
631 'invalid "not" operand %r (inside %r)' % (value, condition))
632 return not value
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000633
634 if isinstance(node, ast.Compare):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200635 if len(node.ops) != 1:
636 raise ValueError(
637 'invalid compare: exactly 1 operator required (inside %r)' % (
638 condition))
639 if len(node.comparators) != 1:
640 raise ValueError(
641 'invalid compare: exactly 1 comparator required (inside %r)' % (
642 condition))
643
644 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000645 right = _convert(
646 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200647
648 if isinstance(node.ops[0], ast.Eq):
649 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700650 if isinstance(node.ops[0], ast.NotEq):
651 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000652 if isinstance(node.ops[0], ast.In):
653 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200654
655 raise ValueError(
656 'unexpected operator: %s %s (inside %r)' % (
657 node.ops[0], ast.dump(node), condition))
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000658
659 raise ValueError(
660 'unexpected AST node: %s %s (inside %r)' % (
661 node, ast.dump(node), condition))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200662 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400663
664
665def RenderDEPSFile(gclient_dict):
666 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000667 # 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 character.
670 # 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):
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000675 if isinstance(node, ast.Call):
676 node = node.args[0]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400677 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000678 quote_char = ''
679 if isinstance(node, ast.Str):
680 quote_char = tokens[position][1][0]
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000681 value = value.encode('unicode_escape').decode('utf-8')
Edward Lesmes62af4e42018-03-30 18:15:44 -0400682 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400683 node.s = value
684
685
Edward Lesmes3d993812018-04-02 12:52:49 -0400686def _ShiftLinesInTokens(tokens, delta, start):
687 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
694
695
696def AddVar(gclient_dict, var_name, value):
697 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.")
701
702 if 'vars' not in gclient_dict:
703 raise KeyError("vars dict is not defined.")
704
705 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)
709
710 if not gclient_dict['vars']:
711 raise ValueError('vars dict is empty. This is not yet supported.')
712
Edward Lesmes8d626572018-04-05 17:53:10 -0400713 # We will attempt to add the var right after 'vars = {'.
714 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400715 if node is None:
716 raise ValueError(
717 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400718 line = node.lineno + 1
719
720 # 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
723 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000724 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400725 var_ast = ast.parse(var_content).body[0].value
726
727 # Set the ast nodes for the key and value.
728 vars_node = gclient_dict.GetNode('vars')
729
730 var_name_node = var_ast.keys[0]
731 var_name_node.lineno += line - 2
732 vars_node.keys.insert(0, var_name_node)
733
734 value_node = var_ast.values[0]
735 value_node.lineno += line - 2
736 vars_node.values.insert(0, value_node)
737
738 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000739 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400740 var_tokens = {
741 token[2]: list(token)
742 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000743 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400744 }
745
746 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
747 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
748
749
Edward Lesmes6f64a052018-03-20 17:35:49 -0400750def SetVar(gclient_dict, var_name, value):
751 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
756
Edward Lesmes3d993812018-04-02 12:52:49 -0400757 if 'vars' not in gclient_dict:
758 raise KeyError("vars dict is not defined.")
759
760 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400761 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400762 "%s has not been declared in the vars dict. Consider using AddVar "
763 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400764
765 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)
769
770 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400771 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):
775 if isinstance(node, ast.Call):
776 return node.args[0].s
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000777
778 if node.s.endswith('}'):
Edward Lemura1e4d482018-12-17 19:01:03 +0000779 last_brace = node.s.rfind('{')
780 return node.s[last_brace+1:-1]
781 return None
782
783
Edward Lesmes6f64a052018-03-20 17:35:49 -0400784def SetCIPD(gclient_dict, dep_name, package_name, new_version):
785 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
786 raise ValueError(
787 "Can't use SetCIPD for the given gclient dict. It contains no "
788 "formatting information.")
789 tokens = gclient_dict.tokens
790
791 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400792 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400793 "Could not find any dependency called %s." % dep_name)
794
795 # Find the package with the given name
796 packages = [
797 package
798 for package in gclient_dict['deps'][dep_name]['packages']
799 if package['package'] == package_name
800 ]
801 if len(packages) != 1:
802 raise ValueError(
803 "There must be exactly one package with the given name (%s), "
804 "%s were found." % (package_name, len(packages)))
805
806 # TODO(ehmaldonado): Support Var in package's version.
807 node = packages[0].GetNode('version')
808 if node is None:
809 raise ValueError(
810 "The deps entry for %s:%s has no formatting information." %
811 (dep_name, package_name))
812
Edward Lemura1e4d482018-12-17 19:01:03 +0000813 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
814 raise ValueError(
815 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000816 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000817
818 var_name = _GetVarName(node)
819 if var_name is not None:
820 SetVar(gclient_dict, var_name, new_version)
821 else:
822 _UpdateAstString(tokens, node, new_version)
823 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400824
825
Edward Lesmes9f531292018-03-20 21:27:15 -0400826def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400827 def _UpdateRevision(dep_dict, dep_key, new_revision):
828 dep_node = dep_dict.GetNode(dep_key)
829 if dep_node is None:
830 raise ValueError(
831 "The deps entry for %s has no formatting information." % dep_name)
832
833 node = dep_node
834 if isinstance(node, ast.BinOp):
835 node = node.right
836
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000837 if isinstance(node, ast.Str):
838 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
839 if token != node.s:
840 raise ValueError(
841 'Can\'t update value for %s. Multiline strings and implicitly '
842 'concatenated strings are not supported.\n'
843 'Consider reformatting the DEPS file.' % dep_key)
Edward Lemur3c117942020-03-12 17:21:12 +0000844
845
Edward Lesmes62af4e42018-03-30 18:15:44 -0400846 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
847 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000848 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000849 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400850
851 var_name = _GetVarName(node)
852 if var_name is not None:
853 SetVar(gclient_dict, var_name, new_revision)
854 else:
855 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400856 # '@' is part of the last string, which we want to modify. Discard
857 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400858 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400859 elif '@' not in dep_dict[dep_key]:
860 # '@' is not part of the URL at all. This mean the dependency is
861 # unpinned and we should pin it.
862 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400863 _UpdateAstString(tokens, node, new_revision)
864 dep_dict.SetNode(dep_key, new_revision, node)
865
Edward Lesmes6f64a052018-03-20 17:35:49 -0400866 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
867 raise ValueError(
868 "Can't use SetRevision for the given gclient dict. It contains no "
869 "formatting information.")
870 tokens = gclient_dict.tokens
871
872 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400873 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400874 "Could not find any dependency called %s." % dep_name)
875
Edward Lesmes6f64a052018-03-20 17:35:49 -0400876 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400877 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400878 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400879 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400880
881
882def GetVar(gclient_dict, var_name):
883 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
884 raise KeyError(
885 "Could not find any variable called %s." % var_name)
886
Dirk Prankefdd2cd62020-06-30 23:30:47 +0000887 val = gclient_dict['vars'][var_name]
888 if isinstance(val, ConstantString):
889 return val.value
890 return val
Edward Lesmes411041f2018-04-05 20:12:55 -0400891
892
893def GetCIPD(gclient_dict, dep_name, package_name):
894 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
895 raise KeyError(
896 "Could not find any dependency called %s." % dep_name)
897
898 # Find the package with the given name
899 packages = [
900 package
901 for package in gclient_dict['deps'][dep_name]['packages']
902 if package['package'] == package_name
903 ]
904 if len(packages) != 1:
905 raise ValueError(
906 "There must be exactly one package with the given name (%s), "
907 "%s were found." % (package_name, len(packages)))
908
Edward Lemura92b9612018-07-03 02:34:32 +0000909 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400910
911
912def GetRevision(gclient_dict, dep_name):
913 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Bruce Dawson03af44a2022-12-27 19:37:58 +0000914 suggestions = []
915 if 'deps' in gclient_dict:
916 for key in gclient_dict['deps']:
917 if dep_name in key:
918 suggestions.append(key)
919 if suggestions:
920 raise KeyError(
921 "Could not find any dependency called %s. Did you mean %s" %
922 (dep_name, ' or '.join(suggestions)))
Edward Lesmes411041f2018-04-05 20:12:55 -0400923 raise KeyError(
924 "Could not find any dependency called %s." % dep_name)
925
926 dep = gclient_dict['deps'][dep_name]
927 if dep is None:
928 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000929
930 if isinstance(dep, basestring):
Edward Lesmes411041f2018-04-05 20:12:55 -0400931 _, _, revision = dep.partition('@')
932 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000933
934 if isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400935 _, _, revision = dep['url'].partition('@')
936 return revision or None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000937
938 raise ValueError(
939 '%s is not a valid git dependency.' % dep_name)