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