blob: a6dd03b6a05d79f67ad4e01a36aaad79abce14b9 [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
Raul Tambre6693d092020-02-19 20:36:45 +000027class _NodeDict(collections_abc.MutableMapping):
Edward Lesmes6f64a052018-03-20 17:35:49 -040028 """Dict-like type that also stores information on AST nodes and tokens."""
Edward Lemurc00ac8d2020-03-04 23:37:57 +000029 def __init__(self, data=None, tokens=None):
30 self.data = collections.OrderedDict(data or [])
Edward Lesmes6f64a052018-03-20 17:35:49 -040031 self.tokens = tokens
32
33 def __str__(self):
Raul Tambreb946b232019-03-26 14:48:46 +000034 return str({k: v[0] for k, v in self.data.items()})
Edward Lesmes6f64a052018-03-20 17:35:49 -040035
Edward Lemura1e4d482018-12-17 19:01:03 +000036 def __repr__(self):
37 return self.__str__()
38
Edward Lesmes6f64a052018-03-20 17:35:49 -040039 def __getitem__(self, key):
40 return self.data[key][0]
41
42 def __setitem__(self, key, value):
43 self.data[key] = (value, None)
44
45 def __delitem__(self, key):
46 del self.data[key]
47
48 def __iter__(self):
49 return iter(self.data)
50
51 def __len__(self):
52 return len(self.data)
53
Edward Lesmes3d993812018-04-02 12:52:49 -040054 def MoveTokens(self, origin, delta):
55 if self.tokens:
56 new_tokens = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +000057 for pos, token in self.tokens.items():
Edward Lesmes3d993812018-04-02 12:52:49 -040058 if pos[0] >= origin:
59 pos = (pos[0] + delta, pos[1])
60 token = token[:2] + (pos,) + token[3:]
61 new_tokens[pos] = token
62
63 for value, node in self.data.values():
64 if node.lineno >= origin:
65 node.lineno += delta
66 if isinstance(value, _NodeDict):
67 value.MoveTokens(origin, delta)
68
Edward Lesmes6f64a052018-03-20 17:35:49 -040069 def GetNode(self, key):
70 return self.data[key][1]
71
Edward Lesmes6c24d372018-03-28 12:52:29 -040072 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040073 self.data[key] = (value, node)
74
75
76def _NodeDictSchema(dict_schema):
77 """Validate dict_schema after converting _NodeDict to a regular dict."""
78 def validate(d):
79 schema.Schema(dict_schema).validate(dict(d))
80 return True
81 return validate
82
83
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020084# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -040085_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +000086 schema.Optional(basestring):
Raul Tambreb946b232019-03-26 14:48:46 +000087 schema.Or(
88 None,
Aaron Gableac9b0f32019-04-18 17:38:37 +000089 basestring,
Raul Tambreb946b232019-03-26 14:48:46 +000090 _NodeDictSchema({
91 # Repo and revision to check out under the path
92 # (same as if no dict was used).
Aaron Gableac9b0f32019-04-18 17:38:37 +000093 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020094
Raul Tambreb946b232019-03-26 14:48:46 +000095 # Optional condition string. The dep will only be processed
96 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +000097 schema.Optional('condition'): basestring,
98 schema.Optional('dep_type', default='git'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +000099 }),
100 # CIPD package.
101 _NodeDictSchema({
102 'packages': [
103 _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +0000104 'package': basestring,
105 'version': basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000106 })
107 ],
Aaron Gableac9b0f32019-04-18 17:38:37 +0000108 schema.Optional('condition'): basestring,
109 schema.Optional('dep_type', default='cipd'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000110 }),
111 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400112})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200113
Raul Tambreb946b232019-03-26 14:48:46 +0000114_GCLIENT_HOOKS_SCHEMA = [
115 _NodeDictSchema({
116 # Hook action: list of command-line arguments to invoke.
Dirk Prankeac93e6d2020-06-29 18:42:26 +0000117 'action': [basestring],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200118
Raul Tambreb946b232019-03-26 14:48:46 +0000119 # Name of the hook. Doesn't affect operation.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000120 schema.Optional('name'): basestring,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200121
Raul Tambreb946b232019-03-26 14:48:46 +0000122 # Hook pattern (regex). Originally intended to limit some hooks to run
123 # only when files matching the pattern have changed. In practice, with
124 # git, gclient runs all the hooks regardless of this field.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000125 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200126
Raul Tambreb946b232019-03-26 14:48:46 +0000127 # Working directory where to execute the hook.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000128 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200129
Raul Tambreb946b232019-03-26 14:48:46 +0000130 # Optional condition string. The hook will only be run
131 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000132 schema.Optional('condition'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000133 })
134]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200135
Raul Tambreb946b232019-03-26 14:48:46 +0000136_GCLIENT_SCHEMA = schema.Schema(
137 _NodeDictSchema({
Ayu Ishii09858612020-06-26 18:00:52 +0000138 # List of host names from which dependencies are allowed (allowlist).
Raul Tambreb946b232019-03-26 14:48:46 +0000139 # NOTE: when not present, all hosts are allowed.
140 # NOTE: scoped to current DEPS file, not recursive.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000141 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200142
Raul Tambreb946b232019-03-26 14:48:46 +0000143 # Mapping from paths to repo and revision to check out under that path.
144 # Applying this mapping to the on-disk checkout is the main purpose
145 # of gclient, and also why the config file is called DEPS.
146 #
147 # The following functions are allowed:
148 #
149 # Var(): allows variable substitution (either from 'vars' dict below,
150 # or command-line override)
Aaron Gableac9b0f32019-04-18 17:38:37 +0000151 schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200152
Raul Tambreb946b232019-03-26 14:48:46 +0000153 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
154 # Also see 'target_os'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000155 schema.Optional('deps_os'): _NodeDictSchema({
156 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
157 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200158
Raul Tambreb946b232019-03-26 14:48:46 +0000159 # Dependency to get gclient_gn_args* settings from. This allows these
160 # values to be set in a recursedeps file, rather than requiring that
161 # they exist in the top-level solution.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000162 schema.Optional('gclient_gn_args_from'): basestring,
Michael Moss848c86e2018-05-03 16:05:50 -0700163
Raul Tambreb946b232019-03-26 14:48:46 +0000164 # Path to GN args file to write selected variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000165 schema.Optional('gclient_gn_args_file'): basestring,
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200166
Raul Tambreb946b232019-03-26 14:48:46 +0000167 # Subset of variables to write to the GN args file (see above).
Aaron Gableac9b0f32019-04-18 17:38:37 +0000168 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200169
Raul Tambreb946b232019-03-26 14:48:46 +0000170 # Hooks executed after gclient sync (unless suppressed), or explicitly
171 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
172 # Also see 'pre_deps_hooks'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000173 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200174
Raul Tambreb946b232019-03-26 14:48:46 +0000175 # Similar to 'hooks', also keyed by OS.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000176 schema.Optional('hooks_os'): _NodeDictSchema({
177 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
178 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700179
Raul Tambreb946b232019-03-26 14:48:46 +0000180 # Rules which #includes are allowed in the directory.
181 # Also see 'skip_child_includes' and 'specific_include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000182 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200183
Raul Tambreb946b232019-03-26 14:48:46 +0000184 # Hooks executed before processing DEPS. See 'hooks' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000185 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200186
Raul Tambreb946b232019-03-26 14:48:46 +0000187 # Recursion limit for nested DEPS.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000188 schema.Optional('recursion'): int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200189
Ayu Ishii09858612020-06-26 18:00:52 +0000190 # Allowlists deps for which recursion should be enabled.
Raul Tambreb946b232019-03-26 14:48:46 +0000191 schema.Optional('recursedeps'): [
Aaron Gableac9b0f32019-04-18 17:38:37 +0000192 schema.Optional(schema.Or(
193 basestring,
194 (basestring, basestring),
195 [basestring, basestring]
196 )),
Raul Tambreb946b232019-03-26 14:48:46 +0000197 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200198
Ayu Ishii09858612020-06-26 18:00:52 +0000199 # Blocklists directories for checking 'include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000200 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200201
Raul Tambreb946b232019-03-26 14:48:46 +0000202 # Mapping from paths to include rules specific for that path.
203 # See 'include_rules' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000204 schema.Optional('specific_include_rules'): _NodeDictSchema({
205 schema.Optional(basestring): [basestring]
206 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200207
Raul Tambreb946b232019-03-26 14:48:46 +0000208 # List of additional OS names to consider when selecting dependencies
209 # from deps_os.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000210 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200211
Raul Tambreb946b232019-03-26 14:48:46 +0000212 # For recursed-upon sub-dependencies, check out their own dependencies
213 # relative to the parent's path, rather than relative to the .gclient
214 # file.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000215 schema.Optional('use_relative_paths'): bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200216
Raul Tambreb946b232019-03-26 14:48:46 +0000217 # For recursed-upon sub-dependencies, run their hooks relative to the
218 # parent's path instead of relative to the .gclient file.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000219 schema.Optional('use_relative_hooks'): bool,
Corentin Walleza68660d2018-09-10 17:33:24 +0000220
Raul Tambreb946b232019-03-26 14:48:46 +0000221 # Variables that can be referenced using Var() - see 'deps'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000222 schema.Optional('vars'): _NodeDictSchema({
Dirk Prankeac93e6d2020-06-29 18:42:26 +0000223 schema.Optional(basestring): schema.Or(basestring, bool),
Aaron Gableac9b0f32019-04-18 17:38:37 +0000224 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000225 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200226
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200227
Edward Lemure05f18d2018-06-08 17:36:53 +0000228def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200229 """Safely evaluates a single expression. Returns the result."""
230 _allowed_names = {'None': None, 'True': True, 'False': False}
Aaron Gableac9b0f32019-04-18 17:38:37 +0000231 if isinstance(node_or_string, basestring):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200232 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
233 if isinstance(node_or_string, ast.Expression):
234 node_or_string = node_or_string.body
235 def _convert(node):
236 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000237 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000238 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400239 try:
240 return node.s.format(**vars_dict)
241 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000242 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400243 '%s was used as a variable, but was not declared in the vars dict '
244 '(file %r, line %s)' % (
Edward Lemurba1b1f72019-07-27 00:41:59 +0000245 e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200246 elif isinstance(node, ast.Num):
247 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200248 elif isinstance(node, ast.Tuple):
249 return tuple(map(_convert, node.elts))
250 elif isinstance(node, ast.List):
251 return list(map(_convert, node.elts))
252 elif isinstance(node, ast.Dict):
Edward Lemurc00ac8d2020-03-04 23:37:57 +0000253 node_dict = _NodeDict()
254 for key_node, value_node in zip(node.keys, node.values):
255 key = _convert(key_node)
256 if key in node_dict:
257 raise ValueError(
258 'duplicate key in dictionary: %s (file %r, line %s)' % (
259 key, filename, getattr(key_node, 'lineno', '<unknown>')))
260 node_dict.SetNode(key, _convert(value_node), value_node)
261 return node_dict
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200262 elif isinstance(node, ast.Name):
263 if node.id not in _allowed_names:
264 raise ValueError(
265 'invalid name %r (file %r, line %s)' % (
266 node.id, filename, getattr(node, 'lineno', '<unknown>')))
267 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000268 elif not sys.version_info[:2] < (3, 4) and isinstance(
269 node, ast.NameConstant): # Since Python 3.4
270 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200271 elif isinstance(node, ast.Call):
Dirk Prankeac93e6d2020-06-29 18:42:26 +0000272 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200273 raise ValueError(
Dirk Prankeac93e6d2020-06-29 18:42:26 +0000274 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200275 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000276 if node.keywords or getattr(node, 'starargs', None) or getattr(
277 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200278 raise ValueError(
Dirk Prankeac93e6d2020-06-29 18:42:26 +0000279 'Var takes exactly one argument (file %r, line %s)' % (
280 filename, getattr(node, 'lineno', '<unknown>')))
281 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000282 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400283 raise ValueError(
284 'Var\'s argument must be a variable name (file %r, line %s)' % (
285 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400286 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000287 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400288 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000289 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400290 '%s was used as a variable, but was not declared in the vars dict '
291 '(file %r, line %s)' % (
292 arg, filename, getattr(node, 'lineno', '<unknown>')))
Dirk Prankeac93e6d2020-06-29 18:42:26 +0000293 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200294 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
295 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200296 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
297 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200298 else:
299 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200300 'unexpected AST node: %s %s (file %r, line %s)' % (
301 node, ast.dump(node), filename,
302 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200303 return _convert(node_or_string)
304
305
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000306def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400307 """Safely execs a set of assignments."""
308 def _validate_statement(node, local_scope):
309 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200310 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200311 'unexpected AST node: %s %s (file %r, line %s)' % (
312 node, ast.dump(node), filename,
313 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200314
Edward Lesmes6c24d372018-03-28 12:52:29 -0400315 if len(node.targets) != 1:
316 raise ValueError(
317 'invalid assignment: use exactly one target (file %r, line %s)' % (
318 filename, getattr(node, 'lineno', '<unknown>')))
319
320 target = node.targets[0]
321 if not isinstance(target, ast.Name):
322 raise ValueError(
323 'invalid assignment: target should be a name (file %r, line %s)' % (
324 filename, getattr(node, 'lineno', '<unknown>')))
325 if target.id in local_scope:
326 raise ValueError(
327 'invalid assignment: overrides var %r (file %r, line %s)' % (
328 target.id, filename, getattr(node, 'lineno', '<unknown>')))
329
330 node_or_string = ast.parse(content, filename=filename, mode='exec')
331 if isinstance(node_or_string, ast.Expression):
332 node_or_string = node_or_string.body
333
334 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200335 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200336 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200337 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200338 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200339 filename,
340 getattr(node_or_string, 'lineno', '<unknown>')))
341
Edward Lesmes6c24d372018-03-28 12:52:29 -0400342 statements = {}
343 for statement in node_or_string.body:
344 _validate_statement(statement, statements)
345 statements[statement.targets[0].id] = statement.value
346
Raul Tambreb946b232019-03-26 14:48:46 +0000347 # The tokenized representation needs to end with a newline token, otherwise
348 # untokenization will trigger an assert later on.
349 # In Python 2.7 on Windows we need to ensure the input ends with a newline
350 # for a newline token to be generated.
351 # In other cases a newline token is always generated during tokenization so
352 # this has no effect.
353 # TODO: Remove this workaround after migrating to Python 3.
354 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400355 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000356 token[2]: list(token) for token in tokenize.generate_tokens(
357 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400358 }
Raul Tambreb946b232019-03-26 14:48:46 +0000359
Edward Lesmes6c24d372018-03-28 12:52:29 -0400360 local_scope = _NodeDict({}, tokens)
361
362 # Process vars first, so we can expand variables in the rest of the DEPS file.
363 vars_dict = {}
364 if 'vars' in statements:
365 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000366 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400367 local_scope.SetNode('vars', value, vars_statement)
368 # Update the parsed vars with the overrides, but only if they are already
369 # present (overrides do not introduce new variables).
370 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000371
372 if builtin_vars:
373 vars_dict.update(builtin_vars)
374
375 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000376 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400377
Raul Tambreb946b232019-03-26 14:48:46 +0000378 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000379 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400380 local_scope.SetNode(name, value, node)
381
Edward Lemur67cabcd2020-03-03 19:31:15 +0000382 try:
383 return _GCLIENT_SCHEMA.validate(local_scope)
384 except schema.SchemaError as e:
385 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400386
387
Edward Lemur16f4bad2018-05-16 16:53:49 -0400388def _StandardizeDeps(deps_dict, vars_dict):
389 """"Standardizes the deps_dict.
390
391 For each dependency:
392 - Expands the variable in the dependency name.
393 - Ensures the dependency is a dictionary.
394 - Set's the 'dep_type' to be 'git' by default.
395 """
396 new_deps_dict = {}
397 for dep_name, dep_info in deps_dict.items():
398 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000399 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400400 dep_info = {'url': dep_info}
401 dep_info.setdefault('dep_type', 'git')
402 new_deps_dict[dep_name] = dep_info
403 return new_deps_dict
404
405
406def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
407 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
408
409 The dependencies in os_deps_dict are transformed into conditional dependencies
410 using |'checkout_' + os_name|.
411 If the dependency is already present, the URL and revision must coincide.
412 """
413 for dep_name, dep_info in os_deps_dict.items():
414 # Make this condition very visible, so it's not a silent failure.
415 # It's unclear how to support None override in deps_os.
416 if dep_info['url'] is None:
417 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
418 continue
419
420 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
421 UpdateCondition(dep_info, 'and', os_condition)
422
423 if dep_name in deps_dict:
424 if deps_dict[dep_name]['url'] != dep_info['url']:
425 raise gclient_utils.Error(
426 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
427 'entry (%r).' % (
428 os_name, dep_name, dep_info, deps_dict[dep_name]))
429
430 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
431
432 deps_dict[dep_name] = dep_info
433
434
435def UpdateCondition(info_dict, op, new_condition):
436 """Updates info_dict's condition with |new_condition|.
437
438 An absent value is treated as implicitly True.
439 """
440 curr_condition = info_dict.get('condition')
441 # Easy case: Both are present.
442 if curr_condition and new_condition:
443 info_dict['condition'] = '(%s) %s (%s)' % (
444 curr_condition, op, new_condition)
445 # If |op| == 'and', and at least one condition is present, then use it.
446 elif op == 'and' and (curr_condition or new_condition):
447 info_dict['condition'] = curr_condition or new_condition
448 # Otherwise, no condition should be set
449 elif curr_condition:
450 del info_dict['condition']
451
452
Edward Lemur67cabcd2020-03-03 19:31:15 +0000453def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400454 """Parses DEPS strings.
455
456 Executes the Python-like string stored in content, resulting in a Python
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000457 dictionary specified by the schema above. Supports syntax validation and
Edward Lemur16f4bad2018-05-16 16:53:49 -0400458 variable expansion.
459
460 Args:
461 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400462 filename: str. The name of the DEPS file, or a string describing the source
463 of the content, e.g. '<string>', '<unknown>'.
464 vars_override: dict, optional. A dictionary with overrides for the variables
465 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000466 builtin_vars: dict, optional. A dictionary with variables that are provided
467 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400468
469 Returns:
470 A Python dict with the parsed contents of the DEPS file, as specified by the
471 schema above.
472 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000473 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400474
475 vars_dict = result.get('vars', {})
476 if 'deps' in result:
477 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
478
479 if 'deps_os' in result:
480 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000481 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400482 os_deps = _StandardizeDeps(os_deps, vars_dict)
483 _MergeDepsOs(deps, os_deps, os_name)
484 del result['deps_os']
485
486 if 'hooks_os' in result:
487 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000488 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400489 for hook in os_hooks:
490 UpdateCondition(hook, 'and', 'checkout_' + os_name)
491 hooks.extend(os_hooks)
492 del result['hooks_os']
493
494 return result
495
496
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200497def EvaluateCondition(condition, variables, referenced_variables=None):
498 """Safely evaluates a boolean condition. Returns the result."""
499 if not referenced_variables:
500 referenced_variables = set()
501 _allowed_names = {'None': None, 'True': True, 'False': False}
502 main_node = ast.parse(condition, mode='eval')
503 if isinstance(main_node, ast.Expression):
504 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000505 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200506 if isinstance(node, ast.Str):
507 return node.s
Ben Pastenea541b282019-05-24 00:25:12 +0000508 elif isinstance(node, ast.Tuple) and allow_tuple:
509 return tuple(map(_convert, node.elts))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200510 elif isinstance(node, ast.Name):
511 if node.id in referenced_variables:
512 raise ValueError(
513 'invalid cyclic reference to %r (inside %r)' % (
514 node.id, condition))
515 elif node.id in _allowed_names:
516 return _allowed_names[node.id]
517 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200518 value = variables[node.id]
519
520 # Allow using "native" types, without wrapping everything in strings.
521 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000522 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200523 return value
524
525 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200526 return EvaluateCondition(
527 variables[node.id],
528 variables,
529 referenced_variables.union([node.id]))
530 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200531 # Implicitly convert unrecognized names to strings.
532 # If we want to change this, we'll need to explicitly distinguish
533 # between arguments for GN to be passed verbatim, and ones to
534 # be evaluated.
535 return node.id
Edward Lemurba1b1f72019-07-27 00:41:59 +0000536 elif not sys.version_info[:2] < (3, 4) and isinstance(
537 node, ast.NameConstant): # Since Python 3.4
538 return node.value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200539 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000540 bool_values = []
541 for value in node.values:
542 bool_values.append(_convert(value))
543 if not isinstance(bool_values[-1], bool):
544 raise ValueError(
545 'invalid "or" operand %r (inside %r)' % (
546 bool_values[-1], condition))
547 return any(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200548 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000549 bool_values = []
550 for value in node.values:
551 bool_values.append(_convert(value))
552 if not isinstance(bool_values[-1], bool):
553 raise ValueError(
554 'invalid "and" operand %r (inside %r)' % (
555 bool_values[-1], condition))
556 return all(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200557 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200558 value = _convert(node.operand)
559 if not isinstance(value, bool):
560 raise ValueError(
561 'invalid "not" operand %r (inside %r)' % (value, condition))
562 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200563 elif isinstance(node, ast.Compare):
564 if len(node.ops) != 1:
565 raise ValueError(
566 'invalid compare: exactly 1 operator required (inside %r)' % (
567 condition))
568 if len(node.comparators) != 1:
569 raise ValueError(
570 'invalid compare: exactly 1 comparator required (inside %r)' % (
571 condition))
572
573 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000574 right = _convert(
575 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200576
577 if isinstance(node.ops[0], ast.Eq):
578 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700579 if isinstance(node.ops[0], ast.NotEq):
580 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000581 if isinstance(node.ops[0], ast.In):
582 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200583
584 raise ValueError(
585 'unexpected operator: %s %s (inside %r)' % (
586 node.ops[0], ast.dump(node), condition))
587 else:
588 raise ValueError(
589 'unexpected AST node: %s %s (inside %r)' % (
590 node, ast.dump(node), condition))
591 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400592
593
594def RenderDEPSFile(gclient_dict):
595 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000596 # The last token is a newline, which we ensure in Exec() for compatibility.
597 # However tests pass in inputs not ending with a newline and expect the same
598 # back, so for backwards compatibility need to remove that newline character.
599 # TODO: Fix tests to expect the newline
600 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400601
602
603def _UpdateAstString(tokens, node, value):
604 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000605 quote_char = ''
606 if isinstance(node, ast.Str):
607 quote_char = tokens[position][1][0]
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000608 value = value.encode('unicode_escape').decode('utf-8')
Edward Lesmes62af4e42018-03-30 18:15:44 -0400609 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400610 node.s = value
611
612
Edward Lesmes3d993812018-04-02 12:52:49 -0400613def _ShiftLinesInTokens(tokens, delta, start):
614 new_tokens = {}
615 for token in tokens.values():
616 if token[2][0] >= start:
617 token[2] = token[2][0] + delta, token[2][1]
618 token[3] = token[3][0] + delta, token[3][1]
619 new_tokens[token[2]] = token
620 return new_tokens
621
622
623def AddVar(gclient_dict, var_name, value):
624 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
625 raise ValueError(
626 "Can't use SetVar for the given gclient dict. It contains no "
627 "formatting information.")
628
629 if 'vars' not in gclient_dict:
630 raise KeyError("vars dict is not defined.")
631
632 if var_name in gclient_dict['vars']:
633 raise ValueError(
634 "%s has already been declared in the vars dict. Consider using SetVar "
635 "instead." % var_name)
636
637 if not gclient_dict['vars']:
638 raise ValueError('vars dict is empty. This is not yet supported.')
639
Edward Lesmes8d626572018-04-05 17:53:10 -0400640 # We will attempt to add the var right after 'vars = {'.
641 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400642 if node is None:
643 raise ValueError(
644 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400645 line = node.lineno + 1
646
647 # We will try to match the new var's indentation to the next variable.
648 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400649
650 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000651 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400652 var_ast = ast.parse(var_content).body[0].value
653
654 # Set the ast nodes for the key and value.
655 vars_node = gclient_dict.GetNode('vars')
656
657 var_name_node = var_ast.keys[0]
658 var_name_node.lineno += line - 2
659 vars_node.keys.insert(0, var_name_node)
660
661 value_node = var_ast.values[0]
662 value_node.lineno += line - 2
663 vars_node.values.insert(0, value_node)
664
665 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000666 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400667 var_tokens = {
668 token[2]: list(token)
669 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000670 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400671 }
672
673 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
674 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
675
676
Edward Lesmes6f64a052018-03-20 17:35:49 -0400677def SetVar(gclient_dict, var_name, value):
678 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
679 raise ValueError(
680 "Can't use SetVar for the given gclient dict. It contains no "
681 "formatting information.")
682 tokens = gclient_dict.tokens
683
Edward Lesmes3d993812018-04-02 12:52:49 -0400684 if 'vars' not in gclient_dict:
685 raise KeyError("vars dict is not defined.")
686
687 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400688 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400689 "%s has not been declared in the vars dict. Consider using AddVar "
690 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400691
692 node = gclient_dict['vars'].GetNode(var_name)
693 if node is None:
694 raise ValueError(
695 "The vars entry for %s has no formatting information." % var_name)
696
697 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400698 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400699
700
Edward Lemura1e4d482018-12-17 19:01:03 +0000701def _GetVarName(node):
702 if isinstance(node, ast.Call):
703 return node.args[0].s
704 elif node.s.endswith('}'):
705 last_brace = node.s.rfind('{')
706 return node.s[last_brace+1:-1]
707 return None
708
709
Edward Lesmes6f64a052018-03-20 17:35:49 -0400710def SetCIPD(gclient_dict, dep_name, package_name, new_version):
711 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
712 raise ValueError(
713 "Can't use SetCIPD for the given gclient dict. It contains no "
714 "formatting information.")
715 tokens = gclient_dict.tokens
716
717 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400718 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400719 "Could not find any dependency called %s." % dep_name)
720
721 # Find the package with the given name
722 packages = [
723 package
724 for package in gclient_dict['deps'][dep_name]['packages']
725 if package['package'] == package_name
726 ]
727 if len(packages) != 1:
728 raise ValueError(
729 "There must be exactly one package with the given name (%s), "
730 "%s were found." % (package_name, len(packages)))
731
732 # TODO(ehmaldonado): Support Var in package's version.
733 node = packages[0].GetNode('version')
734 if node is None:
735 raise ValueError(
736 "The deps entry for %s:%s has no formatting information." %
737 (dep_name, package_name))
738
Edward Lemura1e4d482018-12-17 19:01:03 +0000739 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
740 raise ValueError(
741 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000742 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000743
744 var_name = _GetVarName(node)
745 if var_name is not None:
746 SetVar(gclient_dict, var_name, new_version)
747 else:
748 _UpdateAstString(tokens, node, new_version)
749 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400750
751
Edward Lesmes9f531292018-03-20 21:27:15 -0400752def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400753 def _UpdateRevision(dep_dict, dep_key, new_revision):
754 dep_node = dep_dict.GetNode(dep_key)
755 if dep_node is None:
756 raise ValueError(
757 "The deps entry for %s has no formatting information." % dep_name)
758
759 node = dep_node
760 if isinstance(node, ast.BinOp):
761 node = node.right
762
Josip Sokcevicb3e593c2020-03-27 17:16:34 +0000763 if isinstance(node, ast.Str):
764 token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
765 if token != node.s:
766 raise ValueError(
767 'Can\'t update value for %s. Multiline strings and implicitly '
768 'concatenated strings are not supported.\n'
769 'Consider reformatting the DEPS file.' % dep_key)
Edward Lemur3c117942020-03-12 17:21:12 +0000770
771
Edward Lesmes62af4e42018-03-30 18:15:44 -0400772 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
773 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000774 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000775 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400776
777 var_name = _GetVarName(node)
778 if var_name is not None:
779 SetVar(gclient_dict, var_name, new_revision)
780 else:
781 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400782 # '@' is part of the last string, which we want to modify. Discard
783 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400784 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400785 elif '@' not in dep_dict[dep_key]:
786 # '@' is not part of the URL at all. This mean the dependency is
787 # unpinned and we should pin it.
788 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400789 _UpdateAstString(tokens, node, new_revision)
790 dep_dict.SetNode(dep_key, new_revision, node)
791
Edward Lesmes6f64a052018-03-20 17:35:49 -0400792 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
793 raise ValueError(
794 "Can't use SetRevision for the given gclient dict. It contains no "
795 "formatting information.")
796 tokens = gclient_dict.tokens
797
798 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400799 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400800 "Could not find any dependency called %s." % dep_name)
801
Edward Lesmes6f64a052018-03-20 17:35:49 -0400802 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400803 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400804 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400805 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400806
807
808def GetVar(gclient_dict, var_name):
809 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
810 raise KeyError(
811 "Could not find any variable called %s." % var_name)
812
Dirk Prankeac93e6d2020-06-29 18:42:26 +0000813 return gclient_dict['vars'][var_name]
Edward Lesmes411041f2018-04-05 20:12:55 -0400814
815
816def GetCIPD(gclient_dict, dep_name, package_name):
817 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
818 raise KeyError(
819 "Could not find any dependency called %s." % dep_name)
820
821 # Find the package with the given name
822 packages = [
823 package
824 for package in gclient_dict['deps'][dep_name]['packages']
825 if package['package'] == package_name
826 ]
827 if len(packages) != 1:
828 raise ValueError(
829 "There must be exactly one package with the given name (%s), "
830 "%s were found." % (package_name, len(packages)))
831
Edward Lemura92b9612018-07-03 02:34:32 +0000832 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400833
834
835def GetRevision(gclient_dict, dep_name):
836 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
837 raise KeyError(
838 "Could not find any dependency called %s." % dep_name)
839
840 dep = gclient_dict['deps'][dep_name]
841 if dep is None:
842 return None
843 elif isinstance(dep, basestring):
844 _, _, revision = dep.partition('@')
845 return revision or None
Raul Tambre6693d092020-02-19 20:36:45 +0000846 elif isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400847 _, _, revision = dep['url'].partition('@')
848 return revision or None
849 else:
850 raise ValueError(
851 '%s is not a valid git dependency.' % dep_name)