Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 1 | # 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 | |
| 5 | import ast |
Paweł Hajdan, Jr | 7cf96a4 | 2017-05-26 20:28:35 +0200 | [diff] [blame] | 6 | import collections |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 7 | import logging |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 8 | import sys |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 9 | import tokenize |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 10 | |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 11 | import gclient_utils |
| 12 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 13 | from third_party import schema |
James Darpinian | f994d87 | 2019-08-06 18:57:40 +0000 | [diff] [blame] | 14 | from third_party import six |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 15 | |
Edward Lemur | ba1b1f7 | 2019-07-27 00:41:59 +0000 | [diff] [blame] | 16 | if six.PY2: |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 17 | # We use cStringIO.StringIO because it is equivalent to Py3's io.StringIO. |
| 18 | from cStringIO import StringIO |
Raul Tambre | 6693d09 | 2020-02-19 20:36:45 +0000 | [diff] [blame] | 19 | import collections as collections_abc |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 20 | else: |
Raul Tambre | 6693d09 | 2020-02-19 20:36:45 +0000 | [diff] [blame] | 21 | from collections import abc as collections_abc |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 22 | from io import StringIO |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 23 | # pylint: disable=redefined-builtin |
| 24 | basestring = str |
| 25 | |
| 26 | |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 27 | class ConstantString(object): |
| 28 | def __init__(self, value): |
| 29 | self.value = value |
| 30 | |
| 31 | def __format__(self, format_spec): |
| 32 | del format_spec |
| 33 | return self.value |
| 34 | |
| 35 | def __repr__(self): |
| 36 | return "Str('" + self.value + "')" |
| 37 | |
| 38 | def __eq__(self, other): |
| 39 | if isinstance(other, ConstantString): |
| 40 | return self.value == other.value |
| 41 | else: |
| 42 | return self.value == other |
| 43 | |
| 44 | def __hash__(self): |
| 45 | return self.value.__hash__() |
| 46 | |
| 47 | |
Raul Tambre | 6693d09 | 2020-02-19 20:36:45 +0000 | [diff] [blame] | 48 | class _NodeDict(collections_abc.MutableMapping): |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 49 | """Dict-like type that also stores information on AST nodes and tokens.""" |
Edward Lemur | c00ac8d | 2020-03-04 23:37:57 +0000 | [diff] [blame] | 50 | def __init__(self, data=None, tokens=None): |
| 51 | self.data = collections.OrderedDict(data or []) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 52 | self.tokens = tokens |
| 53 | |
| 54 | def __str__(self): |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 55 | return str({k: v[0] for k, v in self.data.items()}) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 56 | |
Edward Lemur | a1e4d48 | 2018-12-17 19:01:03 +0000 | [diff] [blame] | 57 | def __repr__(self): |
| 58 | return self.__str__() |
| 59 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 60 | def __getitem__(self, key): |
| 61 | return self.data[key][0] |
| 62 | |
| 63 | def __setitem__(self, key, value): |
| 64 | self.data[key] = (value, None) |
| 65 | |
| 66 | def __delitem__(self, key): |
| 67 | del self.data[key] |
| 68 | |
| 69 | def __iter__(self): |
| 70 | return iter(self.data) |
| 71 | |
| 72 | def __len__(self): |
| 73 | return len(self.data) |
| 74 | |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 75 | def MoveTokens(self, origin, delta): |
| 76 | if self.tokens: |
| 77 | new_tokens = {} |
Marc-Antoine Ruel | 8e57b4b | 2019-10-11 01:01:36 +0000 | [diff] [blame] | 78 | for pos, token in self.tokens.items(): |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 79 | if pos[0] >= origin: |
| 80 | pos = (pos[0] + delta, pos[1]) |
| 81 | token = token[:2] + (pos,) + token[3:] |
| 82 | new_tokens[pos] = token |
| 83 | |
| 84 | for value, node in self.data.values(): |
| 85 | if node.lineno >= origin: |
| 86 | node.lineno += delta |
| 87 | if isinstance(value, _NodeDict): |
| 88 | value.MoveTokens(origin, delta) |
| 89 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 90 | def GetNode(self, key): |
| 91 | return self.data[key][1] |
| 92 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 93 | def SetNode(self, key, value, node): |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 94 | self.data[key] = (value, node) |
| 95 | |
| 96 | |
| 97 | def _NodeDictSchema(dict_schema): |
| 98 | """Validate dict_schema after converting _NodeDict to a regular dict.""" |
| 99 | def validate(d): |
| 100 | schema.Schema(dict_schema).validate(dict(d)) |
| 101 | return True |
| 102 | return validate |
| 103 | |
| 104 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 105 | # See https://github.com/keleshev/schema for docs how to configure schema. |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 106 | _GCLIENT_DEPS_SCHEMA = _NodeDictSchema({ |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 107 | schema.Optional(basestring): |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 108 | schema.Or( |
| 109 | None, |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 110 | basestring, |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 111 | _NodeDictSchema({ |
| 112 | # Repo and revision to check out under the path |
| 113 | # (same as if no dict was used). |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 114 | 'url': schema.Or(None, basestring), |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 115 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 116 | # Optional condition string. The dep will only be processed |
| 117 | # if the condition evaluates to True. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 118 | schema.Optional('condition'): basestring, |
| 119 | schema.Optional('dep_type', default='git'): basestring, |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 120 | }), |
| 121 | # CIPD package. |
| 122 | _NodeDictSchema({ |
| 123 | 'packages': [ |
| 124 | _NodeDictSchema({ |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 125 | 'package': basestring, |
| 126 | 'version': basestring, |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 127 | }) |
| 128 | ], |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 129 | schema.Optional('condition'): basestring, |
| 130 | schema.Optional('dep_type', default='cipd'): basestring, |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 131 | }), |
| 132 | ), |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 133 | }) |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 134 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 135 | _GCLIENT_HOOKS_SCHEMA = [ |
| 136 | _NodeDictSchema({ |
| 137 | # Hook action: list of command-line arguments to invoke. |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 138 | 'action': [schema.Or(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 139 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 140 | # Name of the hook. Doesn't affect operation. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 141 | schema.Optional('name'): basestring, |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 142 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 143 | # Hook pattern (regex). Originally intended to limit some hooks to run |
| 144 | # only when files matching the pattern have changed. In practice, with |
| 145 | # git, gclient runs all the hooks regardless of this field. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 146 | schema.Optional('pattern'): basestring, |
Paweł Hajdan, Jr | c936439 | 2017-06-14 17:11:56 +0200 | [diff] [blame] | 147 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 148 | # Working directory where to execute the hook. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 149 | schema.Optional('cwd'): basestring, |
Paweł Hajdan, Jr | 032d545 | 2017-06-22 20:43:53 +0200 | [diff] [blame] | 150 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 151 | # Optional condition string. The hook will only be run |
| 152 | # if the condition evaluates to True. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 153 | schema.Optional('condition'): basestring, |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 154 | }) |
| 155 | ] |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 156 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 157 | _GCLIENT_SCHEMA = schema.Schema( |
| 158 | _NodeDictSchema({ |
Ayu Ishii | 0985861 | 2020-06-26 18:00:52 +0000 | [diff] [blame] | 159 | # List of host names from which dependencies are allowed (allowlist). |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 160 | # NOTE: when not present, all hosts are allowed. |
| 161 | # NOTE: scoped to current DEPS file, not recursive. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 162 | schema.Optional('allowed_hosts'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 163 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 164 | # Mapping from paths to repo and revision to check out under that path. |
| 165 | # Applying this mapping to the on-disk checkout is the main purpose |
| 166 | # of gclient, and also why the config file is called DEPS. |
| 167 | # |
| 168 | # The following functions are allowed: |
| 169 | # |
| 170 | # Var(): allows variable substitution (either from 'vars' dict below, |
| 171 | # or command-line override) |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 172 | schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA, |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 173 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 174 | # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux'). |
| 175 | # Also see 'target_os'. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 176 | schema.Optional('deps_os'): _NodeDictSchema({ |
| 177 | schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA, |
| 178 | }), |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 179 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 180 | # Dependency to get gclient_gn_args* settings from. This allows these |
| 181 | # values to be set in a recursedeps file, rather than requiring that |
| 182 | # they exist in the top-level solution. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 183 | schema.Optional('gclient_gn_args_from'): basestring, |
Michael Moss | 848c86e | 2018-05-03 16:05:50 -0700 | [diff] [blame] | 184 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 185 | # Path to GN args file to write selected variables. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 186 | schema.Optional('gclient_gn_args_file'): basestring, |
Paweł Hajdan, Jr | 5725373 | 2017-06-06 23:49:11 +0200 | [diff] [blame] | 187 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 188 | # Subset of variables to write to the GN args file (see above). |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 189 | schema.Optional('gclient_gn_args'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | 5725373 | 2017-06-06 23:49:11 +0200 | [diff] [blame] | 190 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 191 | # Hooks executed after gclient sync (unless suppressed), or explicitly |
| 192 | # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details. |
| 193 | # Also see 'pre_deps_hooks'. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 194 | schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA, |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 195 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 196 | # Similar to 'hooks', also keyed by OS. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 197 | schema.Optional('hooks_os'): _NodeDictSchema({ |
| 198 | schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA |
| 199 | }), |
Scott Graham | c482674 | 2017-05-11 16:59:23 -0700 | [diff] [blame] | 200 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 201 | # Rules which #includes are allowed in the directory. |
| 202 | # Also see 'skip_child_includes' and 'specific_include_rules'. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 203 | schema.Optional('include_rules'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 204 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 205 | # Hooks executed before processing DEPS. See 'hooks' for more details. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 206 | schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA, |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 207 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 208 | # Recursion limit for nested DEPS. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 209 | schema.Optional('recursion'): int, |
Paweł Hajdan, Jr | 6f79679 | 2017-06-02 08:40:06 +0200 | [diff] [blame] | 210 | |
Ayu Ishii | 0985861 | 2020-06-26 18:00:52 +0000 | [diff] [blame] | 211 | # Allowlists deps for which recursion should be enabled. |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 212 | schema.Optional('recursedeps'): [ |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 213 | schema.Optional(schema.Or( |
| 214 | basestring, |
| 215 | (basestring, basestring), |
| 216 | [basestring, basestring] |
| 217 | )), |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 218 | ], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 219 | |
Ayu Ishii | 0985861 | 2020-06-26 18:00:52 +0000 | [diff] [blame] | 220 | # Blocklists directories for checking 'include_rules'. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 221 | schema.Optional('skip_child_includes'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 222 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 223 | # Mapping from paths to include rules specific for that path. |
| 224 | # See 'include_rules' for more details. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 225 | schema.Optional('specific_include_rules'): _NodeDictSchema({ |
| 226 | schema.Optional(basestring): [basestring] |
| 227 | }), |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 228 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 229 | # List of additional OS names to consider when selecting dependencies |
| 230 | # from deps_os. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 231 | schema.Optional('target_os'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 232 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 233 | # For recursed-upon sub-dependencies, check out their own dependencies |
| 234 | # relative to the parent's path, rather than relative to the .gclient |
| 235 | # file. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 236 | schema.Optional('use_relative_paths'): bool, |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 237 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 238 | # Variables that can be referenced using Var() - see 'deps'. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 239 | schema.Optional('vars'): _NodeDictSchema({ |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 240 | schema.Optional(basestring): schema.Or(ConstantString, |
| 241 | basestring, |
| 242 | bool), |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 243 | }), |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 244 | })) |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 245 | |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 246 | |
Edward Lemur | e05f18d | 2018-06-08 17:36:53 +0000 | [diff] [blame] | 247 | def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 248 | """Safely evaluates a single expression. Returns the result.""" |
| 249 | _allowed_names = {'None': None, 'True': True, 'False': False} |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 250 | if isinstance(node_or_string, ConstantString): |
| 251 | return node_or_string.value |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 252 | if isinstance(node_or_string, basestring): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 253 | node_or_string = ast.parse(node_or_string, filename=filename, mode='eval') |
| 254 | if isinstance(node_or_string, ast.Expression): |
| 255 | node_or_string = node_or_string.body |
| 256 | def _convert(node): |
| 257 | if isinstance(node, ast.Str): |
Edward Lemur | e05f18d | 2018-06-08 17:36:53 +0000 | [diff] [blame] | 258 | if vars_dict is None: |
Edward Lesmes | 01cb510 | 2018-06-05 00:45:44 +0000 | [diff] [blame] | 259 | return node.s |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 260 | try: |
| 261 | return node.s.format(**vars_dict) |
| 262 | except KeyError as e: |
Edward Lemur | e05f18d | 2018-06-08 17:36:53 +0000 | [diff] [blame] | 263 | raise KeyError( |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 264 | '%s was used as a variable, but was not declared in the vars dict ' |
| 265 | '(file %r, line %s)' % ( |
Edward Lemur | ba1b1f7 | 2019-07-27 00:41:59 +0000 | [diff] [blame] | 266 | e.args[0], filename, getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | 6f79679 | 2017-06-02 08:40:06 +0200 | [diff] [blame] | 267 | elif isinstance(node, ast.Num): |
| 268 | return node.n |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 269 | elif isinstance(node, ast.Tuple): |
| 270 | return tuple(map(_convert, node.elts)) |
| 271 | elif isinstance(node, ast.List): |
| 272 | return list(map(_convert, node.elts)) |
| 273 | elif isinstance(node, ast.Dict): |
Edward Lemur | c00ac8d | 2020-03-04 23:37:57 +0000 | [diff] [blame] | 274 | node_dict = _NodeDict() |
| 275 | for key_node, value_node in zip(node.keys, node.values): |
| 276 | key = _convert(key_node) |
| 277 | if key in node_dict: |
| 278 | raise ValueError( |
| 279 | 'duplicate key in dictionary: %s (file %r, line %s)' % ( |
| 280 | key, filename, getattr(key_node, 'lineno', '<unknown>'))) |
| 281 | node_dict.SetNode(key, _convert(value_node), value_node) |
| 282 | return node_dict |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 283 | elif isinstance(node, ast.Name): |
| 284 | if node.id not in _allowed_names: |
| 285 | raise ValueError( |
| 286 | 'invalid name %r (file %r, line %s)' % ( |
| 287 | node.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 288 | return _allowed_names[node.id] |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 289 | elif not sys.version_info[:2] < (3, 4) and isinstance( |
| 290 | node, ast.NameConstant): # Since Python 3.4 |
| 291 | return node.value |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 292 | elif isinstance(node, ast.Call): |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 293 | if (not isinstance(node.func, ast.Name) or |
| 294 | (node.func.id not in ('Str', 'Var'))): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 295 | raise ValueError( |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 296 | 'Str and Var are the only allowed functions (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 297 | filename, getattr(node, 'lineno', '<unknown>'))) |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 298 | if node.keywords or getattr(node, 'starargs', None) or getattr( |
| 299 | node, 'kwargs', None) or len(node.args) != 1: |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 300 | raise ValueError( |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 301 | '%s takes exactly one argument (file %r, line %s)' % ( |
| 302 | node.func.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 303 | if node.func.id == 'Str': |
| 304 | if isinstance(node.args[0], ast.Str): |
| 305 | return ConstantString(node.args[0].s) |
| 306 | raise ValueError('Passed a non-string to Str() (file %r, line%s)' % ( |
| 307 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 308 | else: |
| 309 | arg = _convert(node.args[0]) |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 310 | if not isinstance(arg, basestring): |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 311 | raise ValueError( |
| 312 | 'Var\'s argument must be a variable name (file %r, line %s)' % ( |
| 313 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 314 | if vars_dict is None: |
Edward Lemur | e05f18d | 2018-06-08 17:36:53 +0000 | [diff] [blame] | 315 | return '{' + arg + '}' |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 316 | if arg not in vars_dict: |
Edward Lemur | e05f18d | 2018-06-08 17:36:53 +0000 | [diff] [blame] | 317 | raise KeyError( |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 318 | '%s was used as a variable, but was not declared in the vars dict ' |
| 319 | '(file %r, line %s)' % ( |
| 320 | arg, filename, getattr(node, 'lineno', '<unknown>'))) |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 321 | val = vars_dict[arg] |
| 322 | if isinstance(val, ConstantString): |
| 323 | val = val.value |
| 324 | return val |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 325 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): |
| 326 | return _convert(node.left) + _convert(node.right) |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 327 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod): |
| 328 | return _convert(node.left) % _convert(node.right) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 329 | else: |
| 330 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 331 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
| 332 | node, ast.dump(node), filename, |
| 333 | getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 334 | return _convert(node_or_string) |
| 335 | |
| 336 | |
Edward Lemur | 8f8a50d | 2018-11-01 22:03:02 +0000 | [diff] [blame] | 337 | def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None): |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 338 | """Safely execs a set of assignments.""" |
| 339 | def _validate_statement(node, local_scope): |
| 340 | if not isinstance(node, ast.Assign): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 341 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 342 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
| 343 | node, ast.dump(node), filename, |
| 344 | getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 345 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 346 | if len(node.targets) != 1: |
| 347 | raise ValueError( |
| 348 | 'invalid assignment: use exactly one target (file %r, line %s)' % ( |
| 349 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 350 | |
| 351 | target = node.targets[0] |
| 352 | if not isinstance(target, ast.Name): |
| 353 | raise ValueError( |
| 354 | 'invalid assignment: target should be a name (file %r, line %s)' % ( |
| 355 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 356 | if target.id in local_scope: |
| 357 | raise ValueError( |
| 358 | 'invalid assignment: overrides var %r (file %r, line %s)' % ( |
| 359 | target.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 360 | |
| 361 | node_or_string = ast.parse(content, filename=filename, mode='exec') |
| 362 | if isinstance(node_or_string, ast.Expression): |
| 363 | node_or_string = node_or_string.body |
| 364 | |
| 365 | if not isinstance(node_or_string, ast.Module): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 366 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 367 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 368 | node_or_string, |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 369 | ast.dump(node_or_string), |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 370 | filename, |
| 371 | getattr(node_or_string, 'lineno', '<unknown>'))) |
| 372 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 373 | statements = {} |
| 374 | for statement in node_or_string.body: |
| 375 | _validate_statement(statement, statements) |
| 376 | statements[statement.targets[0].id] = statement.value |
| 377 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 378 | # The tokenized representation needs to end with a newline token, otherwise |
| 379 | # untokenization will trigger an assert later on. |
| 380 | # In Python 2.7 on Windows we need to ensure the input ends with a newline |
| 381 | # for a newline token to be generated. |
| 382 | # In other cases a newline token is always generated during tokenization so |
| 383 | # this has no effect. |
| 384 | # TODO: Remove this workaround after migrating to Python 3. |
| 385 | content += '\n' |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 386 | tokens = { |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 387 | token[2]: list(token) for token in tokenize.generate_tokens( |
| 388 | StringIO(content).readline) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 389 | } |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 390 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 391 | local_scope = _NodeDict({}, tokens) |
| 392 | |
| 393 | # Process vars first, so we can expand variables in the rest of the DEPS file. |
| 394 | vars_dict = {} |
| 395 | if 'vars' in statements: |
| 396 | vars_statement = statements['vars'] |
Edward Lemur | e05f18d | 2018-06-08 17:36:53 +0000 | [diff] [blame] | 397 | value = _gclient_eval(vars_statement, filename) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 398 | local_scope.SetNode('vars', value, vars_statement) |
| 399 | # Update the parsed vars with the overrides, but only if they are already |
| 400 | # present (overrides do not introduce new variables). |
| 401 | vars_dict.update(value) |
Edward Lemur | 8f8a50d | 2018-11-01 22:03:02 +0000 | [diff] [blame] | 402 | |
| 403 | if builtin_vars: |
| 404 | vars_dict.update(builtin_vars) |
| 405 | |
| 406 | if vars_override: |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 407 | vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict}) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 408 | |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 409 | for name, node in statements.items(): |
Edward Lemur | e05f18d | 2018-06-08 17:36:53 +0000 | [diff] [blame] | 410 | value = _gclient_eval(node, filename, vars_dict) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 411 | local_scope.SetNode(name, value, node) |
| 412 | |
Edward Lemur | 67cabcd | 2020-03-03 19:31:15 +0000 | [diff] [blame] | 413 | try: |
| 414 | return _GCLIENT_SCHEMA.validate(local_scope) |
| 415 | except schema.SchemaError as e: |
| 416 | raise gclient_utils.Error(str(e)) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 417 | |
| 418 | |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 419 | def _StandardizeDeps(deps_dict, vars_dict): |
| 420 | """"Standardizes the deps_dict. |
| 421 | |
| 422 | For each dependency: |
| 423 | - Expands the variable in the dependency name. |
| 424 | - Ensures the dependency is a dictionary. |
| 425 | - Set's the 'dep_type' to be 'git' by default. |
| 426 | """ |
| 427 | new_deps_dict = {} |
| 428 | for dep_name, dep_info in deps_dict.items(): |
| 429 | dep_name = dep_name.format(**vars_dict) |
Raul Tambre | 6693d09 | 2020-02-19 20:36:45 +0000 | [diff] [blame] | 430 | if not isinstance(dep_info, collections_abc.Mapping): |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 431 | dep_info = {'url': dep_info} |
| 432 | dep_info.setdefault('dep_type', 'git') |
| 433 | new_deps_dict[dep_name] = dep_info |
| 434 | return new_deps_dict |
| 435 | |
| 436 | |
| 437 | def _MergeDepsOs(deps_dict, os_deps_dict, os_name): |
| 438 | """Merges the deps in os_deps_dict into conditional dependencies in deps_dict. |
| 439 | |
| 440 | The dependencies in os_deps_dict are transformed into conditional dependencies |
| 441 | using |'checkout_' + os_name|. |
| 442 | If the dependency is already present, the URL and revision must coincide. |
| 443 | """ |
| 444 | for dep_name, dep_info in os_deps_dict.items(): |
| 445 | # Make this condition very visible, so it's not a silent failure. |
| 446 | # It's unclear how to support None override in deps_os. |
| 447 | if dep_info['url'] is None: |
| 448 | logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name) |
| 449 | continue |
| 450 | |
| 451 | os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux') |
| 452 | UpdateCondition(dep_info, 'and', os_condition) |
| 453 | |
| 454 | if dep_name in deps_dict: |
| 455 | if deps_dict[dep_name]['url'] != dep_info['url']: |
| 456 | raise gclient_utils.Error( |
| 457 | 'Value from deps_os (%r; %r: %r) conflicts with existing deps ' |
| 458 | 'entry (%r).' % ( |
| 459 | os_name, dep_name, dep_info, deps_dict[dep_name])) |
| 460 | |
| 461 | UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition')) |
| 462 | |
| 463 | deps_dict[dep_name] = dep_info |
| 464 | |
| 465 | |
| 466 | def UpdateCondition(info_dict, op, new_condition): |
| 467 | """Updates info_dict's condition with |new_condition|. |
| 468 | |
| 469 | An absent value is treated as implicitly True. |
| 470 | """ |
| 471 | curr_condition = info_dict.get('condition') |
| 472 | # Easy case: Both are present. |
| 473 | if curr_condition and new_condition: |
| 474 | info_dict['condition'] = '(%s) %s (%s)' % ( |
| 475 | curr_condition, op, new_condition) |
| 476 | # If |op| == 'and', and at least one condition is present, then use it. |
| 477 | elif op == 'and' and (curr_condition or new_condition): |
| 478 | info_dict['condition'] = curr_condition or new_condition |
| 479 | # Otherwise, no condition should be set |
| 480 | elif curr_condition: |
| 481 | del info_dict['condition'] |
| 482 | |
| 483 | |
Edward Lemur | 67cabcd | 2020-03-03 19:31:15 +0000 | [diff] [blame] | 484 | def Parse(content, filename, vars_override=None, builtin_vars=None): |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 485 | """Parses DEPS strings. |
| 486 | |
| 487 | Executes the Python-like string stored in content, resulting in a Python |
Quinten Yearsley | 925cedb | 2020-04-13 17:49:39 +0000 | [diff] [blame] | 488 | dictionary specified by the schema above. Supports syntax validation and |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 489 | variable expansion. |
| 490 | |
| 491 | Args: |
| 492 | content: str. DEPS file stored as a string. |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 493 | filename: str. The name of the DEPS file, or a string describing the source |
| 494 | of the content, e.g. '<string>', '<unknown>'. |
| 495 | vars_override: dict, optional. A dictionary with overrides for the variables |
| 496 | defined by the DEPS file. |
Edward Lemur | 8f8a50d | 2018-11-01 22:03:02 +0000 | [diff] [blame] | 497 | builtin_vars: dict, optional. A dictionary with variables that are provided |
| 498 | by default. |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 499 | |
| 500 | Returns: |
| 501 | A Python dict with the parsed contents of the DEPS file, as specified by the |
| 502 | schema above. |
| 503 | """ |
Edward Lemur | 67cabcd | 2020-03-03 19:31:15 +0000 | [diff] [blame] | 504 | result = Exec(content, filename, vars_override, builtin_vars) |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 505 | |
| 506 | vars_dict = result.get('vars', {}) |
| 507 | if 'deps' in result: |
| 508 | result['deps'] = _StandardizeDeps(result['deps'], vars_dict) |
| 509 | |
| 510 | if 'deps_os' in result: |
| 511 | deps = result.setdefault('deps', {}) |
Marc-Antoine Ruel | 8e57b4b | 2019-10-11 01:01:36 +0000 | [diff] [blame] | 512 | for os_name, os_deps in result['deps_os'].items(): |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 513 | os_deps = _StandardizeDeps(os_deps, vars_dict) |
| 514 | _MergeDepsOs(deps, os_deps, os_name) |
| 515 | del result['deps_os'] |
| 516 | |
| 517 | if 'hooks_os' in result: |
| 518 | hooks = result.setdefault('hooks', []) |
Marc-Antoine Ruel | 8e57b4b | 2019-10-11 01:01:36 +0000 | [diff] [blame] | 519 | for os_name, os_hooks in result['hooks_os'].items(): |
Edward Lemur | 16f4bad | 2018-05-16 16:53:49 -0400 | [diff] [blame] | 520 | for hook in os_hooks: |
| 521 | UpdateCondition(hook, 'and', 'checkout_' + os_name) |
| 522 | hooks.extend(os_hooks) |
| 523 | del result['hooks_os'] |
| 524 | |
| 525 | return result |
| 526 | |
| 527 | |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 528 | def EvaluateCondition(condition, variables, referenced_variables=None): |
| 529 | """Safely evaluates a boolean condition. Returns the result.""" |
| 530 | if not referenced_variables: |
| 531 | referenced_variables = set() |
| 532 | _allowed_names = {'None': None, 'True': True, 'False': False} |
| 533 | main_node = ast.parse(condition, mode='eval') |
| 534 | if isinstance(main_node, ast.Expression): |
| 535 | main_node = main_node.body |
Ben Pastene | a541b28 | 2019-05-24 00:25:12 +0000 | [diff] [blame] | 536 | def _convert(node, allow_tuple=False): |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 537 | if isinstance(node, ast.Str): |
| 538 | return node.s |
Ben Pastene | a541b28 | 2019-05-24 00:25:12 +0000 | [diff] [blame] | 539 | elif isinstance(node, ast.Tuple) and allow_tuple: |
| 540 | return tuple(map(_convert, node.elts)) |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 541 | elif isinstance(node, ast.Name): |
| 542 | if node.id in referenced_variables: |
| 543 | raise ValueError( |
| 544 | 'invalid cyclic reference to %r (inside %r)' % ( |
| 545 | node.id, condition)) |
| 546 | elif node.id in _allowed_names: |
| 547 | return _allowed_names[node.id] |
| 548 | elif node.id in variables: |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 549 | value = variables[node.id] |
| 550 | |
| 551 | # Allow using "native" types, without wrapping everything in strings. |
| 552 | # Note that schema constraints still apply to variables. |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 553 | if not isinstance(value, basestring): |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 554 | return value |
| 555 | |
| 556 | # Recursively evaluate the variable reference. |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 557 | return EvaluateCondition( |
| 558 | variables[node.id], |
| 559 | variables, |
| 560 | referenced_variables.union([node.id])) |
| 561 | else: |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 562 | # Implicitly convert unrecognized names to strings. |
| 563 | # If we want to change this, we'll need to explicitly distinguish |
| 564 | # between arguments for GN to be passed verbatim, and ones to |
| 565 | # be evaluated. |
| 566 | return node.id |
Edward Lemur | ba1b1f7 | 2019-07-27 00:41:59 +0000 | [diff] [blame] | 567 | elif not sys.version_info[:2] < (3, 4) and isinstance( |
| 568 | node, ast.NameConstant): # Since Python 3.4 |
| 569 | return node.value |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 570 | elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or): |
Anthony Polito | 2ae039a | 2019-09-11 17:15:17 +0000 | [diff] [blame] | 571 | bool_values = [] |
| 572 | for value in node.values: |
| 573 | bool_values.append(_convert(value)) |
| 574 | if not isinstance(bool_values[-1], bool): |
| 575 | raise ValueError( |
| 576 | 'invalid "or" operand %r (inside %r)' % ( |
| 577 | bool_values[-1], condition)) |
| 578 | return any(bool_values) |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 579 | elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And): |
Anthony Polito | 2ae039a | 2019-09-11 17:15:17 +0000 | [diff] [blame] | 580 | bool_values = [] |
| 581 | for value in node.values: |
| 582 | bool_values.append(_convert(value)) |
| 583 | if not isinstance(bool_values[-1], bool): |
| 584 | raise ValueError( |
| 585 | 'invalid "and" operand %r (inside %r)' % ( |
| 586 | bool_values[-1], condition)) |
| 587 | return all(bool_values) |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 588 | elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 589 | value = _convert(node.operand) |
| 590 | if not isinstance(value, bool): |
| 591 | raise ValueError( |
| 592 | 'invalid "not" operand %r (inside %r)' % (value, condition)) |
| 593 | return not value |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 594 | elif isinstance(node, ast.Compare): |
| 595 | if len(node.ops) != 1: |
| 596 | raise ValueError( |
| 597 | 'invalid compare: exactly 1 operator required (inside %r)' % ( |
| 598 | condition)) |
| 599 | if len(node.comparators) != 1: |
| 600 | raise ValueError( |
| 601 | 'invalid compare: exactly 1 comparator required (inside %r)' % ( |
| 602 | condition)) |
| 603 | |
| 604 | left = _convert(node.left) |
Ben Pastene | a541b28 | 2019-05-24 00:25:12 +0000 | [diff] [blame] | 605 | right = _convert( |
| 606 | node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In)) |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 607 | |
| 608 | if isinstance(node.ops[0], ast.Eq): |
| 609 | return left == right |
Dirk Pranke | 77b7687 | 2017-10-05 18:29:27 -0700 | [diff] [blame] | 610 | if isinstance(node.ops[0], ast.NotEq): |
| 611 | return left != right |
Ben Pastene | a541b28 | 2019-05-24 00:25:12 +0000 | [diff] [blame] | 612 | if isinstance(node.ops[0], ast.In): |
| 613 | return left in right |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 614 | |
| 615 | raise ValueError( |
| 616 | 'unexpected operator: %s %s (inside %r)' % ( |
| 617 | node.ops[0], ast.dump(node), condition)) |
| 618 | else: |
| 619 | raise ValueError( |
| 620 | 'unexpected AST node: %s %s (inside %r)' % ( |
| 621 | node, ast.dump(node), condition)) |
| 622 | return _convert(main_node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 623 | |
| 624 | |
| 625 | def RenderDEPSFile(gclient_dict): |
| 626 | contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2]) |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 627 | # The last token is a newline, which we ensure in Exec() for compatibility. |
| 628 | # However tests pass in inputs not ending with a newline and expect the same |
| 629 | # back, so for backwards compatibility need to remove that newline character. |
| 630 | # TODO: Fix tests to expect the newline |
| 631 | return tokenize.untokenize(contents)[:-1] |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 632 | |
| 633 | |
| 634 | def _UpdateAstString(tokens, node, value): |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 635 | if isinstance(node, ast.Call): |
| 636 | node = node.args[0] |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 637 | position = node.lineno, node.col_offset |
Edward Lemur | 5cc2afd | 2018-08-28 00:54:45 +0000 | [diff] [blame] | 638 | quote_char = '' |
| 639 | if isinstance(node, ast.Str): |
| 640 | quote_char = tokens[position][1][0] |
Josip Sokcevic | b3e593c | 2020-03-27 17:16:34 +0000 | [diff] [blame] | 641 | value = value.encode('unicode_escape').decode('utf-8') |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 642 | tokens[position][1] = quote_char + value + quote_char |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 643 | node.s = value |
| 644 | |
| 645 | |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 646 | def _ShiftLinesInTokens(tokens, delta, start): |
| 647 | new_tokens = {} |
| 648 | for token in tokens.values(): |
| 649 | if token[2][0] >= start: |
| 650 | token[2] = token[2][0] + delta, token[2][1] |
| 651 | token[3] = token[3][0] + delta, token[3][1] |
| 652 | new_tokens[token[2]] = token |
| 653 | return new_tokens |
| 654 | |
| 655 | |
| 656 | def AddVar(gclient_dict, var_name, value): |
| 657 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 658 | raise ValueError( |
| 659 | "Can't use SetVar for the given gclient dict. It contains no " |
| 660 | "formatting information.") |
| 661 | |
| 662 | if 'vars' not in gclient_dict: |
| 663 | raise KeyError("vars dict is not defined.") |
| 664 | |
| 665 | if var_name in gclient_dict['vars']: |
| 666 | raise ValueError( |
| 667 | "%s has already been declared in the vars dict. Consider using SetVar " |
| 668 | "instead." % var_name) |
| 669 | |
| 670 | if not gclient_dict['vars']: |
| 671 | raise ValueError('vars dict is empty. This is not yet supported.') |
| 672 | |
Edward Lesmes | 8d62657 | 2018-04-05 17:53:10 -0400 | [diff] [blame] | 673 | # We will attempt to add the var right after 'vars = {'. |
| 674 | node = gclient_dict.GetNode('vars') |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 675 | if node is None: |
| 676 | raise ValueError( |
| 677 | "The vars dict has no formatting information." % var_name) |
Edward Lesmes | 8d62657 | 2018-04-05 17:53:10 -0400 | [diff] [blame] | 678 | line = node.lineno + 1 |
| 679 | |
| 680 | # We will try to match the new var's indentation to the next variable. |
| 681 | col = node.keys[0].col_offset |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 682 | |
| 683 | # We use a minimal Python dictionary, so that ast can parse it. |
Edward Lemur | bfcde3c | 2019-08-21 22:05:03 +0000 | [diff] [blame] | 684 | var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value) |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 685 | var_ast = ast.parse(var_content).body[0].value |
| 686 | |
| 687 | # Set the ast nodes for the key and value. |
| 688 | vars_node = gclient_dict.GetNode('vars') |
| 689 | |
| 690 | var_name_node = var_ast.keys[0] |
| 691 | var_name_node.lineno += line - 2 |
| 692 | vars_node.keys.insert(0, var_name_node) |
| 693 | |
| 694 | value_node = var_ast.values[0] |
| 695 | value_node.lineno += line - 2 |
| 696 | vars_node.values.insert(0, value_node) |
| 697 | |
| 698 | # Update the tokens. |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 699 | var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline)) |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 700 | var_tokens = { |
| 701 | token[2]: list(token) |
| 702 | # Ignore the tokens corresponding to braces and new lines. |
Edward Lemur | bfcde3c | 2019-08-21 22:05:03 +0000 | [diff] [blame] | 703 | for token in var_tokens[2:-3] |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 704 | } |
| 705 | |
| 706 | gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line) |
| 707 | gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0)) |
| 708 | |
| 709 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 710 | def SetVar(gclient_dict, var_name, value): |
| 711 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 712 | raise ValueError( |
| 713 | "Can't use SetVar for the given gclient dict. It contains no " |
| 714 | "formatting information.") |
| 715 | tokens = gclient_dict.tokens |
| 716 | |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 717 | if 'vars' not in gclient_dict: |
| 718 | raise KeyError("vars dict is not defined.") |
| 719 | |
| 720 | if var_name not in gclient_dict['vars']: |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 721 | raise ValueError( |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 722 | "%s has not been declared in the vars dict. Consider using AddVar " |
| 723 | "instead." % var_name) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 724 | |
| 725 | node = gclient_dict['vars'].GetNode(var_name) |
| 726 | if node is None: |
| 727 | raise ValueError( |
| 728 | "The vars entry for %s has no formatting information." % var_name) |
| 729 | |
| 730 | _UpdateAstString(tokens, node, value) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 731 | gclient_dict['vars'].SetNode(var_name, value, node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 732 | |
| 733 | |
Edward Lemur | a1e4d48 | 2018-12-17 19:01:03 +0000 | [diff] [blame] | 734 | def _GetVarName(node): |
| 735 | if isinstance(node, ast.Call): |
| 736 | return node.args[0].s |
| 737 | elif node.s.endswith('}'): |
| 738 | last_brace = node.s.rfind('{') |
| 739 | return node.s[last_brace+1:-1] |
| 740 | return None |
| 741 | |
| 742 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 743 | def SetCIPD(gclient_dict, dep_name, package_name, new_version): |
| 744 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 745 | raise ValueError( |
| 746 | "Can't use SetCIPD for the given gclient dict. It contains no " |
| 747 | "formatting information.") |
| 748 | tokens = gclient_dict.tokens |
| 749 | |
| 750 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 751 | raise KeyError( |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 752 | "Could not find any dependency called %s." % dep_name) |
| 753 | |
| 754 | # Find the package with the given name |
| 755 | packages = [ |
| 756 | package |
| 757 | for package in gclient_dict['deps'][dep_name]['packages'] |
| 758 | if package['package'] == package_name |
| 759 | ] |
| 760 | if len(packages) != 1: |
| 761 | raise ValueError( |
| 762 | "There must be exactly one package with the given name (%s), " |
| 763 | "%s were found." % (package_name, len(packages))) |
| 764 | |
| 765 | # TODO(ehmaldonado): Support Var in package's version. |
| 766 | node = packages[0].GetNode('version') |
| 767 | if node is None: |
| 768 | raise ValueError( |
| 769 | "The deps entry for %s:%s has no formatting information." % |
| 770 | (dep_name, package_name)) |
| 771 | |
Edward Lemur | a1e4d48 | 2018-12-17 19:01:03 +0000 | [diff] [blame] | 772 | if not isinstance(node, ast.Call) and not isinstance(node, ast.Str): |
| 773 | raise ValueError( |
| 774 | "Unsupported dependency revision format. Please file a bug to the " |
Edward Lemur | fb8c1a2 | 2018-12-17 20:44:18 +0000 | [diff] [blame] | 775 | "Infra>SDK component in crbug.com") |
Edward Lemur | a1e4d48 | 2018-12-17 19:01:03 +0000 | [diff] [blame] | 776 | |
| 777 | var_name = _GetVarName(node) |
| 778 | if var_name is not None: |
| 779 | SetVar(gclient_dict, var_name, new_version) |
| 780 | else: |
| 781 | _UpdateAstString(tokens, node, new_version) |
| 782 | packages[0].SetNode('version', new_version, node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 783 | |
| 784 | |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 785 | def SetRevision(gclient_dict, dep_name, new_revision): |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 786 | def _UpdateRevision(dep_dict, dep_key, new_revision): |
| 787 | dep_node = dep_dict.GetNode(dep_key) |
| 788 | if dep_node is None: |
| 789 | raise ValueError( |
| 790 | "The deps entry for %s has no formatting information." % dep_name) |
| 791 | |
| 792 | node = dep_node |
| 793 | if isinstance(node, ast.BinOp): |
| 794 | node = node.right |
| 795 | |
Josip Sokcevic | b3e593c | 2020-03-27 17:16:34 +0000 | [diff] [blame] | 796 | if isinstance(node, ast.Str): |
| 797 | token = _gclient_eval(tokens[node.lineno, node.col_offset][1]) |
| 798 | if token != node.s: |
| 799 | raise ValueError( |
| 800 | 'Can\'t update value for %s. Multiline strings and implicitly ' |
| 801 | 'concatenated strings are not supported.\n' |
| 802 | 'Consider reformatting the DEPS file.' % dep_key) |
Edward Lemur | 3c11794 | 2020-03-12 17:21:12 +0000 | [diff] [blame] | 803 | |
| 804 | |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 805 | if not isinstance(node, ast.Call) and not isinstance(node, ast.Str): |
| 806 | raise ValueError( |
Edward Lemur | a1e4d48 | 2018-12-17 19:01:03 +0000 | [diff] [blame] | 807 | "Unsupported dependency revision format. Please file a bug to the " |
Edward Lemur | fb8c1a2 | 2018-12-17 20:44:18 +0000 | [diff] [blame] | 808 | "Infra>SDK component in crbug.com") |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 809 | |
| 810 | var_name = _GetVarName(node) |
| 811 | if var_name is not None: |
| 812 | SetVar(gclient_dict, var_name, new_revision) |
| 813 | else: |
| 814 | if '@' in node.s: |
Edward Lesmes | 1118a21 | 2018-04-05 18:37:07 -0400 | [diff] [blame] | 815 | # '@' is part of the last string, which we want to modify. Discard |
| 816 | # whatever was after the '@' and put the new revision in its place. |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 817 | new_revision = node.s.split('@')[0] + '@' + new_revision |
Edward Lesmes | 1118a21 | 2018-04-05 18:37:07 -0400 | [diff] [blame] | 818 | elif '@' not in dep_dict[dep_key]: |
| 819 | # '@' is not part of the URL at all. This mean the dependency is |
| 820 | # unpinned and we should pin it. |
| 821 | new_revision = node.s + '@' + new_revision |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 822 | _UpdateAstString(tokens, node, new_revision) |
| 823 | dep_dict.SetNode(dep_key, new_revision, node) |
| 824 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 825 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 826 | raise ValueError( |
| 827 | "Can't use SetRevision for the given gclient dict. It contains no " |
| 828 | "formatting information.") |
| 829 | tokens = gclient_dict.tokens |
| 830 | |
| 831 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
Edward Lesmes | 3d99381 | 2018-04-02 12:52:49 -0400 | [diff] [blame] | 832 | raise KeyError( |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 833 | "Could not find any dependency called %s." % dep_name) |
| 834 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 835 | if isinstance(gclient_dict['deps'][dep_name], _NodeDict): |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 836 | _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 837 | else: |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 838 | _UpdateRevision(gclient_dict['deps'], dep_name, new_revision) |
Edward Lesmes | 411041f | 2018-04-05 20:12:55 -0400 | [diff] [blame] | 839 | |
| 840 | |
| 841 | def GetVar(gclient_dict, var_name): |
| 842 | if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']: |
| 843 | raise KeyError( |
| 844 | "Could not find any variable called %s." % var_name) |
| 845 | |
Dirk Pranke | fdd2cd6 | 2020-06-30 23:30:47 +0000 | [diff] [blame] | 846 | val = gclient_dict['vars'][var_name] |
| 847 | if isinstance(val, ConstantString): |
| 848 | return val.value |
| 849 | return val |
Edward Lesmes | 411041f | 2018-04-05 20:12:55 -0400 | [diff] [blame] | 850 | |
| 851 | |
| 852 | def GetCIPD(gclient_dict, dep_name, package_name): |
| 853 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
| 854 | raise KeyError( |
| 855 | "Could not find any dependency called %s." % dep_name) |
| 856 | |
| 857 | # Find the package with the given name |
| 858 | packages = [ |
| 859 | package |
| 860 | for package in gclient_dict['deps'][dep_name]['packages'] |
| 861 | if package['package'] == package_name |
| 862 | ] |
| 863 | if len(packages) != 1: |
| 864 | raise ValueError( |
| 865 | "There must be exactly one package with the given name (%s), " |
| 866 | "%s were found." % (package_name, len(packages))) |
| 867 | |
Edward Lemur | a92b961 | 2018-07-03 02:34:32 +0000 | [diff] [blame] | 868 | return packages[0]['version'] |
Edward Lesmes | 411041f | 2018-04-05 20:12:55 -0400 | [diff] [blame] | 869 | |
| 870 | |
| 871 | def GetRevision(gclient_dict, dep_name): |
| 872 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
| 873 | raise KeyError( |
| 874 | "Could not find any dependency called %s." % dep_name) |
| 875 | |
| 876 | dep = gclient_dict['deps'][dep_name] |
| 877 | if dep is None: |
| 878 | return None |
| 879 | elif isinstance(dep, basestring): |
| 880 | _, _, revision = dep.partition('@') |
| 881 | return revision or None |
Raul Tambre | 6693d09 | 2020-02-19 20:36:45 +0000 | [diff] [blame] | 882 | elif isinstance(dep, collections_abc.Mapping) and 'url' in dep: |
Edward Lesmes | 411041f | 2018-04-05 20:12:55 -0400 | [diff] [blame] | 883 | _, _, revision = dep['url'].partition('@') |
| 884 | return revision or None |
| 885 | else: |
| 886 | raise ValueError( |
| 887 | '%s is not a valid git dependency.' % dep_name) |