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