Skip to content

Commit 5751af5

Browse files
phlogistonjohnmergify[bot]
authored andcommitted
sambacc: add support for reading TOML formatted configs
Python 3.11 and later includes support for reading TOML files. Add support for reading TOML based configuration to sambacc. Signed-off-by: John Mulligan <[email protected]>
1 parent 34d81c9 commit 5751af5

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

sambacc/config.py

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,10 @@
1919
from __future__ import annotations
2020

2121
import binascii
22+
import enum
2223
import errno
2324
import json
25+
import sys
2426
import typing
2527

2628
_VALID_VERSIONS = ["v0"]
@@ -48,6 +50,11 @@
4850
_JSON_SCHEMA: dict[str, typing.Any] = {}
4951

5052

53+
class ConfigFormat(enum.Enum):
54+
JSON = "json"
55+
TOML = "toml"
56+
57+
5158
class ValidationUnsupported(Exception):
5259
pass
5360

@@ -56,6 +63,31 @@ class _FakeRefResolutionError(Exception):
5663
pass
5764

5865

66+
class ConfigFormatUnsupported(Exception):
67+
pass
68+
69+
70+
if sys.version_info >= (3, 11):
71+
72+
def _load_toml(source: typing.IO) -> JSONData:
73+
try:
74+
import tomllib
75+
except ImportError:
76+
raise ConfigFormatUnsupported(ConfigFormat.TOML)
77+
return tomllib.load(source)
78+
79+
else:
80+
81+
def _load_toml(source: typing.IO) -> JSONData:
82+
raise ConfigFormatUnsupported(ConfigFormat.TOML)
83+
84+
85+
def _detect_format(fname: str) -> ConfigFormat:
86+
if fname.endswith(".toml"):
87+
return ConfigFormat.TOML
88+
return ConfigFormat.JSON
89+
90+
5991
def _schema_validate(data: dict[str, typing.Any], version: str) -> None:
6092
try:
6193
import jsonschema # type: ignore[import]
@@ -119,9 +151,14 @@ def read_config_files(
119151
gconfig = GlobalConfig()
120152
readfiles = set()
121153
for fname in fnames:
154+
config_format = _detect_format(str(fname))
122155
try:
123-
with _open(fname) as fh:
124-
gconfig.load(fh, require_validation=require_validation)
156+
with _open(fname, "rb") as fh:
157+
gconfig.load(
158+
fh,
159+
require_validation=require_validation,
160+
config_format=config_format,
161+
)
125162
readfiles.add(fname)
126163
except OSError as err:
127164
if getattr(err, "errno", 0) != errno.ENOENT:
@@ -154,9 +191,15 @@ def __init__(
154191
def load(
155192
self,
156193
source: typing.IO,
194+
*,
157195
require_validation: typing.Optional[bool] = None,
196+
config_format: typing.Optional[ConfigFormat] = None,
158197
) -> None:
159-
data = json.load(source)
198+
config_format = config_format or ConfigFormat.JSON
199+
if config_format == ConfigFormat.TOML:
200+
data = _load_toml(source)
201+
else:
202+
data = json.load(source)
160203
_check_config_valid(
161204
data, _check_config_version(data), require_validation
162205
)

0 commit comments

Comments
 (0)