blob: c41ff398d77a42bee54e6b0d7a3bbc6737dc1152 [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
John Budorick0f7b2002018-01-19 15:46:17 -0800375 return _GCLIENT_SCHEMA.validate(local_scope)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200376
377
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000378def ExecLegacy(content, filename='<unknown>', vars_override=None,
379 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400380 """Executes a DEPS file |content| using exec."""
Edward Lesmes6c24d372018-03-28 12:52:29 -0400381 local_scope = {}
382 global_scope = {'Var': lambda var_name: '{%s}' % var_name}
383
384 # If we use 'exec' directly, it complains that 'Parse' contains a nested
385 # function with free variables.
386 # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same
387 # as "exec a in b, c" (See https://bugs.python.org/issue21591).
388 eval(compile(content, filename, 'exec'), global_scope, local_scope)
389
Edward Lesmes6c24d372018-03-28 12:52:29 -0400390 vars_dict = {}
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000391 vars_dict.update(local_scope.get('vars', {}))
392 if builtin_vars:
393 vars_dict.update(builtin_vars)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400394 if vars_override:
Raul Tambreb946b232019-03-26 14:48:46 +0000395 vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
Edward Lesmes6c24d372018-03-28 12:52:29 -0400396
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000397 if not vars_dict:
398 return local_scope
399
Edward Lesmes6c24d372018-03-28 12:52:29 -0400400 def _DeepFormat(node):
Aaron Gableac9b0f32019-04-18 17:38:37 +0000401 if isinstance(node, basestring):
Edward Lesmes6c24d372018-03-28 12:52:29 -0400402 return node.format(**vars_dict)
403 elif isinstance(node, dict):
Raul Tambreb946b232019-03-26 14:48:46 +0000404 return {k.format(**vars_dict): _DeepFormat(v) for k, v in node.items()}
Edward Lesmes6c24d372018-03-28 12:52:29 -0400405 elif isinstance(node, list):
406 return [_DeepFormat(elem) for elem in node]
407 elif isinstance(node, tuple):
408 return tuple(_DeepFormat(elem) for elem in node)
409 else:
410 return node
411
412 return _DeepFormat(local_scope)
413
414
Edward Lemur16f4bad2018-05-16 16:53:49 -0400415def _StandardizeDeps(deps_dict, vars_dict):
416 """"Standardizes the deps_dict.
417
418 For each dependency:
419 - Expands the variable in the dependency name.
420 - Ensures the dependency is a dictionary.
421 - Set's the 'dep_type' to be 'git' by default.
422 """
423 new_deps_dict = {}
424 for dep_name, dep_info in deps_dict.items():
425 dep_name = dep_name.format(**vars_dict)
Raul Tambre6693d092020-02-19 20:36:45 +0000426 if not isinstance(dep_info, collections_abc.Mapping):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400427 dep_info = {'url': dep_info}
428 dep_info.setdefault('dep_type', 'git')
429 new_deps_dict[dep_name] = dep_info
430 return new_deps_dict
431
432
433def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
434 """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
435
436 The dependencies in os_deps_dict are transformed into conditional dependencies
437 using |'checkout_' + os_name|.
438 If the dependency is already present, the URL and revision must coincide.
439 """
440 for dep_name, dep_info in os_deps_dict.items():
441 # Make this condition very visible, so it's not a silent failure.
442 # It's unclear how to support None override in deps_os.
443 if dep_info['url'] is None:
444 logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
445 continue
446
447 os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
448 UpdateCondition(dep_info, 'and', os_condition)
449
450 if dep_name in deps_dict:
451 if deps_dict[dep_name]['url'] != dep_info['url']:
452 raise gclient_utils.Error(
453 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
454 'entry (%r).' % (
455 os_name, dep_name, dep_info, deps_dict[dep_name]))
456
457 UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
458
459 deps_dict[dep_name] = dep_info
460
461
462def UpdateCondition(info_dict, op, new_condition):
463 """Updates info_dict's condition with |new_condition|.
464
465 An absent value is treated as implicitly True.
466 """
467 curr_condition = info_dict.get('condition')
468 # Easy case: Both are present.
469 if curr_condition and new_condition:
470 info_dict['condition'] = '(%s) %s (%s)' % (
471 curr_condition, op, new_condition)
472 # If |op| == 'and', and at least one condition is present, then use it.
473 elif op == 'and' and (curr_condition or new_condition):
474 info_dict['condition'] = curr_condition or new_condition
475 # Otherwise, no condition should be set
476 elif curr_condition:
477 del info_dict['condition']
478
479
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000480def Parse(content, validate_syntax, filename, vars_override=None,
481 builtin_vars=None):
Edward Lemur16f4bad2018-05-16 16:53:49 -0400482 """Parses DEPS strings.
483
484 Executes the Python-like string stored in content, resulting in a Python
485 dictionary specifyied by the schema above. Supports syntax validation and
486 variable expansion.
487
488 Args:
489 content: str. DEPS file stored as a string.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400490 validate_syntax: bool. Whether syntax should be validated using the schema
491 defined above.
492 filename: str. The name of the DEPS file, or a string describing the source
493 of the content, e.g. '<string>', '<unknown>'.
494 vars_override: dict, optional. A dictionary with overrides for the variables
495 defined by the DEPS file.
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000496 builtin_vars: dict, optional. A dictionary with variables that are provided
497 by default.
Edward Lemur16f4bad2018-05-16 16:53:49 -0400498
499 Returns:
500 A Python dict with the parsed contents of the DEPS file, as specified by the
501 schema above.
502 """
503 if validate_syntax:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000504 result = Exec(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400505 else:
Edward Lemur8f8a50d2018-11-01 22:03:02 +0000506 result = ExecLegacy(content, filename, vars_override, builtin_vars)
Edward Lemur16f4bad2018-05-16 16:53:49 -0400507
508 vars_dict = result.get('vars', {})
509 if 'deps' in result:
510 result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
511
512 if 'deps_os' in result:
513 deps = result.setdefault('deps', {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000514 for os_name, os_deps in result['deps_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400515 os_deps = _StandardizeDeps(os_deps, vars_dict)
516 _MergeDepsOs(deps, os_deps, os_name)
517 del result['deps_os']
518
519 if 'hooks_os' in result:
520 hooks = result.setdefault('hooks', [])
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000521 for os_name, os_hooks in result['hooks_os'].items():
Edward Lemur16f4bad2018-05-16 16:53:49 -0400522 for hook in os_hooks:
523 UpdateCondition(hook, 'and', 'checkout_' + os_name)
524 hooks.extend(os_hooks)
525 del result['hooks_os']
526
527 return result
528
529
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200530def EvaluateCondition(condition, variables, referenced_variables=None):
531 """Safely evaluates a boolean condition. Returns the result."""
532 if not referenced_variables:
533 referenced_variables = set()
534 _allowed_names = {'None': None, 'True': True, 'False': False}
535 main_node = ast.parse(condition, mode='eval')
536 if isinstance(main_node, ast.Expression):
537 main_node = main_node.body
Ben Pastenea541b282019-05-24 00:25:12 +0000538 def _convert(node, allow_tuple=False):
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200539 if isinstance(node, ast.Str):
540 return node.s
Ben Pastenea541b282019-05-24 00:25:12 +0000541 elif isinstance(node, ast.Tuple) and allow_tuple:
542 return tuple(map(_convert, node.elts))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200543 elif isinstance(node, ast.Name):
544 if node.id in referenced_variables:
545 raise ValueError(
546 'invalid cyclic reference to %r (inside %r)' % (
547 node.id, condition))
548 elif node.id in _allowed_names:
549 return _allowed_names[node.id]
550 elif node.id in variables:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200551 value = variables[node.id]
552
553 # Allow using "native" types, without wrapping everything in strings.
554 # Note that schema constraints still apply to variables.
Aaron Gableac9b0f32019-04-18 17:38:37 +0000555 if not isinstance(value, basestring):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200556 return value
557
558 # Recursively evaluate the variable reference.
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200559 return EvaluateCondition(
560 variables[node.id],
561 variables,
562 referenced_variables.union([node.id]))
563 else:
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200564 # Implicitly convert unrecognized names to strings.
565 # If we want to change this, we'll need to explicitly distinguish
566 # between arguments for GN to be passed verbatim, and ones to
567 # be evaluated.
568 return node.id
Edward Lemurba1b1f72019-07-27 00:41:59 +0000569 elif not sys.version_info[:2] < (3, 4) and isinstance(
570 node, ast.NameConstant): # Since Python 3.4
571 return node.value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200572 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000573 bool_values = []
574 for value in node.values:
575 bool_values.append(_convert(value))
576 if not isinstance(bool_values[-1], bool):
577 raise ValueError(
578 'invalid "or" operand %r (inside %r)' % (
579 bool_values[-1], condition))
580 return any(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200581 elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
Anthony Polito2ae039a2019-09-11 17:15:17 +0000582 bool_values = []
583 for value in node.values:
584 bool_values.append(_convert(value))
585 if not isinstance(bool_values[-1], bool):
586 raise ValueError(
587 'invalid "and" operand %r (inside %r)' % (
588 bool_values[-1], condition))
589 return all(bool_values)
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200590 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
Paweł Hajdan, Jre0214742017-09-28 12:21:01 +0200591 value = _convert(node.operand)
592 if not isinstance(value, bool):
593 raise ValueError(
594 'invalid "not" operand %r (inside %r)' % (value, condition))
595 return not value
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200596 elif isinstance(node, ast.Compare):
597 if len(node.ops) != 1:
598 raise ValueError(
599 'invalid compare: exactly 1 operator required (inside %r)' % (
600 condition))
601 if len(node.comparators) != 1:
602 raise ValueError(
603 'invalid compare: exactly 1 comparator required (inside %r)' % (
604 condition))
605
606 left = _convert(node.left)
Ben Pastenea541b282019-05-24 00:25:12 +0000607 right = _convert(
608 node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200609
610 if isinstance(node.ops[0], ast.Eq):
611 return left == right
Dirk Pranke77b76872017-10-05 18:29:27 -0700612 if isinstance(node.ops[0], ast.NotEq):
613 return left != right
Ben Pastenea541b282019-05-24 00:25:12 +0000614 if isinstance(node.ops[0], ast.In):
615 return left in right
Paweł Hajdan, Jr76c6ea22017-06-02 21:46:57 +0200616
617 raise ValueError(
618 'unexpected operator: %s %s (inside %r)' % (
619 node.ops[0], ast.dump(node), condition))
620 else:
621 raise ValueError(
622 'unexpected AST node: %s %s (inside %r)' % (
623 node, ast.dump(node), condition))
624 return _convert(main_node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400625
626
627def RenderDEPSFile(gclient_dict):
628 contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
Raul Tambreb946b232019-03-26 14:48:46 +0000629 # The last token is a newline, which we ensure in Exec() for compatibility.
630 # However tests pass in inputs not ending with a newline and expect the same
631 # back, so for backwards compatibility need to remove that newline character.
632 # TODO: Fix tests to expect the newline
633 return tokenize.untokenize(contents)[:-1]
Edward Lesmes6f64a052018-03-20 17:35:49 -0400634
635
636def _UpdateAstString(tokens, node, value):
637 position = node.lineno, node.col_offset
Edward Lemur5cc2afd2018-08-28 00:54:45 +0000638 quote_char = ''
639 if isinstance(node, ast.Str):
640 quote_char = tokens[position][1][0]
Edward Lesmes62af4e42018-03-30 18:15:44 -0400641 tokens[position][1] = quote_char + value + quote_char
Edward Lesmes6f64a052018-03-20 17:35:49 -0400642 node.s = value
643
644
Edward Lesmes3d993812018-04-02 12:52:49 -0400645def _ShiftLinesInTokens(tokens, delta, start):
646 new_tokens = {}
647 for token in tokens.values():
648 if token[2][0] >= start:
649 token[2] = token[2][0] + delta, token[2][1]
650 token[3] = token[3][0] + delta, token[3][1]
651 new_tokens[token[2]] = token
652 return new_tokens
653
654
655def AddVar(gclient_dict, var_name, value):
656 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
657 raise ValueError(
658 "Can't use SetVar for the given gclient dict. It contains no "
659 "formatting information.")
660
661 if 'vars' not in gclient_dict:
662 raise KeyError("vars dict is not defined.")
663
664 if var_name in gclient_dict['vars']:
665 raise ValueError(
666 "%s has already been declared in the vars dict. Consider using SetVar "
667 "instead." % var_name)
668
669 if not gclient_dict['vars']:
670 raise ValueError('vars dict is empty. This is not yet supported.')
671
Edward Lesmes8d626572018-04-05 17:53:10 -0400672 # We will attempt to add the var right after 'vars = {'.
673 node = gclient_dict.GetNode('vars')
Edward Lesmes3d993812018-04-02 12:52:49 -0400674 if node is None:
675 raise ValueError(
676 "The vars dict has no formatting information." % var_name)
Edward Lesmes8d626572018-04-05 17:53:10 -0400677 line = node.lineno + 1
678
679 # We will try to match the new var's indentation to the next variable.
680 col = node.keys[0].col_offset
Edward Lesmes3d993812018-04-02 12:52:49 -0400681
682 # We use a minimal Python dictionary, so that ast can parse it.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000683 var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
Edward Lesmes3d993812018-04-02 12:52:49 -0400684 var_ast = ast.parse(var_content).body[0].value
685
686 # Set the ast nodes for the key and value.
687 vars_node = gclient_dict.GetNode('vars')
688
689 var_name_node = var_ast.keys[0]
690 var_name_node.lineno += line - 2
691 vars_node.keys.insert(0, var_name_node)
692
693 value_node = var_ast.values[0]
694 value_node.lineno += line - 2
695 vars_node.values.insert(0, value_node)
696
697 # Update the tokens.
Raul Tambreb946b232019-03-26 14:48:46 +0000698 var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
Edward Lesmes3d993812018-04-02 12:52:49 -0400699 var_tokens = {
700 token[2]: list(token)
701 # Ignore the tokens corresponding to braces and new lines.
Edward Lemurbfcde3c2019-08-21 22:05:03 +0000702 for token in var_tokens[2:-3]
Edward Lesmes3d993812018-04-02 12:52:49 -0400703 }
704
705 gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
706 gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
707
708
Edward Lesmes6f64a052018-03-20 17:35:49 -0400709def SetVar(gclient_dict, var_name, value):
710 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
711 raise ValueError(
712 "Can't use SetVar for the given gclient dict. It contains no "
713 "formatting information.")
714 tokens = gclient_dict.tokens
715
Edward Lesmes3d993812018-04-02 12:52:49 -0400716 if 'vars' not in gclient_dict:
717 raise KeyError("vars dict is not defined.")
718
719 if var_name not in gclient_dict['vars']:
Edward Lesmes6f64a052018-03-20 17:35:49 -0400720 raise ValueError(
Edward Lesmes3d993812018-04-02 12:52:49 -0400721 "%s has not been declared in the vars dict. Consider using AddVar "
722 "instead." % var_name)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400723
724 node = gclient_dict['vars'].GetNode(var_name)
725 if node is None:
726 raise ValueError(
727 "The vars entry for %s has no formatting information." % var_name)
728
729 _UpdateAstString(tokens, node, value)
Edward Lesmes6c24d372018-03-28 12:52:29 -0400730 gclient_dict['vars'].SetNode(var_name, value, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400731
732
Edward Lemura1e4d482018-12-17 19:01:03 +0000733def _GetVarName(node):
734 if isinstance(node, ast.Call):
735 return node.args[0].s
736 elif node.s.endswith('}'):
737 last_brace = node.s.rfind('{')
738 return node.s[last_brace+1:-1]
739 return None
740
741
Edward Lesmes6f64a052018-03-20 17:35:49 -0400742def SetCIPD(gclient_dict, dep_name, package_name, new_version):
743 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
744 raise ValueError(
745 "Can't use SetCIPD for the given gclient dict. It contains no "
746 "formatting information.")
747 tokens = gclient_dict.tokens
748
749 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400750 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400751 "Could not find any dependency called %s." % dep_name)
752
753 # Find the package with the given name
754 packages = [
755 package
756 for package in gclient_dict['deps'][dep_name]['packages']
757 if package['package'] == package_name
758 ]
759 if len(packages) != 1:
760 raise ValueError(
761 "There must be exactly one package with the given name (%s), "
762 "%s were found." % (package_name, len(packages)))
763
764 # TODO(ehmaldonado): Support Var in package's version.
765 node = packages[0].GetNode('version')
766 if node is None:
767 raise ValueError(
768 "The deps entry for %s:%s has no formatting information." %
769 (dep_name, package_name))
770
Edward Lemura1e4d482018-12-17 19:01:03 +0000771 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
772 raise ValueError(
773 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000774 "Infra>SDK component in crbug.com")
Edward Lemura1e4d482018-12-17 19:01:03 +0000775
776 var_name = _GetVarName(node)
777 if var_name is not None:
778 SetVar(gclient_dict, var_name, new_version)
779 else:
780 _UpdateAstString(tokens, node, new_version)
781 packages[0].SetNode('version', new_version, node)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400782
783
Edward Lesmes9f531292018-03-20 21:27:15 -0400784def SetRevision(gclient_dict, dep_name, new_revision):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400785 def _UpdateRevision(dep_dict, dep_key, new_revision):
786 dep_node = dep_dict.GetNode(dep_key)
787 if dep_node is None:
788 raise ValueError(
789 "The deps entry for %s has no formatting information." % dep_name)
790
791 node = dep_node
792 if isinstance(node, ast.BinOp):
793 node = node.right
794
795 if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
796 raise ValueError(
Edward Lemura1e4d482018-12-17 19:01:03 +0000797 "Unsupported dependency revision format. Please file a bug to the "
Edward Lemurfb8c1a22018-12-17 20:44:18 +0000798 "Infra>SDK component in crbug.com")
Edward Lesmes62af4e42018-03-30 18:15:44 -0400799
800 var_name = _GetVarName(node)
801 if var_name is not None:
802 SetVar(gclient_dict, var_name, new_revision)
803 else:
804 if '@' in node.s:
Edward Lesmes1118a212018-04-05 18:37:07 -0400805 # '@' is part of the last string, which we want to modify. Discard
806 # whatever was after the '@' and put the new revision in its place.
Edward Lesmes62af4e42018-03-30 18:15:44 -0400807 new_revision = node.s.split('@')[0] + '@' + new_revision
Edward Lesmes1118a212018-04-05 18:37:07 -0400808 elif '@' not in dep_dict[dep_key]:
809 # '@' is not part of the URL at all. This mean the dependency is
810 # unpinned and we should pin it.
811 new_revision = node.s + '@' + new_revision
Edward Lesmes62af4e42018-03-30 18:15:44 -0400812 _UpdateAstString(tokens, node, new_revision)
813 dep_dict.SetNode(dep_key, new_revision, node)
814
Edward Lesmes6f64a052018-03-20 17:35:49 -0400815 if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
816 raise ValueError(
817 "Can't use SetRevision for the given gclient dict. It contains no "
818 "formatting information.")
819 tokens = gclient_dict.tokens
820
821 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
Edward Lesmes3d993812018-04-02 12:52:49 -0400822 raise KeyError(
Edward Lesmes6f64a052018-03-20 17:35:49 -0400823 "Could not find any dependency called %s." % dep_name)
824
Edward Lesmes6f64a052018-03-20 17:35:49 -0400825 if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
Edward Lesmes62af4e42018-03-30 18:15:44 -0400826 _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
Edward Lesmes6f64a052018-03-20 17:35:49 -0400827 else:
Edward Lesmes62af4e42018-03-30 18:15:44 -0400828 _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
Edward Lesmes411041f2018-04-05 20:12:55 -0400829
830
831def GetVar(gclient_dict, var_name):
832 if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
833 raise KeyError(
834 "Could not find any variable called %s." % var_name)
835
836 return gclient_dict['vars'][var_name]
837
838
839def GetCIPD(gclient_dict, dep_name, package_name):
840 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
841 raise KeyError(
842 "Could not find any dependency called %s." % dep_name)
843
844 # Find the package with the given name
845 packages = [
846 package
847 for package in gclient_dict['deps'][dep_name]['packages']
848 if package['package'] == package_name
849 ]
850 if len(packages) != 1:
851 raise ValueError(
852 "There must be exactly one package with the given name (%s), "
853 "%s were found." % (package_name, len(packages)))
854
Edward Lemura92b9612018-07-03 02:34:32 +0000855 return packages[0]['version']
Edward Lesmes411041f2018-04-05 20:12:55 -0400856
857
858def GetRevision(gclient_dict, dep_name):
859 if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
860 raise KeyError(
861 "Could not find any dependency called %s." % dep_name)
862
863 dep = gclient_dict['deps'][dep_name]
864 if dep is None:
865 return None
866 elif isinstance(dep, basestring):
867 _, _, revision = dep.partition('@')
868 return revision or None
Raul Tambre6693d092020-02-19 20:36:45 +0000869 elif isinstance(dep, collections_abc.Mapping) and 'url' in dep:
Edward Lesmes411041f2018-04-05 20:12:55 -0400870 _, _, revision = dep['url'].partition('@')
871 return revision or None
872 else:
873 raise ValueError(
874 '%s is not a valid git dependency.' % dep_name)