blob: 9ad6d2c6fa4d70d54ec3292aa0476a22d4fc91c1 [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
14
Raul Tambreb946b232019-03-26 14:48:46 +000015if sys.version_info.major == 2:
16 # We use cStringIO.StringIO because it is equivalent to Py3's io.StringIO.
17 from cStringIO import StringIO
18else:
19 from io import StringIO
20
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020021
Aaron Gableac9b0f32019-04-18 17:38:37 +000022# TODO(crbug.com/953884): Remove this when python3 migration is done.
23try:
24 basestring
25except NameError:
26 # pylint: disable=redefined-builtin
27 basestring = str
28
29
Edward Lesmes6f64a052018-03-20 17:35:49 -040030class _NodeDict(collections.MutableMapping):
31 """Dict-like type that also stores information on AST nodes and tokens."""
32 def __init__(self, data, tokens=None):
33 self.data = collections.OrderedDict(data)
34 self.tokens = tokens
35
36 def __str__(self):
Raul Tambreb946b232019-03-26 14:48:46 +000037 return str({k: v[0] for k, v in self.data.items()})
Edward Lesmes6f64a052018-03-20 17:35:49 -040038
Edward Lemura1e4d482018-12-17 19:01:03 +000039 def __repr__(self):
40 return self.__str__()
41
Edward Lesmes6f64a052018-03-20 17:35:49 -040042 def __getitem__(self, key):
43 return self.data[key][0]
44
45 def __setitem__(self, key, value):
46 self.data[key] = (value, None)
47
48 def __delitem__(self, key):
49 del self.data[key]
50
51 def __iter__(self):
52 return iter(self.data)
53
54 def __len__(self):
55 return len(self.data)
56
Edward Lesmes3d993812018-04-02 12:52:49 -040057 def MoveTokens(self, origin, delta):
58 if self.tokens:
59 new_tokens = {}
60 for pos, token in self.tokens.iteritems():
61 if pos[0] >= origin:
62 pos = (pos[0] + delta, pos[1])
63 token = token[:2] + (pos,) + token[3:]
64 new_tokens[pos] = token
65
66 for value, node in self.data.values():
67 if node.lineno >= origin:
68 node.lineno += delta
69 if isinstance(value, _NodeDict):
70 value.MoveTokens(origin, delta)
71
Edward Lesmes6f64a052018-03-20 17:35:49 -040072 def GetNode(self, key):
73 return self.data[key][1]
74
Edward Lesmes6c24d372018-03-28 12:52:29 -040075 def SetNode(self, key, value, node):
Edward Lesmes6f64a052018-03-20 17:35:49 -040076 self.data[key] = (value, node)
77
78
79def _NodeDictSchema(dict_schema):
80 """Validate dict_schema after converting _NodeDict to a regular dict."""
81 def validate(d):
82 schema.Schema(dict_schema).validate(dict(d))
83 return True
84 return validate
85
86
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +020087# See https://github.com/keleshev/schema for docs how to configure schema.
Edward Lesmes6f64a052018-03-20 17:35:49 -040088_GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +000089 schema.Optional(basestring):
Raul Tambreb946b232019-03-26 14:48:46 +000090 schema.Or(
91 None,
Aaron Gableac9b0f32019-04-18 17:38:37 +000092 basestring,
Raul Tambreb946b232019-03-26 14:48:46 +000093 _NodeDictSchema({
94 # Repo and revision to check out under the path
95 # (same as if no dict was used).
Aaron Gableac9b0f32019-04-18 17:38:37 +000096 'url': schema.Or(None, basestring),
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +020097
Raul Tambreb946b232019-03-26 14:48:46 +000098 # Optional condition string. The dep will only be processed
99 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000100 schema.Optional('condition'): basestring,
101 schema.Optional('dep_type', default='git'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000102 }),
103 # CIPD package.
104 _NodeDictSchema({
105 'packages': [
106 _NodeDictSchema({
Aaron Gableac9b0f32019-04-18 17:38:37 +0000107 'package': basestring,
108 'version': basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000109 })
110 ],
Aaron Gableac9b0f32019-04-18 17:38:37 +0000111 schema.Optional('condition'): basestring,
112 schema.Optional('dep_type', default='cipd'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000113 }),
114 ),
Edward Lesmes6f64a052018-03-20 17:35:49 -0400115})
Paweł Hajdan, Jrad30de62017-06-26 18:51:58 +0200116
Raul Tambreb946b232019-03-26 14:48:46 +0000117_GCLIENT_HOOKS_SCHEMA = [
118 _NodeDictSchema({
119 # Hook action: list of command-line arguments to invoke.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000120 'action': [basestring],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200121
Raul Tambreb946b232019-03-26 14:48:46 +0000122 # Name of the hook. Doesn't affect operation.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000123 schema.Optional('name'): basestring,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200124
Raul Tambreb946b232019-03-26 14:48:46 +0000125 # Hook pattern (regex). Originally intended to limit some hooks to run
126 # only when files matching the pattern have changed. In practice, with
127 # git, gclient runs all the hooks regardless of this field.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000128 schema.Optional('pattern'): basestring,
Paweł Hajdan, Jrc9364392017-06-14 17:11:56 +0200129
Raul Tambreb946b232019-03-26 14:48:46 +0000130 # Working directory where to execute the hook.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000131 schema.Optional('cwd'): basestring,
Paweł Hajdan, Jr032d5452017-06-22 20:43:53 +0200132
Raul Tambreb946b232019-03-26 14:48:46 +0000133 # Optional condition string. The hook will only be run
134 # if the condition evaluates to True.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000135 schema.Optional('condition'): basestring,
Raul Tambreb946b232019-03-26 14:48:46 +0000136 })
137]
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200138
Raul Tambreb946b232019-03-26 14:48:46 +0000139_GCLIENT_SCHEMA = schema.Schema(
140 _NodeDictSchema({
141 # List of host names from which dependencies are allowed (whitelist).
142 # NOTE: when not present, all hosts are allowed.
143 # NOTE: scoped to current DEPS file, not recursive.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000144 schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200145
Raul Tambreb946b232019-03-26 14:48:46 +0000146 # Mapping from paths to repo and revision to check out under that path.
147 # Applying this mapping to the on-disk checkout is the main purpose
148 # of gclient, and also why the config file is called DEPS.
149 #
150 # The following functions are allowed:
151 #
152 # Var(): allows variable substitution (either from 'vars' dict below,
153 # or command-line override)
Aaron Gableac9b0f32019-04-18 17:38:37 +0000154 schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200155
Raul Tambreb946b232019-03-26 14:48:46 +0000156 # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
157 # Also see 'target_os'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000158 schema.Optional('deps_os'): _NodeDictSchema({
159 schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
160 }),
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200161
Raul Tambreb946b232019-03-26 14:48:46 +0000162 # Dependency to get gclient_gn_args* settings from. This allows these
163 # values to be set in a recursedeps file, rather than requiring that
164 # they exist in the top-level solution.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000165 schema.Optional('gclient_gn_args_from'): basestring,
Michael Moss848c86e2018-05-03 16:05:50 -0700166
Raul Tambreb946b232019-03-26 14:48:46 +0000167 # Path to GN args file to write selected variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000168 schema.Optional('gclient_gn_args_file'): basestring,
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200169
Raul Tambreb946b232019-03-26 14:48:46 +0000170 # Subset of variables to write to the GN args file (see above).
Aaron Gableac9b0f32019-04-18 17:38:37 +0000171 schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
Paweł Hajdan, Jr57253732017-06-06 23:49:11 +0200172
Raul Tambreb946b232019-03-26 14:48:46 +0000173 # Hooks executed after gclient sync (unless suppressed), or explicitly
174 # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
175 # Also see 'pre_deps_hooks'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000176 schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200177
Raul Tambreb946b232019-03-26 14:48:46 +0000178 # Similar to 'hooks', also keyed by OS.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000179 schema.Optional('hooks_os'): _NodeDictSchema({
180 schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
181 }),
Scott Grahamc4826742017-05-11 16:59:23 -0700182
Raul Tambreb946b232019-03-26 14:48:46 +0000183 # Rules which #includes are allowed in the directory.
184 # Also see 'skip_child_includes' and 'specific_include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000185 schema.Optional('include_rules'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200186
Raul Tambreb946b232019-03-26 14:48:46 +0000187 # Hooks executed before processing DEPS. See 'hooks' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000188 schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200189
Raul Tambreb946b232019-03-26 14:48:46 +0000190 # Recursion limit for nested DEPS.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000191 schema.Optional('recursion'): int,
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200192
Raul Tambreb946b232019-03-26 14:48:46 +0000193 # Whitelists deps for which recursion should be enabled.
194 schema.Optional('recursedeps'): [
Aaron Gableac9b0f32019-04-18 17:38:37 +0000195 schema.Optional(schema.Or(
196 basestring,
197 (basestring, basestring),
198 [basestring, basestring]
199 )),
Raul Tambreb946b232019-03-26 14:48:46 +0000200 ],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200201
Raul Tambreb946b232019-03-26 14:48:46 +0000202 # Blacklists directories for checking 'include_rules'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000203 schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200204
Raul Tambreb946b232019-03-26 14:48:46 +0000205 # Mapping from paths to include rules specific for that path.
206 # See 'include_rules' for more details.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000207 schema.Optional('specific_include_rules'): _NodeDictSchema({
208 schema.Optional(basestring): [basestring]
209 }),
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200210
Raul Tambreb946b232019-03-26 14:48:46 +0000211 # List of additional OS names to consider when selecting dependencies
212 # from deps_os.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000213 schema.Optional('target_os'): [schema.Optional(basestring)],
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200214
Raul Tambreb946b232019-03-26 14:48:46 +0000215 # For recursed-upon sub-dependencies, check out their own dependencies
216 # relative to the parent's path, rather than relative to the .gclient
217 # file.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000218 schema.Optional('use_relative_paths'): bool,
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200219
Raul Tambreb946b232019-03-26 14:48:46 +0000220 # For recursed-upon sub-dependencies, run their hooks relative to the
221 # parent's path instead of relative to the .gclient file.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000222 schema.Optional('use_relative_hooks'): bool,
Corentin Walleza68660d2018-09-10 17:33:24 +0000223
Raul Tambreb946b232019-03-26 14:48:46 +0000224 # Variables that can be referenced using Var() - see 'deps'.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000225 schema.Optional('vars'): _NodeDictSchema({
226 schema.Optional(basestring): schema.Or(basestring, bool),
227 }),
Raul Tambreb946b232019-03-26 14:48:46 +0000228 }))
Paweł Hajdan, Jrbeec0062017-05-10 21:51:05 +0200229
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200230
Edward Lemure05f18d2018-06-08 17:36:53 +0000231def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200232 """Safely evaluates a single expression. Returns the result."""
233 _allowed_names = {'None': None, 'True': True, 'False': False}
Aaron Gableac9b0f32019-04-18 17:38:37 +0000234 if isinstance(node_or_string, basestring):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200235 node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
236 if isinstance(node_or_string, ast.Expression):
237 node_or_string = node_or_string.body
238 def _convert(node):
239 if isinstance(node, ast.Str):
Edward Lemure05f18d2018-06-08 17:36:53 +0000240 if vars_dict is None:
Edward Lesmes01cb5102018-06-05 00:45:44 +0000241 return node.s
Edward Lesmes6c24d372018-03-28 12:52:29 -0400242 try:
243 return node.s.format(**vars_dict)
244 except KeyError as e:
Edward Lemure05f18d2018-06-08 17:36:53 +0000245 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400246 '%s was used as a variable, but was not declared in the vars dict '
247 '(file %r, line %s)' % (
248 e.message, filename, getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jr6f796792017-06-02 08:40:06 +0200249 elif isinstance(node, ast.Num):
250 return node.n
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200251 elif isinstance(node, ast.Tuple):
252 return tuple(map(_convert, node.elts))
253 elif isinstance(node, ast.List):
254 return list(map(_convert, node.elts))
255 elif isinstance(node, ast.Dict):
Edward Lesmes6f64a052018-03-20 17:35:49 -0400256 return _NodeDict((_convert(k), (_convert(v), v))
Paweł Hajdan, Jr7cf96a42017-05-26 20:28:35 +0200257 for k, v in zip(node.keys, node.values))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200258 elif isinstance(node, ast.Name):
259 if node.id not in _allowed_names:
260 raise ValueError(
261 'invalid name %r (file %r, line %s)' % (
262 node.id, filename, getattr(node, 'lineno', '<unknown>')))
263 return _allowed_names[node.id]
Raul Tambreb946b232019-03-26 14:48:46 +0000264 elif not sys.version_info[:2] < (3, 4) and isinstance(
265 node, ast.NameConstant): # Since Python 3.4
266 return node.value
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200267 elif isinstance(node, ast.Call):
Edward Lesmes9f531292018-03-20 21:27:15 -0400268 if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200269 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400270 'Var is the only allowed function (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200271 filename, getattr(node, 'lineno', '<unknown>')))
Raul Tambreb946b232019-03-26 14:48:46 +0000272 if node.keywords or getattr(node, 'starargs', None) or getattr(
273 node, 'kwargs', None) or len(node.args) != 1:
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200274 raise ValueError(
Edward Lesmes9f531292018-03-20 21:27:15 -0400275 'Var takes exactly one argument (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200276 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes9f531292018-03-20 21:27:15 -0400277 arg = _convert(node.args[0])
Aaron Gableac9b0f32019-04-18 17:38:37 +0000278 if not isinstance(arg, basestring):
Edward Lesmes9f531292018-03-20 21:27:15 -0400279 raise ValueError(
280 'Var\'s argument must be a variable name (file %r, line %s)' % (
281 filename, getattr(node, 'lineno', '<unknown>')))
Edward Lesmes6c24d372018-03-28 12:52:29 -0400282 if vars_dict is None:
Edward Lemure05f18d2018-06-08 17:36:53 +0000283 return '{' + arg + '}'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400284 if arg not in vars_dict:
Edward Lemure05f18d2018-06-08 17:36:53 +0000285 raise KeyError(
Edward Lesmes6c24d372018-03-28 12:52:29 -0400286 '%s was used as a variable, but was not declared in the vars dict '
287 '(file %r, line %s)' % (
288 arg, filename, getattr(node, 'lineno', '<unknown>')))
289 return vars_dict[arg]
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200290 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
291 return _convert(node.left) + _convert(node.right)
Paweł Hajdan, Jrb7e53332017-05-23 16:57:37 +0200292 elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
293 return _convert(node.left) % _convert(node.right)
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200294 else:
295 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200296 'unexpected AST node: %s %s (file %r, line %s)' % (
297 node, ast.dump(node), filename,
298 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200299 return _convert(node_or_string)
300
301
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000302def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400303 """Safely execs a set of assignments."""
304 def _validate_statement(node, local_scope):
305 if not isinstance(node, ast.Assign):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200306 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200307 'unexpected AST node: %s %s (file %r, line %s)' % (
308 node, ast.dump(node), filename,
309 getattr(node, 'lineno', '<unknown>')))
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200310
Edward Lesmes6c24d372018-03-28 12:52:29 -0400311 if len(node.targets) != 1:
312 raise ValueError(
313 'invalid assignment: use exactly one target (file %r, line %s)' % (
314 filename, getattr(node, 'lineno', '<unknown>')))
315
316 target = node.targets[0]
317 if not isinstance(target, ast.Name):
318 raise ValueError(
319 'invalid assignment: target should be a name (file %r, line %s)' % (
320 filename, getattr(node, 'lineno', '<unknown>')))
321 if target.id in local_scope:
322 raise ValueError(
323 'invalid assignment: overrides var %r (file %r, line %s)' % (
324 target.id, filename, getattr(node, 'lineno', '<unknown>')))
325
326 node_or_string = ast.parse(content, filename=filename, mode='exec')
327 if isinstance(node_or_string, ast.Expression):
328 node_or_string = node_or_string.body
329
330 if not isinstance(node_or_string, ast.Module):
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200331 raise ValueError(
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200332 'unexpected AST node: %s %s (file %r, line %s)' % (
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200333 node_or_string,
Paweł Hajdan, Jr1ba610b2017-05-24 20:14:44 +0200334 ast.dump(node_or_string),
Paweł Hajdan, Jre2f9feec2017-05-09 10:04:02 +0200335 filename,
336 getattr(node_or_string, 'lineno', '<unknown>')))
337
Edward Lesmes6c24d372018-03-28 12:52:29 -0400338 statements = {}
339 for statement in node_or_string.body:
340 _validate_statement(statement, statements)
341 statements[statement.targets[0].id] = statement.value
342
Raul Tambreb946b232019-03-26 14:48:46 +0000343 # The tokenized representation needs to end with a newline token, otherwise
344 # untokenization will trigger an assert later on.
345 # In Python 2.7 on Windows we need to ensure the input ends with a newline
346 # for a newline token to be generated.
347 # In other cases a newline token is always generated during tokenization so
348 # this has no effect.
349 # TODO: Remove this workaround after migrating to Python 3.
350 content += '\n'
Edward Lesmes6c24d372018-03-28 12:52:29 -0400351 tokens = {
Raul Tambreb946b232019-03-26 14:48:46 +0000352 token[2]: list(token) for token in tokenize.generate_tokens(
353 StringIO(content).readline)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400354 }
Raul Tambreb946b232019-03-26 14:48:46 +0000355
Edward Lesmes6c24d372018-03-28 12:52:29 -0400356 local_scope = _NodeDict({}, tokens)
357
358 # Process vars first, so we can expand variables in the rest of the DEPS file.
359 vars_dict = {}
360 if 'vars' in statements:
361 vars_statement = statements['vars']
Edward Lemure05f18d2018-06-08 17:36:53 +0000362 value = _gclient_eval(vars_statement, filename)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400363 local_scope.SetNode('vars', value, vars_statement)
364 # Update the parsed vars with the overrides, but only if they are already
365 # present (overrides do not introduce new variables).
366 vars_dict.update(value)
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000367
368 if builtin_vars:
369 vars_dict.update(builtin_vars)
370
371 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000372 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400373
Raul Tambreb946b232019-03-26 14:48:46 +0000374 for name, node in statements.items():
Edward Lemure05f18d2018-06-08 17:36:53 +0000375 value = _gclient_eval(node, filename, vars_dict)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400376 local_scope.SetNode(name, value, node)
377
John Budorick0f7b2002018-01-19 15:46:17 -0800378 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200379
380
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000381def ExecLegacy(content, filename='<unknown>', vars_override=None,
382 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400383 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400384 local_scope = {}
385 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
386
387 # If we use 'exec' directly, it complains that 'Parse' contains a nested
388 # function with free variables.
389 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
390 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
391 eval(compile(content, filename, 'exec'), global_scope, local_scope)
392
Edward Lesmes6c24d372018-03-28 12:52:29 -0400393 vars_dict = {}
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000394 vars_dict.update(local_scope.get('vars', {}))
395 if builtin_vars:
396 vars_dict.update(builtin_vars)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400397 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000398 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400399
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000400 if not vars_dict:
401 return local_scope
402
Edward Lesmes6c24d372018-03-28 12:52:29 -0400403 def _DeepFormat(node):
Aaron Gableac9b0f32019-04-18 17:38:37 +0000404 if isinstance(node, basestring):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400405 return node.format(**vars_dict)
406 elif isinstance(node, dict):
Raul Tambreb946b232019-03-26 14:48:46 +0000407 return {k.format(**vars_dict): _DeepFormat(v) for k, v in node.items()}
Edward Lesmes6c24d372018-03-28 12:52:29 -0400408 elif isinstance(node, list):
409 return [_DeepFormat(elem) for elem in node]
410 elif isinstance(node, tuple):
411 return tuple(_DeepFormat(elem) for elem in node)
412 else:
413 return node
414
415 return _DeepFormat(local_scope)
416
417
Edward Lemur16f4bad2018-05-16 16:53:49 -0400418def _StandardizeDeps(deps_dict, vars_dict):
419 """"Standardizes the deps_dict.
420
421 For each dependency:
422 - Expands the variable in the dependency name.
423 - Ensures the dependency is a dictionary.
424 - Set's the 'dep_type' to be 'git' by default.
425 """
426 new_deps_dict = {}
427 for dep_name, dep_info in deps_dict.items():
428 dep_name = dep_name.format(**vars_dict)
429 if not isinstance(dep_info, collections.Mapping):
430 dep_info = {'url': dep_info}
431 dep_info.setdefault('dep_type', 'git')
432 new_deps_dict[dep_name] = dep_info
433 return new_deps_dict
434
435
436def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
437 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
438
439 The dependencies in os_deps_dict are transformed into conditional dependencies
440 using |'checkout_' + os_name|.
441 If the dependency is already present, the URL and revision must coincide.
442 """
443 for dep_name, dep_info in os_deps_dict.items():
444 # Make this condition very visible, so it's not a silent failure.
445 # It's unclear how to support None override in deps_os.
446 if dep_info['url'] is None:
447 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
448 continue
449
450 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
451 UpdateCondition(dep_info, 'and', os_condition)
452
453 if dep_name in deps_dict:
454 if deps_dict[dep_name]['url'] != dep_info['url']:
455 raise gclient_utils.Error(
456 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
457 'entry (%r).' % (
458 os_name, dep_name, dep_info, deps_dict[dep_name]))
459
460 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
461
462 deps_dict[dep_name] = dep_info
463
464
465def UpdateCondition(info_dict, op, new_condition):
466 """Updates info_dict's condition with |new_condition|.
467
468 An absent value is treated as implicitly True.
469 """
470 curr_condition = info_dict.get('condition')
471 # Easy case: Both are present.
472 if curr_condition and new_condition:
473 info_dict['condition'] = '(%s) %s (%s)' % (
474 curr_condition, op, new_condition)
475 # If |op| == 'and', and at least one condition is present, then use it.
476 elif op == 'and' and (curr_condition or new_condition):
477 info_dict['condition'] = curr_condition or new_condition
478 # Otherwise, no condition should be set
479 elif curr_condition:
480 del info_dict['condition']
481
482
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000483def Parse(content, validate_syntax, filename, vars_override=None,
484 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400485 """Parses DEPS strings.
486
487 Executes the Python-like string stored in content, resulting in a Python
488 dictionary specifyied by the schema above. Supports syntax validation and
489 variable expansion.
490
491 Args:
492 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400493 validate_syntax: bool. Whether syntax should be validated using the schema
494 defined above.
495 filename: str. The name of the DEPS file, or a string describing the source
496 of the content, e.g. '<string>', '<unknown>'.
497 vars_override: dict, optional. A dictionary with overrides for the variables
498 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000499 builtin_vars: dict, optional. A dictionary with variables that are provided
500 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400501
502 Returns:
503 A Python dict with the parsed contents of the DEPS file, as specified by the
504 schema above.
505 """
506 if validate_syntax:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000507 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400508 else:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000509 result = ExecLegacy(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400510
511 vars_dict = result.get('vars', {})
512 if 'deps' in result:
513 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
514
515 if 'deps_os' in result:
516 deps = result.setdefault('deps', {})
517 for os_name, os_deps in result['deps_os'].iteritems():
518 os_deps = _StandardizeDeps(os_deps, vars_dict)
519 _MergeDepsOs(deps, os_deps, os_name)
520 del result['deps_os']
521
522 if 'hooks_os' in result:
523 hooks = result.setdefault('hooks', [])
524 for os_name, os_hooks in result['hooks_os'].iteritems():
525 for hook in os_hooks:
526 UpdateCondition(hook, 'and', 'checkout_' + os_name)
527 hooks.extend(os_hooks)
528 del result['hooks_os']
529
530 return result
531
532
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200533def EvaluateCondition(condition, variables, referenced_variables=None):
534 """Safely evaluates a boolean condition. Returns the result."""
535 if not referenced_variables:
536 referenced_variables = set()
537 _allowed_names = {'None': None, 'True': True, 'False': False}
538 main_node = ast.parse(condition, mode='eval')
539 if isinstance(main_node, ast.Expression):
540 main_node = main_node.body
541 def _convert(node):
542 if isinstance(node, ast.Str):
543 return node.s
544 elif isinstance(node, ast.Name):
545 if node.id in referenced_variables:
546 raise ValueError(
547 'invalid cyclic reference to %r (inside %r)' % (
548 node.id, condition))
549 elif node.id in _allowed_names:
550 return _allowed_names[node.id]
551 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200552 value = variables[node.id]
553
554 # Allow using "native" types, without wrapping everything in strings.
555 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000556 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200557 return value
558
559 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200560 return EvaluateCondition(
561 variables[node.id],
562 variables,
563 referenced_variables.union([node.id]))
564 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200565 # Implicitly convert unrecognized names to strings.
566 # If we want to change this, we'll need to explicitly distinguish
567 # between arguments for GN to be passed verbatim, and ones to
568 # be evaluated.
569 return node.id
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200570 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
571 if len(node.values) != 2:
572 raise ValueError(
573 'invalid "or": exactly 2 operands required (inside %r)' % (
574 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200575 left = _convert(node.values[0])
576 right = _convert(node.values[1])
577 if not isinstance(left, bool):
578 raise ValueError(
579 'invalid "or" operand %r (inside %r)' % (left, condition))
580 if not isinstance(right, bool):
581 raise ValueError(
582 'invalid "or" operand %r (inside %r)' % (right, condition))
583 return left or right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200584 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
585 if len(node.values) != 2:
586 raise ValueError(
587 'invalid "and": exactly 2 operands required (inside %r)' % (
588 condition))
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200589 left = _convert(node.values[0])
590 right = _convert(node.values[1])
591 if not isinstance(left, bool):
592 raise ValueError(
593 'invalid "and" operand %r (inside %r)' % (left, condition))
594 if not isinstance(right, bool):
595 raise ValueError(
596 'invalid "and" operand %r (inside %r)' % (right, condition))
597 return left and right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200598 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200599 value = _convert(node.operand)
600 if not isinstance(value, bool):
601 raise ValueError(
602 'invalid "not" operand %r (inside %r)' % (value, condition))
603 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200604 elif isinstance(node, ast.Compare):
605 if len(node.ops) != 1:
606 raise ValueError(
607 'invalid compare: exactly 1 operator required (inside %r)' % (
608 condition))
609 if len(node.comparators) != 1:
610 raise ValueError(
611 'invalid compare: exactly 1 comparator required (inside %r)' % (
612 condition))
613
614 left = _convert(node.left)
615 right = _convert(node.comparators[0])
616
617 if isinstance(node.ops[0], ast.Eq):
618 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700619 if isinstance(node.ops[0], ast.NotEq):
620 return left != right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200621
622 raise ValueError(
623 'unexpected operator: %s %s (inside %r)' % (
624 node.ops[0], ast.dump(node), condition))
625 else:
626 raise ValueError(
627 'unexpected AST node: %s %s (inside %r)' % (
628 node, ast.dump(node), condition))
629 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400630
631
632def RenderDEPSFile(gclient_dict):
633 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000634 # The last token is a newline, which we ensure in Exec() for compatibility.
635 # However tests pass in inputs not ending with a newline and expect the same
636 # back, so for backwards compatibility need to remove that newline character.
637 # TODO: Fix tests to expect the newline
638 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400639
640
641def _UpdateAstString(tokens, node, value):
642 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000643 quote_char = ''
644 if isinstance(node, ast.Str):
645 quote_char = tokens[position][1][0]
Edward Lesmes62af4e42018-03-30 18:15:44 -0400646 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400647 node.s = value
648
649
Edward Lesmes3d993812018-04-02 12:52:49 -0400650def _ShiftLinesInTokens(tokens, delta, start):
651 new_tokens = {}
652 for token in tokens.values():
653 if token[2][0] >= start:
654 token[2] = token[2][0] + delta, token[2][1]
655 token[3] = token[3][0] + delta, token[3][1]
656 new_tokens[token[2]] = token
657 return new_tokens
658
659
660def AddVar(gclient_dict, var_name, value):
661 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
662 raise ValueError(
663 "Can't use SetVar for the given gclient dict. It contains no "
664 "formatting information.")
665
666 if 'vars' not in gclient_dict:
667 raise KeyError("vars dict is not defined.")
668
669 if var_name in gclient_dict['vars']:
670 raise ValueError(
671 "%s has already been declared in the vars dict. Consider using SetVar "
672 "instead." % var_name)
673
674 if not gclient_dict['vars']:
675 raise ValueError('vars dict is empty. This is not yet supported.')
676
Edward Lesmes8d626572018-04-05 17:53:10 -0400677 # We will attempt to add the var right after 'vars = {'.
678 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400679 if node is None:
680 raise ValueError(
681 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400682 line = node.lineno + 1
683
684 # We will try to match the new var's indentation to the next variable.
685 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400686
687 # We use a minimal Python dictionary, so that ast can parse it.
688 var_content = '{\n%s"%s": "%s",\n}' % (' ' * col, var_name, value)
689 var_ast = ast.parse(var_content).body[0].value
690
691 # Set the ast nodes for the key and value.
692 vars_node = gclient_dict.GetNode('vars')
693
694 var_name_node = var_ast.keys[0]
695 var_name_node.lineno += line - 2
696 vars_node.keys.insert(0, var_name_node)
697
698 value_node = var_ast.values[0]
699 value_node.lineno += line - 2
700 vars_node.values.insert(0, value_node)
701
702 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000703 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400704 var_tokens = {
705 token[2]: list(token)
706 # Ignore the tokens corresponding to braces and new lines.
707 for token in var_tokens[2:-2]
708 }
709
710 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
711 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
712
713
Edward Lesmes6f64a052018-03-20 17:35:49 -0400714def SetVar(gclient_dict, var_name, value):
715 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
716 raise ValueError(
717 "Can't use SetVar for the given gclient dict. It contains no "
718 "formatting information.")
719 tokens = gclient_dict.tokens
720
Edward Lesmes3d993812018-04-02 12:52:49 -0400721 if 'vars' not in gclient_dict:
722 raise KeyError("vars dict is not defined.")
723
724 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400725 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400726 "%s has not been declared in the vars dict. Consider using AddVar "
727 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400728
729 node = gclient_dict['vars'].GetNode(var_name)
730 if node is None:
731 raise ValueError(
732 "The vars entry for %s has no formatting information." % var_name)
733
734 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400735 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400736
737
Edward Lemura1e4d482018-12-17 19:01:03 +0000738def _GetVarName(node):
739 if isinstance(node, ast.Call):
740 return node.args[0].s
741 elif node.s.endswith('}'):
742 last_brace = node.s.rfind('{')
743 return node.s[last_brace+1:-1]
744 return None
745
746
Edward Lesmes6f64a052018-03-20 17:35:49 -0400747def SetCIPD(gclient_dict, dep_name, package_name, new_version):
748 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
749 raise ValueError(
750 "Can't use SetCIPD for the given gclient dict. It contains no "
751 "formatting information.")
752 tokens = gclient_dict.tokens
753
754 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400755 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400756 "Could not find any dependency called %s." % dep_name)
757
758 # Find the package with the given name
759 packages = [
760 package
761 for package in gclient_dict['deps'][dep_name]['packages']
762 if package['package'] == package_name
763 ]
764 if len(packages) != 1:
765 raise ValueError(
766 "There must be exactly one package with the given name (%s), "
767 "%s were found." % (package_name, len(packages)))
768
769 # TODO(ehmaldonado): Support Var in package's version.
770 node = packages[0].GetNode('version')
771 if node is None:
772 raise ValueError(
773 "The deps entry for %s:%s has no formatting information." %
774 (dep_name, package_name))
775
Edward Lemura1e4d482018-12-17 19:01:03 +0000776 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
777 raise ValueError(
778 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000779 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000780
781 var_name = _GetVarName(node)
782 if var_name is not None:
783 SetVar(gclient_dict, var_name, new_version)
784 else:
785 _UpdateAstString(tokens, node, new_version)
786 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400787
788
Edward Lesmes9f531292018-03-20 21:27:15 -0400789def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400790 def _UpdateRevision(dep_dict, dep_key, new_revision):
791 dep_node = dep_dict.GetNode(dep_key)
792 if dep_node is None:
793 raise ValueError(
794 "The deps entry for %s has no formatting information." % dep_name)
795
796 node = dep_node
797 if isinstance(node, ast.BinOp):
798 node = node.right
799
800 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
801 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000802 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000803 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400804
805 var_name = _GetVarName(node)
806 if var_name is not None:
807 SetVar(gclient_dict, var_name, new_revision)
808 else:
809 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400810 # '@' is part of the last string, which we want to modify. Discard
811 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400812 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400813 elif '@' not in dep_dict[dep_key]:
814 # '@' is not part of the URL at all. This mean the dependency is
815 # unpinned and we should pin it.
816 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400817 _UpdateAstString(tokens, node, new_revision)
818 dep_dict.SetNode(dep_key, new_revision, node)
819
Edward Lesmes6f64a052018-03-20 17:35:49 -0400820 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
821 raise ValueError(
822 "Can't use SetRevision for the given gclient dict. It contains no "
823 "formatting information.")
824 tokens = gclient_dict.tokens
825
826 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400827 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400828 "Could not find any dependency called %s." % dep_name)
829
Edward Lesmes6f64a052018-03-20 17:35:49 -0400830 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400831 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400832 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400833 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400834
835
836def GetVar(gclient_dict, var_name):
837 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
838 raise KeyError(
839 "Could not find any variable called %s." % var_name)
840
841 return gclient_dict['vars'][var_name]
842
843
844def GetCIPD(gclient_dict, dep_name, package_name):
845 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
846 raise KeyError(
847 "Could not find any dependency called %s." % dep_name)
848
849 # Find the package with the given name
850 packages = [
851 package
852 for package in gclient_dict['deps'][dep_name]['packages']
853 if package['package'] == package_name
854 ]
855 if len(packages) != 1:
856 raise ValueError(
857 "There must be exactly one package with the given name (%s), "
858 "%s were found." % (package_name, len(packages)))
859
Edward Lemura92b9612018-07-03 02:34:32 +0000860 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400861
862
863def GetRevision(gclient_dict, dep_name):
864 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
865 raise KeyError(
866 "Could not find any dependency called %s." % dep_name)
867
868 dep = gclient_dict['deps'][dep_name]
869 if dep is None:
870 return None
871 elif isinstance(dep, basestring):
872 _, _, revision = dep.partition('@')
873 return revision or None
874 elif isinstance(dep, collections.Mapping) and 'url' in dep:
875 _, _, revision = dep['url'].partition('@')
876 return revision or None
877 else:
878 raise ValueError(
879 '%s is not a valid git dependency.' % dep_name)