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 | 6c24d37 | 2018-03-28 12:52:29 -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 | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 186 | def _gclient_eval(node_or_string, vars_dict=None, expand_vars=False, |
| 187 | filename='<unknown>'): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 188 | """Safely evaluates a single expression. Returns the result.""" |
| 189 | _allowed_names = {'None': None, 'True': True, 'False': False} |
| 190 | if isinstance(node_or_string, basestring): |
| 191 | node_or_string = ast.parse(node_or_string, filename=filename, mode='eval') |
| 192 | if isinstance(node_or_string, ast.Expression): |
| 193 | node_or_string = node_or_string.body |
| 194 | def _convert(node): |
| 195 | if isinstance(node, ast.Str): |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 196 | if not expand_vars: |
| 197 | return node.s |
| 198 | try: |
| 199 | return node.s.format(**vars_dict) |
| 200 | except KeyError as e: |
| 201 | raise ValueError( |
| 202 | '%s was used as a variable, but was not declared in the vars dict ' |
| 203 | '(file %r, line %s)' % ( |
| 204 | e.message, filename, getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | 6f79679 | 2017-06-02 08:40:06 +0200 | [diff] [blame] | 205 | elif isinstance(node, ast.Num): |
| 206 | return node.n |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 207 | elif isinstance(node, ast.Tuple): |
| 208 | return tuple(map(_convert, node.elts)) |
| 209 | elif isinstance(node, ast.List): |
| 210 | return list(map(_convert, node.elts)) |
| 211 | elif isinstance(node, ast.Dict): |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 212 | return _NodeDict((_convert(k), (_convert(v), v)) |
Paweł Hajdan, Jr | 7cf96a4 | 2017-05-26 20:28:35 +0200 | [diff] [blame] | 213 | for k, v in zip(node.keys, node.values)) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 214 | elif isinstance(node, ast.Name): |
| 215 | if node.id not in _allowed_names: |
| 216 | raise ValueError( |
| 217 | 'invalid name %r (file %r, line %s)' % ( |
| 218 | node.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 219 | return _allowed_names[node.id] |
| 220 | elif isinstance(node, ast.Call): |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 221 | 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] | 222 | raise ValueError( |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 223 | 'Var is the only allowed function (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 224 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 225 | 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] | 226 | raise ValueError( |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 227 | 'Var takes exactly one argument (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 228 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 229 | arg = _convert(node.args[0]) |
| 230 | if not isinstance(arg, basestring): |
| 231 | raise ValueError( |
| 232 | 'Var\'s argument must be a variable name (file %r, line %s)' % ( |
| 233 | filename, getattr(node, 'lineno', '<unknown>'))) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 234 | if not expand_vars: |
| 235 | return '{%s}' % arg |
| 236 | if vars_dict is None: |
| 237 | raise ValueError( |
| 238 | 'vars must be declared before Var can be used (file %r, line %s)' |
| 239 | % (filename, getattr(node, 'lineno', '<unknown>'))) |
| 240 | if arg not in vars_dict: |
| 241 | raise ValueError( |
| 242 | '%s was used as a variable, but was not declared in the vars dict ' |
| 243 | '(file %r, line %s)' % ( |
| 244 | arg, filename, getattr(node, 'lineno', '<unknown>'))) |
| 245 | return vars_dict[arg] |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 246 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): |
| 247 | return _convert(node.left) + _convert(node.right) |
Paweł Hajdan, Jr | b7e5333 | 2017-05-23 16:57:37 +0200 | [diff] [blame] | 248 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod): |
| 249 | return _convert(node.left) % _convert(node.right) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 250 | else: |
| 251 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 252 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
| 253 | node, ast.dump(node), filename, |
| 254 | getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 255 | return _convert(node_or_string) |
| 256 | |
| 257 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 258 | def Exec(content, expand_vars=True, filename='<unknown>', vars_override=None): |
| 259 | """Safely execs a set of assignments.""" |
| 260 | def _validate_statement(node, local_scope): |
| 261 | if not isinstance(node, ast.Assign): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 262 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 263 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
| 264 | node, ast.dump(node), filename, |
| 265 | getattr(node, 'lineno', '<unknown>'))) |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 266 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 267 | if len(node.targets) != 1: |
| 268 | raise ValueError( |
| 269 | 'invalid assignment: use exactly one target (file %r, line %s)' % ( |
| 270 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 271 | |
| 272 | target = node.targets[0] |
| 273 | if not isinstance(target, ast.Name): |
| 274 | raise ValueError( |
| 275 | 'invalid assignment: target should be a name (file %r, line %s)' % ( |
| 276 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 277 | if target.id in local_scope: |
| 278 | raise ValueError( |
| 279 | 'invalid assignment: overrides var %r (file %r, line %s)' % ( |
| 280 | target.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 281 | |
| 282 | node_or_string = ast.parse(content, filename=filename, mode='exec') |
| 283 | if isinstance(node_or_string, ast.Expression): |
| 284 | node_or_string = node_or_string.body |
| 285 | |
| 286 | if not isinstance(node_or_string, ast.Module): |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 287 | raise ValueError( |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 288 | 'unexpected AST node: %s %s (file %r, line %s)' % ( |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 289 | node_or_string, |
Paweł Hajdan, Jr | 1ba610b | 2017-05-24 20:14:44 +0200 | [diff] [blame] | 290 | ast.dump(node_or_string), |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 291 | filename, |
| 292 | getattr(node_or_string, 'lineno', '<unknown>'))) |
| 293 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 294 | statements = {} |
| 295 | for statement in node_or_string.body: |
| 296 | _validate_statement(statement, statements) |
| 297 | statements[statement.targets[0].id] = statement.value |
| 298 | |
| 299 | tokens = { |
| 300 | token[2]: list(token) |
| 301 | for token in tokenize.generate_tokens( |
| 302 | cStringIO.StringIO(content).readline) |
| 303 | } |
| 304 | local_scope = _NodeDict({}, tokens) |
| 305 | |
| 306 | # Process vars first, so we can expand variables in the rest of the DEPS file. |
| 307 | vars_dict = {} |
| 308 | if 'vars' in statements: |
| 309 | vars_statement = statements['vars'] |
| 310 | value = _gclient_eval(vars_statement, None, False, filename) |
| 311 | local_scope.SetNode('vars', value, vars_statement) |
| 312 | # Update the parsed vars with the overrides, but only if they are already |
| 313 | # present (overrides do not introduce new variables). |
| 314 | vars_dict.update(value) |
| 315 | if vars_override: |
| 316 | vars_dict.update({ |
| 317 | k: v |
| 318 | for k, v in vars_override.iteritems() |
| 319 | if k in vars_dict}) |
| 320 | |
| 321 | for name, node in statements.iteritems(): |
| 322 | value = _gclient_eval(node, vars_dict, expand_vars, filename) |
| 323 | local_scope.SetNode(name, value, node) |
| 324 | |
John Budorick | 0f7b200 | 2018-01-19 15:46:17 -0800 | [diff] [blame] | 325 | return _GCLIENT_SCHEMA.validate(local_scope) |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 326 | |
| 327 | |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 328 | def Parse(content, expand_vars, validate_syntax, filename, vars_override=None): |
| 329 | """Parses DEPS strings. |
| 330 | |
| 331 | Executes the Python-like string stored in content, resulting in a Python |
| 332 | dictionary specifyied by the schema above. Supports syntax validation and |
| 333 | variable expansion. |
| 334 | |
| 335 | Args: |
| 336 | content: str. DEPS file stored as a string. |
| 337 | expand_vars: bool. Whether variables should be expanded to their values. |
| 338 | validate_syntax: bool. Whether syntax should be validated using the schema |
| 339 | defined above. |
| 340 | filename: str. The name of the DEPS file, or a string describing the source |
| 341 | of the content, e.g. '<string>', '<unknown>'. |
| 342 | vars_override: dict, optional. A dictionary with overrides for the variables |
| 343 | defined by the DEPS file. |
| 344 | |
| 345 | Returns: |
| 346 | A Python dict with the parsed contents of the DEPS file, as specified by the |
| 347 | schema above. |
| 348 | """ |
| 349 | # TODO(ehmaldonado): Make validate_syntax = True the only case |
| 350 | if validate_syntax: |
| 351 | return Exec(content, expand_vars, filename, vars_override) |
| 352 | |
| 353 | local_scope = {} |
| 354 | global_scope = {'Var': lambda var_name: '{%s}' % var_name} |
| 355 | |
| 356 | # If we use 'exec' directly, it complains that 'Parse' contains a nested |
| 357 | # function with free variables. |
| 358 | # This is because on versions of Python < 2.7.9, "exec(a, b, c)" not the same |
| 359 | # as "exec a in b, c" (See https://bugs.python.org/issue21591). |
| 360 | eval(compile(content, filename, 'exec'), global_scope, local_scope) |
| 361 | |
| 362 | if 'vars' not in local_scope or not expand_vars: |
| 363 | return local_scope |
| 364 | |
| 365 | vars_dict = {} |
| 366 | vars_dict.update(local_scope['vars']) |
| 367 | if vars_override: |
| 368 | vars_dict.update({ |
| 369 | k: v |
| 370 | for k, v in vars_override.iteritems() |
| 371 | if k in vars_dict |
| 372 | }) |
| 373 | |
| 374 | def _DeepFormat(node): |
| 375 | if isinstance(node, basestring): |
| 376 | return node.format(**vars_dict) |
| 377 | elif isinstance(node, dict): |
| 378 | return { |
| 379 | k.format(**vars_dict): _DeepFormat(v) |
| 380 | for k, v in node.iteritems() |
| 381 | } |
| 382 | elif isinstance(node, list): |
| 383 | return [_DeepFormat(elem) for elem in node] |
| 384 | elif isinstance(node, tuple): |
| 385 | return tuple(_DeepFormat(elem) for elem in node) |
| 386 | else: |
| 387 | return node |
| 388 | |
| 389 | return _DeepFormat(local_scope) |
| 390 | |
| 391 | |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 392 | def EvaluateCondition(condition, variables, referenced_variables=None): |
| 393 | """Safely evaluates a boolean condition. Returns the result.""" |
| 394 | if not referenced_variables: |
| 395 | referenced_variables = set() |
| 396 | _allowed_names = {'None': None, 'True': True, 'False': False} |
| 397 | main_node = ast.parse(condition, mode='eval') |
| 398 | if isinstance(main_node, ast.Expression): |
| 399 | main_node = main_node.body |
| 400 | def _convert(node): |
| 401 | if isinstance(node, ast.Str): |
| 402 | return node.s |
| 403 | elif isinstance(node, ast.Name): |
| 404 | if node.id in referenced_variables: |
| 405 | raise ValueError( |
| 406 | 'invalid cyclic reference to %r (inside %r)' % ( |
| 407 | node.id, condition)) |
| 408 | elif node.id in _allowed_names: |
| 409 | return _allowed_names[node.id] |
| 410 | elif node.id in variables: |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 411 | value = variables[node.id] |
| 412 | |
| 413 | # Allow using "native" types, without wrapping everything in strings. |
| 414 | # Note that schema constraints still apply to variables. |
| 415 | if not isinstance(value, basestring): |
| 416 | return value |
| 417 | |
| 418 | # Recursively evaluate the variable reference. |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 419 | return EvaluateCondition( |
| 420 | variables[node.id], |
| 421 | variables, |
| 422 | referenced_variables.union([node.id])) |
| 423 | else: |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 424 | # Implicitly convert unrecognized names to strings. |
| 425 | # If we want to change this, we'll need to explicitly distinguish |
| 426 | # between arguments for GN to be passed verbatim, and ones to |
| 427 | # be evaluated. |
| 428 | return node.id |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 429 | elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or): |
| 430 | if len(node.values) != 2: |
| 431 | raise ValueError( |
| 432 | 'invalid "or": exactly 2 operands required (inside %r)' % ( |
| 433 | condition)) |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 434 | left = _convert(node.values[0]) |
| 435 | right = _convert(node.values[1]) |
| 436 | if not isinstance(left, bool): |
| 437 | raise ValueError( |
| 438 | 'invalid "or" operand %r (inside %r)' % (left, condition)) |
| 439 | if not isinstance(right, bool): |
| 440 | raise ValueError( |
| 441 | 'invalid "or" operand %r (inside %r)' % (right, condition)) |
| 442 | return left or right |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 443 | elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And): |
| 444 | if len(node.values) != 2: |
| 445 | raise ValueError( |
| 446 | 'invalid "and": exactly 2 operands required (inside %r)' % ( |
| 447 | condition)) |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 448 | left = _convert(node.values[0]) |
| 449 | right = _convert(node.values[1]) |
| 450 | if not isinstance(left, bool): |
| 451 | raise ValueError( |
| 452 | 'invalid "and" operand %r (inside %r)' % (left, condition)) |
| 453 | if not isinstance(right, bool): |
| 454 | raise ValueError( |
| 455 | 'invalid "and" operand %r (inside %r)' % (right, condition)) |
| 456 | return left and right |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 457 | elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): |
Paweł Hajdan, Jr | e021474 | 2017-09-28 12:21:01 +0200 | [diff] [blame] | 458 | value = _convert(node.operand) |
| 459 | if not isinstance(value, bool): |
| 460 | raise ValueError( |
| 461 | 'invalid "not" operand %r (inside %r)' % (value, condition)) |
| 462 | return not value |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 463 | elif isinstance(node, ast.Compare): |
| 464 | if len(node.ops) != 1: |
| 465 | raise ValueError( |
| 466 | 'invalid compare: exactly 1 operator required (inside %r)' % ( |
| 467 | condition)) |
| 468 | if len(node.comparators) != 1: |
| 469 | raise ValueError( |
| 470 | 'invalid compare: exactly 1 comparator required (inside %r)' % ( |
| 471 | condition)) |
| 472 | |
| 473 | left = _convert(node.left) |
| 474 | right = _convert(node.comparators[0]) |
| 475 | |
| 476 | if isinstance(node.ops[0], ast.Eq): |
| 477 | return left == right |
Dirk Pranke | 77b7687 | 2017-10-05 18:29:27 -0700 | [diff] [blame] | 478 | if isinstance(node.ops[0], ast.NotEq): |
| 479 | return left != right |
Paweł Hajdan, Jr | 76c6ea2 | 2017-06-02 21:46:57 +0200 | [diff] [blame] | 480 | |
| 481 | raise ValueError( |
| 482 | 'unexpected operator: %s %s (inside %r)' % ( |
| 483 | node.ops[0], ast.dump(node), condition)) |
| 484 | else: |
| 485 | raise ValueError( |
| 486 | 'unexpected AST node: %s %s (inside %r)' % ( |
| 487 | node, ast.dump(node), condition)) |
| 488 | return _convert(main_node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 489 | |
| 490 | |
| 491 | def RenderDEPSFile(gclient_dict): |
| 492 | contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2]) |
| 493 | return tokenize.untokenize(contents) |
| 494 | |
| 495 | |
| 496 | def _UpdateAstString(tokens, node, value): |
| 497 | position = node.lineno, node.col_offset |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 498 | quote_char = tokens[position][1][0] |
| 499 | tokens[position][1] = quote_char + value + quote_char |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 500 | node.s = value |
| 501 | |
| 502 | |
| 503 | def SetVar(gclient_dict, var_name, value): |
| 504 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 505 | raise ValueError( |
| 506 | "Can't use SetVar for the given gclient dict. It contains no " |
| 507 | "formatting information.") |
| 508 | tokens = gclient_dict.tokens |
| 509 | |
| 510 | if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']: |
| 511 | raise ValueError( |
| 512 | "Could not find any variable called %s." % var_name) |
| 513 | |
| 514 | node = gclient_dict['vars'].GetNode(var_name) |
| 515 | if node is None: |
| 516 | raise ValueError( |
| 517 | "The vars entry for %s has no formatting information." % var_name) |
| 518 | |
| 519 | _UpdateAstString(tokens, node, value) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 520 | gclient_dict['vars'].SetNode(var_name, value, node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 521 | |
| 522 | |
| 523 | def SetCIPD(gclient_dict, dep_name, package_name, new_version): |
| 524 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 525 | raise ValueError( |
| 526 | "Can't use SetCIPD for the given gclient dict. It contains no " |
| 527 | "formatting information.") |
| 528 | tokens = gclient_dict.tokens |
| 529 | |
| 530 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
| 531 | raise ValueError( |
| 532 | "Could not find any dependency called %s." % dep_name) |
| 533 | |
| 534 | # Find the package with the given name |
| 535 | packages = [ |
| 536 | package |
| 537 | for package in gclient_dict['deps'][dep_name]['packages'] |
| 538 | if package['package'] == package_name |
| 539 | ] |
| 540 | if len(packages) != 1: |
| 541 | raise ValueError( |
| 542 | "There must be exactly one package with the given name (%s), " |
| 543 | "%s were found." % (package_name, len(packages))) |
| 544 | |
| 545 | # TODO(ehmaldonado): Support Var in package's version. |
| 546 | node = packages[0].GetNode('version') |
| 547 | if node is None: |
| 548 | raise ValueError( |
| 549 | "The deps entry for %s:%s has no formatting information." % |
| 550 | (dep_name, package_name)) |
| 551 | |
| 552 | new_version = 'version:' + new_version |
| 553 | _UpdateAstString(tokens, node, new_version) |
Edward Lesmes | 6c24d37 | 2018-03-28 12:52:29 -0400 | [diff] [blame] | 554 | packages[0].SetNode('version', new_version, node) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 555 | |
| 556 | |
Edward Lesmes | 9f53129 | 2018-03-20 21:27:15 -0400 | [diff] [blame] | 557 | def SetRevision(gclient_dict, dep_name, new_revision): |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 558 | def _GetVarName(node): |
| 559 | if isinstance(node, ast.Call): |
| 560 | return node.args[0].s |
| 561 | elif node.s.endswith('}'): |
| 562 | last_brace = node.s.rfind('{') |
| 563 | return node.s[last_brace+1:-1] |
| 564 | return None |
| 565 | |
| 566 | def _UpdateRevision(dep_dict, dep_key, new_revision): |
| 567 | dep_node = dep_dict.GetNode(dep_key) |
| 568 | if dep_node is None: |
| 569 | raise ValueError( |
| 570 | "The deps entry for %s has no formatting information." % dep_name) |
| 571 | |
| 572 | node = dep_node |
| 573 | if isinstance(node, ast.BinOp): |
| 574 | node = node.right |
| 575 | |
| 576 | if not isinstance(node, ast.Call) and not isinstance(node, ast.Str): |
| 577 | raise ValueError( |
| 578 | "Unsupported dependency revision format. Please file a bug.") |
| 579 | |
| 580 | var_name = _GetVarName(node) |
| 581 | if var_name is not None: |
| 582 | SetVar(gclient_dict, var_name, new_revision) |
| 583 | else: |
| 584 | if '@' in node.s: |
| 585 | new_revision = node.s.split('@')[0] + '@' + new_revision |
| 586 | _UpdateAstString(tokens, node, new_revision) |
| 587 | dep_dict.SetNode(dep_key, new_revision, node) |
| 588 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 589 | if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None: |
| 590 | raise ValueError( |
| 591 | "Can't use SetRevision for the given gclient dict. It contains no " |
| 592 | "formatting information.") |
| 593 | tokens = gclient_dict.tokens |
| 594 | |
| 595 | if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']: |
| 596 | raise ValueError( |
| 597 | "Could not find any dependency called %s." % dep_name) |
| 598 | |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 599 | if isinstance(gclient_dict['deps'][dep_name], _NodeDict): |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 600 | _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision) |
Edward Lesmes | 6f64a05 | 2018-03-20 17:35:49 -0400 | [diff] [blame] | 601 | else: |
Edward Lesmes | 62af4e4 | 2018-03-30 18:15:44 -0400 | [diff] [blame] | 602 | _UpdateRevision(gclient_dict['deps'], dep_name, new_revision) |