| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import importlib |
| 4 |
import shutil |
| 5 |
import json |
| 6 |
import typing as T |
| 7 |
|
| 8 |
from ..mesonlib import MesonException, Popen_safe |
| 9 |
if T.TYPE_CHECKING: |
| 10 |
from types import ModuleType |
| 11 |
|
| 12 |
|
| 13 |
# tomllib is present in python 3.11, before that it is a pypi module called tomli, |
| 14 |
# we try to import tomllib, then tomli, |
| 15 |
tomllib: T.Optional[ModuleType] = None |
| 16 |
toml2json: T.Optional[str] = None |
| 17 |
for t in ['tomllib', 'tomli']: |
| 18 |
try: |
| 19 |
tomllib = importlib.import_module(t) |
| 20 |
break |
| 21 |
except ImportError: |
| 22 |
pass |
| 23 |
else: |
| 24 |
# TODO: it would be better to use an Executable here, which could be looked |
| 25 |
# up in the cross file or provided by a wrap. However, that will have to be |
| 26 |
# passed in externally, since we don't have (and I don't think we should), |
| 27 |
# have access to the `Environment` for that in this module. |
| 28 |
toml2json = shutil.which('toml2json') |
| 29 |
|
| 30 |
class TomlImplementationMissing(MesonException): |
| 31 |
pass |
| 32 |
|
| 33 |
|
| 34 |
class CargoTomlError(MesonException): |
| 35 |
"""Exception for TOML parsing errors, keeping proper location info.""" |
| 36 |
|
| 37 |
|
| 38 |
def load_toml(filename: str) -> T.Dict[str, object]: |
| 39 |
if tomllib: |
| 40 |
try: |
| 41 |
with open(filename, 'rb') as f: |
| 42 |
raw = tomllib.load(f) |
| 43 |
except tomllib.TOMLDecodeError as e: |
| 44 |
if hasattr(e, 'msg'): |
| 45 |
raise CargoTomlError(e.msg, file=filename, lineno=e.lineno, colno=e.colno) from e |
| 46 |
else: |
| 47 |
raise CargoTomlError(str(e), file=filename) from e |
| 48 |
else: |
| 49 |
if toml2json is None: |
| 50 |
raise TomlImplementationMissing('Could not find an implementation of tomllib, nor toml2json') |
| 51 |
|
| 52 |
p, out, err = Popen_safe([toml2json, filename]) |
| 53 |
if p.returncode != 0: |
| 54 |
error_msg = err.strip() or 'toml2json failed to decode TOML' |
| 55 |
raise CargoTomlError(error_msg, file=filename) |
| 56 |
|
| 57 |
raw = json.loads(out) |
| 58 |
|
| 59 |
# tomllib.load() returns T.Dict[str, T.Any] but not other implementations. |
| 60 |
return T.cast('T.Dict[str, object]', raw) |