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 |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 6 | import cStringIO |
Paweł Hajdan, Jr | 7cf96a4 | 2017-05-26 20:28:35 +0200 | [diff] [blame] | 7 | import collections |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 8 | import tokenize |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 9 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 10 | from third_party import schema |
| 11 | |
| 12 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 13 | class _NodeDict(collections.MutableMapping): |
| 14 | """Dict-like type that also stores information on AST nodes and tokens.""" |
| 15 | def __init__(self, data, tokens=None): |
| 16 | self.data = collections.OrderedDict(data) |
| 17 | self.tokens = tokens |
| 18 | |
| 19 | def __str__(self): |
| 20 | return str({k: v[0] for k, v in self.data.iteritems()}) |
| 21 | |
| 22 | def __getitem__(self, key): |
| 23 | return self.data[key][0] |
| 24 | |
| 25 | def __setitem__(self, key, value): |
| 26 | self.data[key] = (value, None) |
| 27 | |
| 28 | def __delitem__(self, key): |
| 29 | del self.data[key] |
| 30 | |
| 31 | def __iter__(self): |
| 32 | return iter(self.data) |
| 33 | |
| 34 | def __len__(self): |
| 35 | return len(self.data) |
| 36 | |
| 37 | def GetNode(self, key): |
| 38 | return self.data[key][1] |
| 39 | |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 40 | def SetNode(self, key, value, node): |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 41 | self.data[key] = (value, node) |
| 42 | |
| 43 | |
| 44 | def _NodeDictSchema(dict_schema): |
| 45 | """Validate dict_schema after converting _NodeDict to a regular dict.""" |
| 46 | def validate(d): |
| 47 | schema.Schema(dict_schema).validate(dict(d)) |
| 48 | return True |
| 49 | return validate |
| 50 | |
| 51 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 52 | # See https://github.com/keleshev/schema for docs how to configure schema. |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 53 | _GCLIENT_DEPS_SCHEMA = _NodeDictSchema({ |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 54 | schema.Optional(basestring): schema.Or( |
| 55 | None, |
| 56 | basestring, |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 57 | _NodeDictSchema({ |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 58 | # Repo and revision to check out under the path |
| 59 | # (same as if no dict was used). |
| 60 | 'url': basestring, |
| 61 | |
| 62 | # Optional condition string. The dep will only be processed |
| 63 | # if the condition evaluates to True. |
| 64 | schema.Optional('condition'): basestring, |
John Budorick | 0f7b200 | 2018-01-19 15:46:17 -0800 | [diff] [blame] | 65 | |
| 66 | schema.Optional('dep_type', default='git'): basestring, |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 67 | }), |
John Budorick | 0f7b200 | 2018-01-19 15:46:17 -0800 | [diff] [blame] | 68 | # CIPD package. |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 69 | _NodeDictSchema({ |
John Budorick | 0f7b200 | 2018-01-19 15:46:17 -0800 | [diff] [blame] | 70 | 'packages': [ |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 71 | _NodeDictSchema({ |
John Budorick | 0f7b200 | 2018-01-19 15:46:17 -0800 | [diff] [blame] | 72 | 'package': basestring, |
| 73 | |
| 74 | 'version': basestring, |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 75 | }) |
John Budorick | 0f7b200 | 2018-01-19 15:46:17 -0800 | [diff] [blame] | 76 | ], |
| 77 | |
| 78 | schema.Optional('condition'): basestring, |
| 79 | |
| 80 | schema.Optional('dep_type', default='cipd'): basestring, |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 81 | }), |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 82 | ), |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 83 | }) |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 84 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 85 | _GCLIENT_HOOKS_SCHEMA = [_NodeDictSchema({ |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 86 | # Hook action: list of command-line arguments to invoke. |
| 87 | 'action': [basestring], |
| 88 | |
| 89 | # Name of the hook. Doesn't affect operation. |
| 90 | schema.Optional('name'): basestring, |
| 91 | |
| 92 | # Hook pattern (regex). Originally intended to limit some hooks to run |
| 93 | # only when files matching the pattern have changed. In practice, with git, |
| 94 | # gclient runs all the hooks regardless of this field. |
| 95 | schema.Optional('pattern'): basestring, |
Paweł Hajdan, Jr | c936439 | 2017-06-14 17:11:56 +0200 | [diff] [blame] | 96 | |
| 97 | # Working directory where to execute the hook. |
| 98 | schema.Optional('cwd'): basestring, |
Paweł Hajdan, Jr | 032d545 | 2017-06-22 20:43:53 +0200 | [diff] [blame] | 99 | |
| 100 | # Optional condition string. The hook will only be run |
| 101 | # if the condition evaluates to True. |
| 102 | schema.Optional('condition'): basestring, |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 103 | })] |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 104 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 105 | _GCLIENT_SCHEMA = schema.Schema(_NodeDictSchema({ |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 106 | # List of host names from which dependencies are allowed (whitelist). |
| 107 | # NOTE: when not present, all hosts are allowed. |
| 108 | # NOTE: scoped to current DEPS file, not recursive. |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 109 | schema.Optional('allowed_hosts'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 110 | |
| 111 | # Mapping from paths to repo and revision to check out under that path. |
| 112 | # Applying this mapping to the on-disk checkout is the main purpose |
| 113 | # of gclient, and also why the config file is called DEPS. |
| 114 | # |
| 115 | # The following functions are allowed: |
| 116 | # |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 117 | # Var(): allows variable substitution (either from 'vars' dict below, |
| 118 | # or command-line override) |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 119 | schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA, |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 120 | |
| 121 | # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux'). |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 122 | # Also see 'target_os'. |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 123 | schema.Optional('deps_os'): _NodeDictSchema({ |
Paweł Hajdan, Jr | ad30de6 | 2017-06-26 18:51:58 +0200 | [diff] [blame] | 124 | schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA, |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 125 | }), |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 126 | |
Paweł Hajdan, Jr | 5725373 | 2017-06-06 23:49:11 +0200 | [diff] [blame] | 127 | # Path to GN args file to write selected variables. |
| 128 | schema.Optional('gclient_gn_args_file'): basestring, |
| 129 | |
| 130 | # Subset of variables to write to the GN args file (see above). |
| 131 | schema.Optional('gclient_gn_args'): [schema.Optional(basestring)], |
| 132 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 133 | # Hooks executed after gclient sync (unless suppressed), or explicitly |
| 134 | # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details. |
| 135 | # Also see 'pre_deps_hooks'. |
| 136 | schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA, |
| 137 | |
Scott Graham | c482674 | 2017-05-11 16:59:23 -0700 | [diff] [blame] | 138 | # Similar to 'hooks', also keyed by OS. |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 139 | schema.Optional('hooks_os'): _NodeDictSchema({ |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 140 | schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 141 | }), |
Scott Graham | c482674 | 2017-05-11 16:59:23 -0700 | [diff] [blame] | 142 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 143 | # Rules which #includes are allowed in the directory. |
| 144 | # Also see 'skip_child_includes' and 'specific_include_rules'. |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 145 | schema.Optional('include_rules'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 146 | |
| 147 | # Hooks executed before processing DEPS. See 'hooks' for more details. |
| 148 | schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA, |
| 149 | |
Paweł Hajdan, Jr | 6f79679 | 2017-06-02 08:40:06 +0200 | [diff] [blame] | 150 | # Recursion limit for nested DEPS. |
| 151 | schema.Optional('recursion'): int, |
| 152 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 153 | # Whitelists deps for which recursion should be enabled. |
| 154 | schema.Optional('recursedeps'): [ |
Paweł Hajdan, Jr | 05fec03 | 2017-05-30 23:04:23 +0200 | [diff] [blame] | 155 | schema.Optional(schema.Or( |
| 156 | basestring, |
| 157 | (basestring, basestring), |
| 158 | [basestring, basestring] |
| 159 | )), |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 160 | ], |
| 161 | |
| 162 | # Blacklists directories for checking 'include_rules'. |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 163 | schema.Optional('skip_child_includes'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 164 | |
| 165 | # Mapping from paths to include rules specific for that path. |
| 166 | # See 'include_rules' for more details. |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 167 | schema.Optional('specific_include_rules'): _NodeDictSchema({ |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 168 | schema.Optional(basestring): [basestring] |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 169 | }), |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 170 | |
| 171 | # List of additional OS names to consider when selecting dependencies |
| 172 | # from deps_os. |
| 173 | schema.Optional('target_os'): [schema.Optional(basestring)], |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 174 | |
| 175 | # For recursed-upon sub-dependencies, check out their own dependencies |
| 176 | # relative to the paren't path, rather than relative to the .gclient file. |
| 177 | schema.Optional('use_relative_paths'): bool, |
| 178 | |
| 179 | # Variables that can be referenced using Var() - see 'deps'. |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 180 | schema.Optional('vars'): _NodeDictSchema({ |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 181 | schema.Optional(basestring): schema.Or(basestring, bool), |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 182 | }), |
| 183 | })) |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 184 | |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 185 | |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 186 | def _gclient_eval(node_or_string, vars_dict, expand_vars, filename): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 187 | """Safely evaluates a single expression. Returns the result.""" |
| 188 | _allowed_names = {'None': None, 'True': True, 'False': False} |
| 189 | if isinstance(node_or_string, basestring): |
| 190 | node_or_string = ast.parse(node_or_string, filename=filename, mode='eval') |
| 191 | if isinstance(node_or_string, ast.Expression): |
| 192 | node_or_string = node_or_string.body |
| 193 | def _convert(node): |
| 194 | if isinstance(node, ast.Str): |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 195 | if not expand_vars: |
| 196 | return node.s |
| 197 | try: |
| 198 | return node.s.format(**vars_dict) |
| 199 | except KeyError as e: |
| 200 | raise ValueError( |
| 201 | '%s was used as a variable, but was not declared in the vars dict ' |
| 202 | '(file %r, line %s)' % ( |
| 203 | e.message, filename, getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | 6f79679 | 2017-06-02 08:40:06 +0200 | [diff] [blame] | 204 | elif isinstance(node, ast.Num): |
| 205 | return node.n |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 206 | elif isinstance(node, ast.Tuple): |
| 207 | return tuple(map(_convert, node.elts)) |
| 208 | elif isinstance(node, ast.List): |
| 209 | return list(map(_convert, node.elts)) |
| 210 | elif isinstance(node, ast.Dict): |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 211 | return _NodeDict((_convert(k), (_convert(v), v)) |
Paweł Hajdan, Jr | 7cf96a4 | 2017-05-26 20:28:35 +0200 | [diff] [blame] | 212 | for k, v in zip(node.keys, node.values)) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 213 | elif isinstance(node, ast.Name): |
| 214 | if node.id not in _allowed_names: |
| 215 | raise ValueError( |
| 216 | 'invalid name %r (file %r, line %s)' % ( |
| 217 | node.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 218 | return _allowed_names[node.id] |
| 219 | elif isinstance(node, ast.Call): |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 220 | 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] | 221 | raise ValueError( |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 222 | 'Var is the only allowed function (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 223 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 224 | if node.keywords or node.starargs or node.kwargs or len(node.args) != 1: |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 225 | raise ValueError( |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 226 | 'Var takes exactly one argument (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 227 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 228 | arg = _convert(node.args[0]) |
| 229 | if not isinstance(arg, basestring): |
| 230 | raise ValueError( |
| 231 | 'Var\'s argument must be a variable name (file %r, line %s)' % ( |
| 232 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 233 | if not expand_vars: |
| 234 | return '{%s}' % arg |
| 235 | if vars_dict is None: |
| 236 | raise ValueError( |
| 237 | 'vars must be declared before Var can be used (file %r, line %s)' |
| 238 | % (filename, getattr(node, 'lineno', '<unknown>'))) |
| 239 | if arg not in vars_dict: |
| 240 | raise ValueError( |
| 241 | '%s was used as a variable, but was not declared in the vars dict ' |
| 242 | '(file %r, line %s)' % ( |
| 243 | arg, filename, getattr(node, 'lineno', '<unknown>'))) |
| 244 | return vars_dict[arg] |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 245 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): |
| 246 | return _convert(node.left) + _convert(node.right) |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 247 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod): |
| 248 | return _convert(node.left) % _convert(node.right) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 249 | else: |
| 250 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 251 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
| 252 | node, ast.dump(node), filename, |
| 253 | getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 254 | return _convert(node_or_string) |
| 255 | |
| 256 | |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 257 | def Exec(content, expand_vars, filename='<unknown>', vars_override=None): |
| 258 | """Safely execs a set of assignments.""" |
Paweł Hajdan, Jr | c485d5a | 2017-06-02 12:08:09 +0200 | [diff] [blame] | 259 | node_or_string = ast.parse(content, filename=filename, mode='exec') |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 260 | if isinstance(node_or_string, ast.Expression): |
| 261 | node_or_string = node_or_string.body |
| 262 | |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 263 | tokens = { |
| 264 | token[2]: list(token) |
| 265 | for token in tokenize.generate_tokens( |
| 266 | cStringIO.StringIO(content).readline) |
| 267 | } |
| 268 | local_scope = _NodeDict({}, tokens) |
| 269 | vars_dict = {} |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 270 | def _visit_in_module(node): |
| 271 | if isinstance(node, ast.Assign): |
| 272 | if len(node.targets) != 1: |
| 273 | raise ValueError( |
| 274 | 'invalid assignment: use exactly one target (file %r, line %s)' % ( |
| 275 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 276 | target = node.targets[0] |
| 277 | if not isinstance(target, ast.Name): |
| 278 | raise ValueError( |
| 279 | 'invalid assignment: target should be a name (file %r, line %s)' % ( |
| 280 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 281 | value = _gclient_eval(node.value, vars_dict, expand_vars, filename) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 282 | |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 283 | if target.id in local_scope: |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 284 | raise ValueError( |
| 285 | 'invalid assignment: overrides var %r (file %r, line %s)' % ( |
| 286 | target.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 287 | |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 288 | if target.id == 'vars': |
| 289 | vars_dict.update(value) |
| 290 | if vars_override: |
| 291 | vars_dict.update({ |
| 292 | k: v |
| 293 | for k, v in vars_override.iteritems() |
| 294 | if k in vars_dict}) |
| 295 | |
| 296 | local_scope.SetNode(target.id, value, node.value) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 297 | else: |
| 298 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 299 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
| 300 | node, ast.dump(node), filename, |
| 301 | getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 302 | |
| 303 | if isinstance(node_or_string, ast.Module): |
| 304 | for stmt in node_or_string.body: |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 305 | _visit_in_module(stmt) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 306 | else: |
| 307 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 308 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 309 | node_or_string, |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 310 | ast.dump(node_or_string), |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 311 | filename, |
| 312 | getattr(node_or_string, 'lineno', '<unknown>'))) |
| 313 | |
John Budorick | 0f7b200 | 2018-01-19 15:46:17 -0800 | [diff] [blame] | 314 | return _GCLIENT_SCHEMA.validate(local_scope) |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 315 | |
| 316 | |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 317 | def Parse(content, expand_vars, validate_syntax, filename, vars_override=None): |
| 318 | """Parses DEPS strings. |
| 319 | |
| 320 | Executes the Python-like string stored in content, resulting in a Python |
| 321 | dictionary specifyied by the schema above. Supports syntax validation and |
| 322 | variable expansion. |
| 323 | |
| 324 | Args: |
| 325 | content: str. DEPS file stored as a string. |
| 326 | expand_vars: bool. Whether variables should be expanded to their values. |
| 327 | validate_syntax: bool. Whether syntax should be validated using the schema |
| 328 | defined above. |
| 329 | filename: str. The name of the DEPS file, or a string describing the source |
| 330 | of the content, e.g. '<string>', '<unknown>'. |
| 331 | vars_override: dict, optional. A dictionary with overrides for the variables |
| 332 | defined by the DEPS file. |
| 333 | |
| 334 | Returns: |
| 335 | A Python dict with the parsed contents of the DEPS file, as specified by the |
| 336 | schema above. |
| 337 | """ |
| 338 | # TODO(ehmaldonado): Make validate_syntax = True the only case |
| 339 | if validate_syntax: |
| 340 | return Exec(content, expand_vars, filename, vars_override) |
| 341 | |
| 342 | local_scope = {} |
| 343 | global_scope = {'Var': lambda var_name: '{%s}' % var_name} |
| 344 | |
| 345 | # If we use 'exec' directly, it complains that 'Parse' contains a nested |
| 346 | # function with free variables. |
| 347 | # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same |
| 348 | # as "exec a in b, c" (See https://bugs.python.org/issue21591). |
| 349 | eval(compile(content, filename, 'exec'), global_scope, local_scope) |
| 350 | |
| 351 | if 'vars' not in local_scope or not expand_vars: |
| 352 | return local_scope |
| 353 | |
| 354 | vars_dict = {} |
| 355 | vars_dict.update(local_scope['vars']) |
| 356 | if vars_override: |
| 357 | vars_dict.update({ |
| 358 | k: v |
| 359 | for k, v in vars_override.iteritems() |
| 360 | if k in vars_dict |
| 361 | }) |
| 362 | |
| 363 | def _DeepFormat(node): |
| 364 | if isinstance(node, basestring): |
| 365 | return node.format(**vars_dict) |
| 366 | elif isinstance(node, dict): |
| 367 | return { |
| 368 | k.format(**vars_dict): _DeepFormat(v) |
| 369 | for k, v in node.iteritems() |
| 370 | } |
| 371 | elif isinstance(node, list): |
| 372 | return [_DeepFormat(elem) for elem in node] |
| 373 | elif isinstance(node, tuple): |
| 374 | return tuple(_DeepFormat(elem) for elem in node) |
| 375 | else: |
| 376 | return node |
| 377 | |
| 378 | return _DeepFormat(local_scope) |
| 379 | |
| 380 | |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 381 | def EvaluateCondition(condition, variables, referenced_variables=None): |
| 382 | """Safely evaluates a boolean condition. Returns the result.""" |
| 383 | if not referenced_variables: |
| 384 | referenced_variables = set() |
| 385 | _allowed_names = {'None': None, 'True': True, 'False': False} |
| 386 | main_node = ast.parse(condition, mode='eval') |
| 387 | if isinstance(main_node, ast.Expression): |
| 388 | main_node = main_node.body |
| 389 | def _convert(node): |
| 390 | if isinstance(node, ast.Str): |
| 391 | return node.s |
| 392 | elif isinstance(node, ast.Name): |
| 393 | if node.id in referenced_variables: |
| 394 | raise ValueError( |
| 395 | 'invalid cyclic reference to %r (inside %r)' % ( |
| 396 | node.id, condition)) |
| 397 | elif node.id in _allowed_names: |
| 398 | return _allowed_names[node.id] |
| 399 | elif node.id in variables: |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 400 | value = variables[node.id] |
| 401 | |
| 402 | # Allow using "native" types, without wrapping everything in strings. |
| 403 | # Note that schema constraints still apply to variables. |
| 404 | if not isinstance(value, basestring): |
| 405 | return value |
| 406 | |
| 407 | # Recursively evaluate the variable reference. |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 408 | return EvaluateCondition( |
| 409 | variables[node.id], |
| 410 | variables, |
| 411 | referenced_variables.union([node.id])) |
| 412 | else: |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 413 | # Implicitly convert unrecognized names to strings. |
| 414 | # If we want to change this, we'll need to explicitly distinguish |
| 415 | # between arguments for GN to be passed verbatim, and ones to |
| 416 | # be evaluated. |
| 417 | return node.id |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 418 | elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or): |
| 419 | if len(node.values) != 2: |
| 420 | raise ValueError( |
| 421 | 'invalid "or": exactly 2 operands required (inside %r)' % ( |
| 422 | condition)) |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 423 | left = _convert(node.values[0]) |
| 424 | right = _convert(node.values[1]) |
| 425 | if not isinstance(left, bool): |
| 426 | raise ValueError( |
| 427 | 'invalid "or" operand %r (inside %r)' % (left, condition)) |
| 428 | if not isinstance(right, bool): |
| 429 | raise ValueError( |
| 430 | 'invalid "or" operand %r (inside %r)' % (right, condition)) |
| 431 | return left or right |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 432 | elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And): |
| 433 | if len(node.values) != 2: |
| 434 | raise ValueError( |
| 435 | 'invalid "and": exactly 2 operands required (inside %r)' % ( |
| 436 | condition)) |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 437 | left = _convert(node.values[0]) |
| 438 | right = _convert(node.values[1]) |
| 439 | if not isinstance(left, bool): |
| 440 | raise ValueError( |
| 441 | 'invalid "and" operand %r (inside %r)' % (left, condition)) |
| 442 | if not isinstance(right, bool): |
| 443 | raise ValueError( |
| 444 | 'invalid "and" operand %r (inside %r)' % (right, condition)) |
| 445 | return left and right |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 446 | elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 447 | value = _convert(node.operand) |
| 448 | if not isinstance(value, bool): |
| 449 | raise ValueError( |
| 450 | 'invalid "not" operand %r (inside %r)' % (value, condition)) |
| 451 | return not value |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 452 | elif isinstance(node, ast.Compare): |
| 453 | if len(node.ops) != 1: |
| 454 | raise ValueError( |
| 455 | 'invalid compare: exactly 1 operator required (inside %r)' % ( |
| 456 | condition)) |
| 457 | if len(node.comparators) != 1: |
| 458 | raise ValueError( |
| 459 | 'invalid compare: exactly 1 comparator required (inside %r)' % ( |
| 460 | condition)) |
| 461 | |
| 462 | left = _convert(node.left) |
| 463 | right = _convert(node.comparators[0]) |
| 464 | |
| 465 | if isinstance(node.ops[0], ast.Eq): |
| 466 | return left == right |
Dirk Pranke | 77b7687 | 2017-10-05 18:29:27 -0700 | [diff] [blame] | 467 | if isinstance(node.ops[0], ast.NotEq): |
| 468 | return left != right |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 469 | |
| 470 | raise ValueError( |
| 471 | 'unexpected operator: %s %s (inside %r)' % ( |
| 472 | node.ops[0], ast.dump(node), condition)) |
| 473 | else: |
| 474 | raise ValueError( |
| 475 | 'unexpected AST node: %s %s (inside %r)' % ( |
| 476 | node, ast.dump(node), condition)) |
| 477 | return _convert(main_node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 478 | |
| 479 | |
| 480 | def RenderDEPSFile(gclient_dict): |
| 481 | contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2]) |
| 482 | return tokenize.untokenize(contents) |
| 483 | |
| 484 | |
| 485 | def _UpdateAstString(tokens, node, value): |
| 486 | position = node.lineno, node.col_offset |
| 487 | tokens[position][1] = repr(value) |
| 488 | node.s = value |
| 489 | |
| 490 | |
| 491 | def SetVar(gclient_dict, var_name, value): |
| 492 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 493 | raise ValueError( |
| 494 | "Can't use SetVar for the given gclient dict. It contains no " |
| 495 | "formatting information.") |
| 496 | tokens = gclient_dict.tokens |
| 497 | |
| 498 | if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']: |
| 499 | raise ValueError( |
| 500 | "Could not find any variable called %s." % var_name) |
| 501 | |
| 502 | node = gclient_dict['vars'].GetNode(var_name) |
| 503 | if node is None: |
| 504 | raise ValueError( |
| 505 | "The vars entry for %s has no formatting information." % var_name) |
| 506 | |
| 507 | _UpdateAstString(tokens, node, value) |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 508 | gclient_dict['vars'].SetNode(var_name, value, node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 509 | |
| 510 | |
| 511 | def SetCIPD(gclient_dict, dep_name, package_name, new_version): |
| 512 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 513 | raise ValueError( |
| 514 | "Can't use SetCIPD for the given gclient dict. It contains no " |
| 515 | "formatting information.") |
| 516 | tokens = gclient_dict.tokens |
| 517 | |
| 518 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
| 519 | raise ValueError( |
| 520 | "Could not find any dependency called %s." % dep_name) |
| 521 | |
| 522 | # Find the package with the given name |
| 523 | packages = [ |
| 524 | package |
| 525 | for package in gclient_dict['deps'][dep_name]['packages'] |
| 526 | if package['package'] == package_name |
| 527 | ] |
| 528 | if len(packages) != 1: |
| 529 | raise ValueError( |
| 530 | "There must be exactly one package with the given name (%s), " |
| 531 | "%s were found." % (package_name, len(packages))) |
| 532 | |
| 533 | # TODO(ehmaldonado): Support Var in package's version. |
| 534 | node = packages[0].GetNode('version') |
| 535 | if node is None: |
| 536 | raise ValueError( |
| 537 | "The deps entry for %s:%s has no formatting information." % |
| 538 | (dep_name, package_name)) |
| 539 | |
| 540 | new_version = 'version:' + new_version |
| 541 | _UpdateAstString(tokens, node, new_version) |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 542 | packages[0].SetNode('version', new_version, node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 543 | |
| 544 | |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 545 | def SetRevision(gclient_dict, dep_name, new_revision): |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 546 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 547 | raise ValueError( |
| 548 | "Can't use SetRevision for the given gclient dict. It contains no " |
| 549 | "formatting information.") |
| 550 | tokens = gclient_dict.tokens |
| 551 | |
| 552 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
| 553 | raise ValueError( |
| 554 | "Could not find any dependency called %s." % dep_name) |
| 555 | |
| 556 | def _UpdateRevision(dep_dict, dep_key): |
| 557 | dep_node = dep_dict.GetNode(dep_key) |
| 558 | if dep_node is None: |
| 559 | raise ValueError( |
| 560 | "The deps entry for %s has no formatting information." % dep_name) |
| 561 | |
| 562 | node = dep_node |
| 563 | if isinstance(node, ast.BinOp): |
| 564 | node = node.right |
| 565 | if isinstance(node, ast.Call): |
| 566 | SetVar(gclient_dict, node.args[0].s, new_revision) |
| 567 | else: |
| 568 | _UpdateAstString(tokens, node, new_revision) |
Edward Lesmes | 0d9ecc9 | 2018-03-23 15:10:58 -0400 | [diff] [blame] | 569 | value = _gclient_eval(dep_node, gclient_dict.get('vars', None), |
| 570 | expand_vars=True, filename='<unknown>') |
| 571 | dep_dict.SetNode(dep_key, value, dep_node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 572 | |
| 573 | if isinstance(gclient_dict['deps'][dep_name], _NodeDict): |
| 574 | _UpdateRevision(gclient_dict['deps'][dep_name], 'url') |
| 575 | else: |
| 576 | _UpdateRevision(gclient_dict['deps'], dep_name) |