blob: 13abeb863c70c2b844eadbc7f1c517a0d7924bae [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."""
29 def __init__(self, data, tokens=None):
30 self.data = collections.OrderedDict(data)
31 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.
Aaron Gableac9b0f32019-04-18 17:38:37 +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({
138 # List of host names from which dependencies are allowed (whitelist).
139 # 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
Raul Tambreb946b232019-03-26 14:48:46 +0000190 # Whitelists deps for which recursion should be enabled.
191 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
Raul Tambreb946b232019-03-26 14:48:46 +0000199 # Blacklists 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({
223 schema.Optional(basestring): schema.Or(basestring, bool),
224 }),
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 Lesmes6f64a052018-03-20 17:35:49 -0400253 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200254 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200255 elif isinstance(node, ast.Name):
256 if node.id not in _allowed_names:
257 raise ValueError(
258 'invalid name %r (file %r, line %s)' % (
259 node.id, filename, getattr(node, 'lineno', '<unknown>')))
260 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000261 elif not sys.version_info[:2] < (3, 4) and isinstance(
262 node, ast.NameConstant): # Since Python 3.4
263 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200264 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400265 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200266 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400267 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200268 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000269 if node.keywords or getattr(node, 'starargs', None) or getattr(
270 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200271 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400272 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200273 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400274 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000275 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400276 raise ValueError(
277 'Var\'s argument must be a variable name (file %r, line %s)' % (
278 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400279 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000280 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400281 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000282 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400283 '%s was used as a variable, but was not declared in the vars dict '
284 '(file %r, line %s)' % (
285 arg, filename, getattr(node, 'lineno', '<unknown>')))
286 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200287 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
288 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200289 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
290 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200291 else:
292 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200293 'unexpected AST node: %s %s (file %r, line %s)' % (
294 node, ast.dump(node), filename,
295 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200296 return _convert(node_or_string)
297
298
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000299def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400300 """Safely execs a set of assignments."""
301 def _validate_statement(node, local_scope):
302 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200303 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200304 'unexpected AST node: %s %s (file %r, line %s)' % (
305 node, ast.dump(node), filename,
306 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200307
Edward Lesmes6c24d372018-03-28 12:52:29 -0400308 if len(node.targets) != 1:
309 raise ValueError(
310 'invalid assignment: use exactly one target (file %r, line %s)' % (
311 filename, getattr(node, 'lineno', '<unknown>')))
312
313 target = node.targets[0]
314 if not isinstance(target, ast.Name):
315 raise ValueError(
316 'invalid assignment: target should be a name (file %r, line %s)' % (
317 filename, getattr(node, 'lineno', '<unknown>')))
318 if target.id in local_scope:
319 raise ValueError(
320 'invalid assignment: overrides var %r (file %r, line %s)' % (
321 target.id, filename, getattr(node, 'lineno', '<unknown>')))
322
323 node_or_string = ast.parse(content, filename=filename, mode='exec')
324 if isinstance(node_or_string, ast.Expression):
325 node_or_string = node_or_string.body
326
327 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200328 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200329 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200330 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200331 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200332 filename,
333 getattr(node_or_string, 'lineno', '<unknown>')))
334
Edward Lesmes6c24d372018-03-28 12:52:29 -0400335 statements = {}
336 for statement in node_or_string.body:
337 _validate_statement(statement, statements)
338 statements[statement.targets[0].id] = statement.value
339
Raul Tambreb946b232019-03-26 14:48:46 +0000340 # The tokenized representation needs to end with a newline token, otherwise
341 # untokenization will trigger an assert later on.
342 # In Python 2.7 on Windows we need to ensure the input ends with a newline
343 # for a newline token to be generated.
344 # In other cases a newline token is always generated during tokenization so
345 # this has no effect.
346 # TODO: Remove this workaround after migrating to Python 3.
347 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400348 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000349 token[2]: list(token) for token in tokenize.generate_tokens(
350 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400351 }
Raul Tambreb946b232019-03-26 14:48:46 +0000352
Edward Lesmes6c24d372018-03-28 12:52:29 -0400353 local_scope = _NodeDict({}, tokens)
354
355 # Process vars first, so we can expand variables in the rest of the DEPS file.
356 vars_dict = {}
357 if 'vars' in statements:
358 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000359 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400360 local_scope.SetNode('vars', value, vars_statement)
361 # Update the parsed vars with the overrides, but only if they are already
362 # present (overrides do not introduce new variables).
363 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000364
365 if builtin_vars:
366 vars_dict.update(builtin_vars)
367
368 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000369 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400370
Raul Tambreb946b232019-03-26 14:48:46 +0000371 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000372 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400373 local_scope.SetNode(name, value, node)
374
Edward Lemur67cabcd2020-03-03 19:31:15 +0000375 try:
376 return _GCLIENT_SCHEMA.validate(local_scope)
377 except schema.SchemaError as e:
378 raise gclient_utils.Error(str(e))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400379
380
Edward Lemur16f4bad2018-05-16 16:53:49 -0400381def _StandardizeDeps(deps_dict, vars_dict):
382 """"Standardizes the deps_dict.
383
384 For each dependency:
385 - Expands the variable in the dependency name.
386 - Ensures the dependency is a dictionary.
387 - Set's the 'dep_type' to be 'git' by default.
388 """
389 new_deps_dict = {}
390 for dep_name, dep_info in deps_dict.items():
391 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000392 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400393 dep_info = {'url': dep_info}
394 dep_info.setdefault('dep_type', 'git')
395 new_deps_dict[dep_name] = dep_info
396 return new_deps_dict
397
398
399def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
400 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
401
402 The dependencies in os_deps_dict are transformed into conditional dependencies
403 using |'checkout_' + os_name|.
404 If the dependency is already present, the URL and revision must coincide.
405 """
406 for dep_name, dep_info in os_deps_dict.items():
407 # Make this condition very visible, so it's not a silent failure.
408 # It's unclear how to support None override in deps_os.
409 if dep_info['url'] is None:
410 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
411 continue
412
413 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
414 UpdateCondition(dep_info, 'and', os_condition)
415
416 if dep_name in deps_dict:
417 if deps_dict[dep_name]['url'] != dep_info['url']:
418 raise gclient_utils.Error(
419 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
420 'entry (%r).' % (
421 os_name, dep_name, dep_info, deps_dict[dep_name]))
422
423 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
424
425 deps_dict[dep_name] = dep_info
426
427
428def UpdateCondition(info_dict, op, new_condition):
429 """Updates info_dict's condition with |new_condition|.
430
431 An absent value is treated as implicitly True.
432 """
433 curr_condition = info_dict.get('condition')
434 # Easy case: Both are present.
435 if curr_condition and new_condition:
436 info_dict['condition'] = '(%s) %s (%s)' % (
437 curr_condition, op, new_condition)
438 # If |op| == 'and', and at least one condition is present, then use it.
439 elif op == 'and' and (curr_condition or new_condition):
440 info_dict['condition'] = curr_condition or new_condition
441 # Otherwise, no condition should be set
442 elif curr_condition:
443 del info_dict['condition']
444
445
Edward Lemur67cabcd2020-03-03 19:31:15 +0000446def Parse(content, filename, vars_override=None, builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400447 """Parses DEPS strings.
448
449 Executes the Python-like string stored in content, resulting in a Python
450 dictionary specifyied by the schema above. Supports syntax validation and
451 variable expansion.
452
453 Args:
454 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400455 filename: str. The name of the DEPS file, or a string describing the source
456 of the content, e.g. '<string>', '<unknown>'.
457 vars_override: dict, optional. A dictionary with overrides for the variables
458 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000459 builtin_vars: dict, optional. A dictionary with variables that are provided
460 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400461
462 Returns:
463 A Python dict with the parsed contents of the DEPS file, as specified by the
464 schema above.
465 """
Edward Lemur67cabcd2020-03-03 19:31:15 +0000466 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400467
468 vars_dict = result.get('vars', {})
469 if 'deps' in result:
470 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
471
472 if 'deps_os' in result:
473 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000474 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400475 os_deps = _StandardizeDeps(os_deps, vars_dict)
476 _MergeDepsOs(deps, os_deps, os_name)
477 del result['deps_os']
478
479 if 'hooks_os' in result:
480 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000481 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400482 for hook in os_hooks:
483 UpdateCondition(hook, 'and', 'checkout_' + os_name)
484 hooks.extend(os_hooks)
485 del result['hooks_os']
486
487 return result
488
489
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200490def EvaluateCondition(condition, variables, referenced_variables=None):
491 """Safely evaluates a boolean condition. Returns the result."""
492 if not referenced_variables:
493 referenced_variables = set()
494 _allowed_names = {'None': None, 'True': True, 'False': False}
495 main_node = ast.parse(condition, mode='eval')
496 if isinstance(main_node, ast.Expression):
497 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000498 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200499 if isinstance(node, ast.Str):
500 return node.s
Ben Pastenea541b282019-05-24 00:25:12 +0000501 elif isinstance(node, ast.Tuple) and allow_tuple:
502 return tuple(map(_convert, node.elts))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200503 elif isinstance(node, ast.Name):
504 if node.id in referenced_variables:
505 raise ValueError(
506 'invalid cyclic reference to %r (inside %r)' % (
507 node.id, condition))
508 elif node.id in _allowed_names:
509 return _allowed_names[node.id]
510 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200511 value = variables[node.id]
512
513 # Allow using "native" types, without wrapping everything in strings.
514 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000515 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200516 return value
517
518 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200519 return EvaluateCondition(
520 variables[node.id],
521 variables,
522 referenced_variables.union([node.id]))
523 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200524 # Implicitly convert unrecognized names to strings.
525 # If we want to change this, we'll need to explicitly distinguish
526 # between arguments for GN to be passed verbatim, and ones to
527 # be evaluated.
528 return node.id
Edward Lemurba1b1f72019-07-27 00:41:59 +0000529 elif not sys.version_info[:2] < (3, 4) and isinstance(
530 node, ast.NameConstant): # Since Python 3.4
531 return node.value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200532 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000533 bool_values = []
534 for value in node.values:
535 bool_values.append(_convert(value))
536 if not isinstance(bool_values[-1], bool):
537 raise ValueError(
538 'invalid "or" operand %r (inside %r)' % (
539 bool_values[-1], condition))
540 return any(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200541 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000542 bool_values = []
543 for value in node.values:
544 bool_values.append(_convert(value))
545 if not isinstance(bool_values[-1], bool):
546 raise ValueError(
547 'invalid "and" operand %r (inside %r)' % (
548 bool_values[-1], condition))
549 return all(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200550 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200551 value = _convert(node.operand)
552 if not isinstance(value, bool):
553 raise ValueError(
554 'invalid "not" operand %r (inside %r)' % (value, condition))
555 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200556 elif isinstance(node, ast.Compare):
557 if len(node.ops) != 1:
558 raise ValueError(
559 'invalid compare: exactly 1 operator required (inside %r)' % (
560 condition))
561 if len(node.comparators) != 1:
562 raise ValueError(
563 'invalid compare: exactly 1 comparator required (inside %r)' % (
564 condition))
565
566 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000567 right = _convert(
568 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200569
570 if isinstance(node.ops[0], ast.Eq):
571 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700572 if isinstance(node.ops[0], ast.NotEq):
573 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000574 if isinstance(node.ops[0], ast.In):
575 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200576
577 raise ValueError(
578 'unexpected operator: %s %s (inside %r)' % (
579 node.ops[0], ast.dump(node), condition))
580 else:
581 raise ValueError(
582 'unexpected AST node: %s %s (inside %r)' % (
583 node, ast.dump(node), condition))
584 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400585
586
587def RenderDEPSFile(gclient_dict):
588 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000589 # The last token is a newline, which we ensure in Exec() for compatibility.
590 # However tests pass in inputs not ending with a newline and expect the same
591 # back, so for backwards compatibility need to remove that newline character.
592 # TODO: Fix tests to expect the newline
593 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400594
595
596def _UpdateAstString(tokens, node, value):
597 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000598 quote_char = ''
599 if isinstance(node, ast.Str):
600 quote_char = tokens[position][1][0]
Edward Lesmes62af4e42018-03-30 18:15:44 -0400601 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400602 node.s = value
603
604
Edward Lesmes3d993812018-04-02 12:52:49 -0400605def _ShiftLinesInTokens(tokens, delta, start):
606 new_tokens = {}
607 for token in tokens.values():
608 if token[2][0] >= start:
609 token[2] = token[2][0] + delta, token[2][1]
610 token[3] = token[3][0] + delta, token[3][1]
611 new_tokens[token[2]] = token
612 return new_tokens
613
614
615def AddVar(gclient_dict, var_name, value):
616 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
617 raise ValueError(
618 "Can't use SetVar for the given gclient dict. It contains no "
619 "formatting information.")
620
621 if 'vars' not in gclient_dict:
622 raise KeyError("vars dict is not defined.")
623
624 if var_name in gclient_dict['vars']:
625 raise ValueError(
626 "%s has already been declared in the vars dict. Consider using SetVar "
627 "instead." % var_name)
628
629 if not gclient_dict['vars']:
630 raise ValueError('vars dict is empty. This is not yet supported.')
631
Edward Lesmes8d626572018-04-05 17:53:10 -0400632 # We will attempt to add the var right after 'vars = {'.
633 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400634 if node is None:
635 raise ValueError(
636 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400637 line = node.lineno + 1
638
639 # We will try to match the new var's indentation to the next variable.
640 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400641
642 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000643 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400644 var_ast = ast.parse(var_content).body[0].value
645
646 # Set the ast nodes for the key and value.
647 vars_node = gclient_dict.GetNode('vars')
648
649 var_name_node = var_ast.keys[0]
650 var_name_node.lineno += line - 2
651 vars_node.keys.insert(0, var_name_node)
652
653 value_node = var_ast.values[0]
654 value_node.lineno += line - 2
655 vars_node.values.insert(0, value_node)
656
657 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000658 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400659 var_tokens = {
660 token[2]: list(token)
661 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000662 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400663 }
664
665 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
666 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
667
668
Edward Lesmes6f64a052018-03-20 17:35:49 -0400669def SetVar(gclient_dict, var_name, value):
670 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
671 raise ValueError(
672 "Can't use SetVar for the given gclient dict. It contains no "
673 "formatting information.")
674 tokens = gclient_dict.tokens
675
Edward Lesmes3d993812018-04-02 12:52:49 -0400676 if 'vars' not in gclient_dict:
677 raise KeyError("vars dict is not defined.")
678
679 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400680 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400681 "%s has not been declared in the vars dict. Consider using AddVar "
682 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400683
684 node = gclient_dict['vars'].GetNode(var_name)
685 if node is None:
686 raise ValueError(
687 "The vars entry for %s has no formatting information." % var_name)
688
689 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400690 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400691
692
Edward Lemura1e4d482018-12-17 19:01:03 +0000693def _GetVarName(node):
694 if isinstance(node, ast.Call):
695 return node.args[0].s
696 elif node.s.endswith('}'):
697 last_brace = node.s.rfind('{')
698 return node.s[last_brace+1:-1]
699 return None
700
701
Edward Lesmes6f64a052018-03-20 17:35:49 -0400702def SetCIPD(gclient_dict, dep_name, package_name, new_version):
703 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
704 raise ValueError(
705 "Can't use SetCIPD for the given gclient dict. It contains no "
706 "formatting information.")
707 tokens = gclient_dict.tokens
708
709 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400710 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400711 "Could not find any dependency called %s." % dep_name)
712
713 # Find the package with the given name
714 packages = [
715 package
716 for package in gclient_dict['deps'][dep_name]['packages']
717 if package['package'] == package_name
718 ]
719 if len(packages) != 1:
720 raise ValueError(
721 "There must be exactly one package with the given name (%s), "
722 "%s were found." % (package_name, len(packages)))
723
724 # TODO(ehmaldonado): Support Var in package's version.
725 node = packages[0].GetNode('version')
726 if node is None:
727 raise ValueError(
728 "The deps entry for %s:%s has no formatting information." %
729 (dep_name, package_name))
730
Edward Lemura1e4d482018-12-17 19:01:03 +0000731 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
732 raise ValueError(
733 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000734 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000735
736 var_name = _GetVarName(node)
737 if var_name is not None:
738 SetVar(gclient_dict, var_name, new_version)
739 else:
740 _UpdateAstString(tokens, node, new_version)
741 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400742
743
Edward Lesmes9f531292018-03-20 21:27:15 -0400744def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400745 def _UpdateRevision(dep_dict, dep_key, new_revision):
746 dep_node = dep_dict.GetNode(dep_key)
747 if dep_node is None:
748 raise ValueError(
749 "The deps entry for %s has no formatting information." % dep_name)
750
751 node = dep_node
752 if isinstance(node, ast.BinOp):
753 node = node.right
754
755 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
756 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000757 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000758 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400759
760 var_name = _GetVarName(node)
761 if var_name is not None:
762 SetVar(gclient_dict, var_name, new_revision)
763 else:
764 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400765 # '@' is part of the last string, which we want to modify. Discard
766 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400767 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400768 elif '@' not in dep_dict[dep_key]:
769 # '@' is not part of the URL at all. This mean the dependency is
770 # unpinned and we should pin it.
771 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400772 _UpdateAstString(tokens, node, new_revision)
773 dep_dict.SetNode(dep_key, new_revision, node)
774
Edward Lesmes6f64a052018-03-20 17:35:49 -0400775 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
776 raise ValueError(
777 "Can't use SetRevision for the given gclient dict. It contains no "
778 "formatting information.")
779 tokens = gclient_dict.tokens
780
781 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400782 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400783 "Could not find any dependency called %s." % dep_name)
784
Edward Lesmes6f64a052018-03-20 17:35:49 -0400785 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400786 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400787 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400788 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400789
790
791def GetVar(gclient_dict, var_name):
792 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
793 raise KeyError(
794 "Could not find any variable called %s." % var_name)
795
796 return gclient_dict['vars'][var_name]
797
798
799def GetCIPD(gclient_dict, dep_name, package_name):
800 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
801 raise KeyError(
802 "Could not find any dependency called %s." % dep_name)
803
804 # Find the package with the given name
805 packages = [
806 package
807 for package in gclient_dict['deps'][dep_name]['packages']
808 if package['package'] == package_name
809 ]
810 if len(packages) != 1:
811 raise ValueError(
812 "There must be exactly one package with the given name (%s), "
813 "%s were found." % (package_name, len(packages)))
814
Edward Lemura92b9612018-07-03 02:34:32 +0000815 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400816
817
818def GetRevision(gclient_dict, dep_name):
819 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
820 raise KeyError(
821 "Could not find any dependency called %s." % dep_name)
822
823 dep = gclient_dict['deps'][dep_name]
824 if dep is None:
825 return None
826 elif isinstance(dep, basestring):
827 _, _, revision = dep.partition('@')
828 return revision or None
Raul Tambre6693d092020-02-19 20:36:45 +0000829 elif isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400830 _, _, revision = dep['url'].partition('@')
831 return revision or None
832 else:
833 raise ValueError(
834 '%s is not a valid git dependency.' % dep_name)