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