Skip to content

Commit 58bba11

Browse files
committed
ENH: implement variables substitution in configuration
1 parent 71f5926 commit 58bba11

File tree

8 files changed

+171
-0
lines changed

8 files changed

+171
-0
lines changed

meson.build

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ py.install_sources(
1111
'mesonpy/_compat.py',
1212
'mesonpy/_editable.py',
1313
'mesonpy/_rpath.py',
14+
'mesonpy/_substitutions.py',
1415
'mesonpy/_tags.py',
1516
'mesonpy/_util.py',
1617
'mesonpy/_wheelfile.py',

mesonpy/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747

4848
import mesonpy._compat
4949
import mesonpy._rpath
50+
import mesonpy._substitutions
5051
import mesonpy._tags
5152
import mesonpy._util
5253
import mesonpy._wheelfile
@@ -660,6 +661,12 @@ def __init__( # noqa: C901
660661
# load meson args from pyproject.toml
661662
pyproject_config = _validate_pyproject_config(pyproject)
662663
for key, value in pyproject_config.get('args', {}).items():
664+
# apply variable interpolation
665+
try:
666+
value = [mesonpy._substitutions.interpolate(x) for x in value]
667+
except ValueError as exc:
668+
raise ConfigError(
669+
f'Cannot interpret value for "tool.meson-python.args.{key}" configuration entry: {exc.args[0]}') from None
663670
self._meson_args[key].extend(value)
664671

665672
# meson arguments from the command line take precedence over

mesonpy/_substitutions.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# SPDX-FileCopyrightText: 2023 The meson-python developers
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
from __future__ import annotations
6+
7+
import ast
8+
import operator
9+
import sys
10+
import typing
11+
12+
13+
if typing.TYPE_CHECKING: # pragma: no cover
14+
from typing import Any, Callable, Mapping, Optional, Type
15+
16+
17+
_methods = {}
18+
19+
20+
def _register(nodetype: Type[ast.AST]) -> Callable[..., Callable[..., Any]]:
21+
def closure(method: Callable[[Interpreter, ast.AST], Any]) -> Callable[[Interpreter, ast.AST], Any]:
22+
_methods[nodetype] = method
23+
return method
24+
return closure
25+
26+
27+
class Interpreter:
28+
29+
_operators = {
30+
ast.Add: operator.add,
31+
ast.Sub: operator.sub,
32+
ast.Mult: operator.mul,
33+
ast.Div: operator.truediv,
34+
}
35+
36+
def __init__(self, variables: Mapping[str, Any]):
37+
self._variables = variables
38+
39+
def eval(self, string: str) -> Any:
40+
try:
41+
expr = ast.parse(string, mode='eval')
42+
return self._eval(expr)
43+
except KeyError as exc:
44+
raise ValueError(f'unknown variable "{exc.args[0]}"') from exc
45+
except NotImplementedError as exc:
46+
raise ValueError(f'invalid expression {string!r}') from exc
47+
48+
__getitem__ = eval
49+
50+
def _eval(self, node: ast.AST) -> Any:
51+
# Cannot use functools.singlemethoddispatch as long as Python 3.7 is supported.
52+
method = _methods.get(type(node), None)
53+
if method is None:
54+
raise NotImplementedError
55+
return method(self, node)
56+
57+
@_register(ast.Expression)
58+
def _expression(self, node: ast.Expression) -> Any:
59+
return self._eval(node.body)
60+
61+
@_register(ast.BinOp)
62+
def _binop(self, node: ast.BinOp) -> Any:
63+
func = self._operators.get(type(node.op))
64+
if func is None:
65+
raise NotImplementedError
66+
return func(self._eval(node.left), self._eval(node.right))
67+
68+
@_register(ast.Constant)
69+
def _constant(self, node: ast.Constant) -> Any:
70+
return node.value
71+
72+
if sys.version_info < (3, 8):
73+
74+
# Python 3.7, replaced by ast.Constant is later versions.
75+
@_register(ast.Num)
76+
def _num(self, node: ast.Num) -> Any:
77+
return node.n
78+
79+
# Python 3.7, replaced by ast.Constant is later versions.
80+
@_register(ast.Str)
81+
def _str(self, node: ast.Str) -> Any:
82+
return node.s
83+
84+
@_register(ast.Name)
85+
def _variable(self, node: ast.Name) -> Any:
86+
value = self._variables[node.id]
87+
if callable(value):
88+
value = value()
89+
return value
90+
91+
92+
def _ncores() -> int:
93+
return 42
94+
95+
96+
def interpolate(string: str, variables: Optional[Mapping[str, Any]] = None) -> str:
97+
if variables is None:
98+
variables = {'ncores': _ncores}
99+
return string % Interpreter(variables)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# SPDX-FileCopyrightText: 2023 The meson-python developers
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
project('substitutions', version: '0.0.1')
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# SPDX-FileCopyrightText: 2023 The meson-python developers
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
[build-system]
6+
build-backend = 'mesonpy'
7+
requires = ['meson-python']
8+
9+
[tool.meson-python.args]
10+
compile = ['-j', '%(xxx)d']
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# SPDX-FileCopyrightText: 2023 The meson-python developers
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
project('substitutions', version: '0.0.1')
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# SPDX-FileCopyrightText: 2023 The meson-python developers
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
[build-system]
6+
build-backend = 'mesonpy'
7+
requires = ['meson-python']
8+
9+
[tool.meson-python.args]
10+
compile = ['-j', '%(ncores / 2 + 2)d']

tests/test_substitutions.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# SPDX-FileCopyrightText: 2023 The meson-python developers
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import pytest
6+
7+
import mesonpy
8+
9+
10+
def test_interpolate():
11+
assert mesonpy._substitutions.interpolate('%(x * 2 + 3 - 4 / 1)d', {'x': 1}) == '1'
12+
13+
14+
def test_interpolate_key_error():
15+
with pytest.raises(ValueError, match='unknown variable "y"'):
16+
mesonpy._substitutions.interpolate('%(y)d', {'x': 1})
17+
18+
19+
def test_interpolate_not_implemented():
20+
with pytest.raises(ValueError, match='invalid expression'):
21+
mesonpy._substitutions.interpolate('%(x ** 2)d', {'x': 1})
22+
23+
24+
def test_substitutions(package_substitutions, monkeypatch):
25+
monkeypatch.setattr(mesonpy._substitutions, '_ncores', lambda: 2)
26+
with mesonpy._project() as project:
27+
assert project._meson_args['compile'] == ['-j', '3']
28+
29+
30+
def test_substitutions_invalid(package_substitutions_invalid, monkeypatch):
31+
monkeypatch.setattr(mesonpy._substitutions, '_ncores', lambda: 2)
32+
with pytest.raises(mesonpy.ConfigError, match=''):
33+
with mesonpy._project():
34+
pass

0 commit comments

Comments
 (0)