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 |
| 6 | |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 7 | from third_party import schema |
| 8 | |
| 9 | |
| 10 | # See https://github.com/keleshev/schema for docs how to configure schema. |
| 11 | _GCLIENT_HOOKS_SCHEMA = [{ |
| 12 | # Hook action: list of command-line arguments to invoke. |
| 13 | 'action': [basestring], |
| 14 | |
| 15 | # Name of the hook. Doesn't affect operation. |
| 16 | schema.Optional('name'): basestring, |
| 17 | |
| 18 | # Hook pattern (regex). Originally intended to limit some hooks to run |
| 19 | # only when files matching the pattern have changed. In practice, with git, |
| 20 | # gclient runs all the hooks regardless of this field. |
| 21 | schema.Optional('pattern'): basestring, |
| 22 | }] |
| 23 | |
| 24 | _GCLIENT_SCHEMA = schema.Schema({ |
| 25 | # List of host names from which dependencies are allowed (whitelist). |
| 26 | # NOTE: when not present, all hosts are allowed. |
| 27 | # NOTE: scoped to current DEPS file, not recursive. |
| 28 | schema.Optional('allowed_hosts'): [basestring], |
| 29 | |
| 30 | # Mapping from paths to repo and revision to check out under that path. |
| 31 | # Applying this mapping to the on-disk checkout is the main purpose |
| 32 | # of gclient, and also why the config file is called DEPS. |
| 33 | # |
| 34 | # The following functions are allowed: |
| 35 | # |
| 36 | # File(): specifies to expect to checkout a file instead of a directory |
| 37 | # From(): used to fetch a dependency definition from another DEPS file |
| 38 | # Var(): allows variable substitution (either from 'vars' dict below, |
| 39 | # or command-line override) |
| 40 | schema.Optional('deps'): {schema.Optional(basestring): basestring}, |
| 41 | |
| 42 | # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux'). |
| 43 | schema.Optional('deps_os'): {basestring: {basestring: basestring}}, |
| 44 | |
| 45 | # Hooks executed after gclient sync (unless suppressed), or explicitly |
| 46 | # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details. |
| 47 | # Also see 'pre_deps_hooks'. |
| 48 | schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA, |
| 49 | |
| 50 | # Rules which #includes are allowed in the directory. |
| 51 | # Also see 'skip_child_includes' and 'specific_include_rules'. |
| 52 | schema.Optional('include_rules'): [basestring], |
| 53 | |
| 54 | # Hooks executed before processing DEPS. See 'hooks' for more details. |
| 55 | schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA, |
| 56 | |
| 57 | # Whitelists deps for which recursion should be enabled. |
| 58 | schema.Optional('recursedeps'): [ |
| 59 | schema.Or(basestring, (basestring, basestring)) |
| 60 | ], |
| 61 | |
| 62 | # Blacklists directories for checking 'include_rules'. |
| 63 | schema.Optional('skip_child_includes'): [basestring], |
| 64 | |
| 65 | # Mapping from paths to include rules specific for that path. |
| 66 | # See 'include_rules' for more details. |
| 67 | schema.Optional('specific_include_rules'): {basestring: [basestring]}, |
| 68 | |
| 69 | # For recursed-upon sub-dependencies, check out their own dependencies |
| 70 | # relative to the paren't path, rather than relative to the .gclient file. |
| 71 | schema.Optional('use_relative_paths'): bool, |
| 72 | |
| 73 | # Variables that can be referenced using Var() - see 'deps'. |
| 74 | schema.Optional('vars'): {basestring: basestring}, |
| 75 | }) |
| 76 | |
Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 77 | |
| 78 | def _gclient_eval(node_or_string, global_scope, filename='<unknown>'): |
| 79 | """Safely evaluates a single expression. Returns the result.""" |
| 80 | _allowed_names = {'None': None, 'True': True, 'False': False} |
| 81 | if isinstance(node_or_string, basestring): |
| 82 | node_or_string = ast.parse(node_or_string, filename=filename, mode='eval') |
| 83 | if isinstance(node_or_string, ast.Expression): |
| 84 | node_or_string = node_or_string.body |
| 85 | def _convert(node): |
| 86 | if isinstance(node, ast.Str): |
| 87 | return node.s |
| 88 | elif isinstance(node, ast.Tuple): |
| 89 | return tuple(map(_convert, node.elts)) |
| 90 | elif isinstance(node, ast.List): |
| 91 | return list(map(_convert, node.elts)) |
| 92 | elif isinstance(node, ast.Dict): |
| 93 | return dict((_convert(k), _convert(v)) |
| 94 | for k, v in zip(node.keys, node.values)) |
| 95 | elif isinstance(node, ast.Name): |
| 96 | if node.id not in _allowed_names: |
| 97 | raise ValueError( |
| 98 | 'invalid name %r (file %r, line %s)' % ( |
| 99 | node.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 100 | return _allowed_names[node.id] |
| 101 | elif isinstance(node, ast.Call): |
| 102 | if not isinstance(node.func, ast.Name): |
| 103 | raise ValueError( |
| 104 | 'invalid call: func should be a name (file %r, line %s)' % ( |
| 105 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 106 | if node.keywords or node.starargs or node.kwargs: |
| 107 | raise ValueError( |
| 108 | 'invalid call: use only regular args (file %r, line %s)' % ( |
| 109 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 110 | args = map(_convert, node.args) |
| 111 | return global_scope[node.func.id](*args) |
| 112 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): |
| 113 | return _convert(node.left) + _convert(node.right) |
| 114 | else: |
| 115 | raise ValueError( |
| 116 | 'unexpected AST node: %s (file %r, line %s)' % ( |
| 117 | node, filename, getattr(node, 'lineno', '<unknown>'))) |
| 118 | return _convert(node_or_string) |
| 119 | |
| 120 | |
| 121 | def _gclient_exec(node_or_string, global_scope, filename='<unknown>'): |
| 122 | """Safely execs a set of assignments. Returns resulting scope.""" |
| 123 | result_scope = {} |
| 124 | |
| 125 | if isinstance(node_or_string, basestring): |
| 126 | node_or_string = ast.parse(node_or_string, filename=filename, mode='exec') |
| 127 | if isinstance(node_or_string, ast.Expression): |
| 128 | node_or_string = node_or_string.body |
| 129 | |
| 130 | def _visit_in_module(node): |
| 131 | if isinstance(node, ast.Assign): |
| 132 | if len(node.targets) != 1: |
| 133 | raise ValueError( |
| 134 | 'invalid assignment: use exactly one target (file %r, line %s)' % ( |
| 135 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 136 | target = node.targets[0] |
| 137 | if not isinstance(target, ast.Name): |
| 138 | raise ValueError( |
| 139 | 'invalid assignment: target should be a name (file %r, line %s)' % ( |
| 140 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 141 | value = _gclient_eval(node.value, global_scope, filename=filename) |
| 142 | |
| 143 | if target.id in result_scope: |
| 144 | raise ValueError( |
| 145 | 'invalid assignment: overrides var %r (file %r, line %s)' % ( |
| 146 | target.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 147 | |
| 148 | result_scope[target.id] = value |
| 149 | else: |
| 150 | raise ValueError( |
| 151 | 'unexpected AST node: %s (file %r, line %s)' % ( |
| 152 | node, filename, getattr(node, 'lineno', '<unknown>'))) |
| 153 | |
| 154 | if isinstance(node_or_string, ast.Module): |
| 155 | for stmt in node_or_string.body: |
| 156 | _visit_in_module(stmt) |
| 157 | else: |
| 158 | raise ValueError( |
| 159 | 'unexpected AST node: %s (file %r, line %s)' % ( |
| 160 | node_or_string, |
| 161 | filename, |
| 162 | getattr(node_or_string, 'lineno', '<unknown>'))) |
| 163 | |
| 164 | return result_scope |
| 165 | |
| 166 | |
| 167 | class CheckFailure(Exception): |
| 168 | """Contains details of a check failure.""" |
| 169 | def __init__(self, msg, path, exp, act): |
| 170 | super(CheckFailure, self).__init__(msg) |
| 171 | self.path = path |
| 172 | self.exp = exp |
| 173 | self.act = act |
| 174 | |
| 175 | |
| 176 | def Check(content, path, global_scope, expected_scope): |
| 177 | """Cross-checks the old and new gclient eval logic. |
| 178 | |
| 179 | Safely execs |content| (backed by file |path|) using |global_scope|, |
| 180 | and compares with |expected_scope|. |
| 181 | |
| 182 | Throws CheckFailure if any difference between |expected_scope| and scope |
| 183 | returned by new gclient eval code is detected. |
| 184 | """ |
| 185 | def fail(prefix, exp, act): |
| 186 | raise CheckFailure( |
| 187 | 'gclient check for %s: %s exp %s, got %s' % ( |
| 188 | path, prefix, repr(exp), repr(act)), prefix, exp, act) |
| 189 | |
| 190 | def compare(expected, actual, var_path, actual_scope): |
| 191 | if isinstance(expected, dict): |
| 192 | exp = set(expected.keys()) |
| 193 | act = set(actual.keys()) |
| 194 | if exp != act: |
| 195 | fail(var_path, exp, act) |
| 196 | for k in expected: |
| 197 | compare(expected[k], actual[k], var_path + '["%s"]' % k, actual_scope) |
| 198 | return |
| 199 | elif isinstance(expected, list): |
| 200 | exp = len(expected) |
| 201 | act = len(actual) |
| 202 | if exp != act: |
| 203 | fail('len(%s)' % var_path, expected_scope, actual_scope) |
| 204 | for i in range(exp): |
| 205 | compare(expected[i], actual[i], var_path + '[%d]' % i, actual_scope) |
| 206 | else: |
| 207 | if expected != actual: |
| 208 | fail(var_path, expected_scope, actual_scope) |
| 209 | |
| 210 | result_scope = _gclient_exec(content, global_scope, filename=path) |
| 211 | |
| 212 | compare(expected_scope, result_scope, '', result_scope) |
Paweł Hajdan, Jr | beec006 | 2017-05-10 21:51:05 +0200 | [diff] [blame] | 213 | |
| 214 | _GCLIENT_SCHEMA.validate(result_scope) |