-
Notifications
You must be signed in to change notification settings - Fork 66
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ENH: implement variables substitution in configuration
- Loading branch information
Showing
8 changed files
with
168 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
# SPDX-FileCopyrightText: 2023 The meson-python developers | ||
# | ||
# SPDX-License-Identifier: MIT | ||
|
||
from __future__ import annotations | ||
|
||
import ast | ||
import operator | ||
import typing | ||
|
||
|
||
if typing.TYPE_CHECKING: # pragma: no cover | ||
from typing import Any, Callable, Mapping, Optional, Type | ||
|
||
|
||
_methods = {} | ||
|
||
|
||
def _register(nodetype: Type[ast.AST]) -> Callable[..., Callable[..., Any]]: | ||
def closure(method: Callable[[Interpreter, ast.AST], Any]) -> Callable[[Interpreter, ast.AST], Any]: | ||
_methods[nodetype] = method | ||
return method | ||
return closure | ||
|
||
|
||
class Interpreter: | ||
|
||
_operators = { | ||
ast.Add: operator.add, | ||
ast.Sub: operator.sub, | ||
ast.Mult: operator.mul, | ||
ast.Div: operator.truediv, | ||
} | ||
|
||
def __init__(self, variables: Mapping[str, Any]): | ||
self._variables = variables | ||
|
||
def eval(self, string: str) -> Any: | ||
try: | ||
expr = ast.parse(string, mode='eval') | ||
return self._eval(expr) | ||
except KeyError as exc: | ||
raise ValueError(f'unknown variable "{exc.args[0]}"') from exc | ||
except NotImplementedError as exc: | ||
raise ValueError(f'invalid expression {string!r}') from exc | ||
|
||
__getitem__ = eval | ||
|
||
def _eval(self, node: ast.AST) -> Any: | ||
# Cannot use functools.singlemethoddispatch as long as Python 3.7 is supported. | ||
method = _methods.get(type(node), None) | ||
if method is None: | ||
raise NotImplementedError | ||
return method(self, node) | ||
|
||
@_register(ast.Expression) | ||
def _expression(self, node: ast.Expression) -> Any: | ||
return self._eval(node.body) | ||
|
||
@_register(ast.BinOp) | ||
def _binop(self, node: ast.BinOp) -> Any: | ||
func = self._operators.get(type(node.op)) | ||
if func is None: | ||
raise NotImplementedError | ||
return func(self._eval(node.left), self._eval(node.right)) | ||
|
||
@_register(ast.Constant) | ||
def _constant(self, node: ast.Constant) -> Any: | ||
return node.value | ||
|
||
# Python 3.7, replaced by ast.Constant is later versions. | ||
@_register(ast.Num) | ||
def _num(self, node: ast.Num) -> Any: | ||
return node.n | ||
|
||
# Python 3.7, replaced by ast.Constant is later versions. | ||
@_register(ast.Str) | ||
def _str(self, node: ast.Str) -> Any: | ||
return node.s | ||
|
||
@_register(ast.Name) | ||
def _variable(self, node: ast.Name) -> Any: | ||
value = self._variables[node.id] | ||
if callable(value): | ||
value = value() | ||
return value | ||
|
||
|
||
def _ncores() -> int: | ||
return 42 | ||
|
||
|
||
def interpolate(string: str, variables: Optional[Mapping[str, Any]] = None) -> str: | ||
if variables is None: | ||
variables = {'ncores': _ncores} | ||
return string % Interpreter(variables) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# SPDX-FileCopyrightText: 2023 The meson-python developers | ||
# | ||
# SPDX-License-Identifier: MIT | ||
|
||
project('substitutions', version: '0.0.1') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# SPDX-FileCopyrightText: 2023 The meson-python developers | ||
# | ||
# SPDX-License-Identifier: MIT | ||
|
||
[build-system] | ||
build-backend = 'mesonpy' | ||
requires = ['meson-python'] | ||
|
||
[tool.meson-python.args] | ||
compile = ['-j', '%(xxx)d'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# SPDX-FileCopyrightText: 2023 The meson-python developers | ||
# | ||
# SPDX-License-Identifier: MIT | ||
|
||
project('substitutions', version: '0.0.1') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# SPDX-FileCopyrightText: 2023 The meson-python developers | ||
# | ||
# SPDX-License-Identifier: MIT | ||
|
||
[build-system] | ||
build-backend = 'mesonpy' | ||
requires = ['meson-python'] | ||
|
||
[tool.meson-python.args] | ||
compile = ['-j', '%(ncores / 2 + 2)d'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# SPDX-FileCopyrightText: 2023 The meson-python developers | ||
# | ||
# SPDX-License-Identifier: MIT | ||
|
||
import pytest | ||
|
||
import mesonpy | ||
|
||
|
||
def test_interpolate(): | ||
assert mesonpy._substitutions.interpolate('%(x * 2 + 3 - 4 / 1)d', {'x': 1}) == '1' | ||
|
||
|
||
def test_interpolate_key_error(): | ||
with pytest.raises(RuntimeError, match='unknown variable "y"'): | ||
mesonpy._substitutions.interpolate('%(y)d', {'x': 1}) | ||
|
||
|
||
def test_interpolate_not_implemented(): | ||
with pytest.raises(RuntimeError, match='invalid expression'): | ||
mesonpy._substitutions.interpolate('%(x ** 2)d', {'x': 1}) | ||
|
||
|
||
def test_substitutions(package_substitutions, monkeypatch): | ||
monkeypatch.setattr(mesonpy._substitutions, '_ncores', lambda: 2) | ||
with mesonpy._project() as project: | ||
assert project._meson_args['compile'] == ['-j', '3'] | ||
|
||
|
||
def test_substitutions_invalid(package_substitutions_invalid, monkeypatch): | ||
monkeypatch.setattr(mesonpy._substitutions, '_ncores', lambda: 2) | ||
with pytest.raises(mesonpy.ConfigError, match=''): | ||
with mesonpy._project(): | ||
pass |