1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 03:24:20 +00:00

Implement toml and json Scrolls

This commit is contained in:
Steffo 2020-10-28 18:00:11 +01:00
parent 6e05026f9f
commit 57fd4cd8c3
2 changed files with 37 additions and 0 deletions

View file

@ -2,6 +2,8 @@ from royalnet.typing import *
import os import os
import json import json
import re import re
import toml
import json
from .errors import * from .errors import *
@ -11,10 +13,40 @@ class Scroll:
key_validator = re.compile(r"^[A-Z.]+$") key_validator = re.compile(r"^[A-Z.]+$")
loaders = {
".json": json.load,
".toml": toml.load
}
def __init__(self, namespace: str, config: Optional[Dict[str, JSON]] = None): def __init__(self, namespace: str, config: Optional[Dict[str, JSON]] = None):
self.namespace: str = namespace self.namespace: str = namespace
self.config: Optional[Dict[str, JSON]] = config self.config: Optional[Dict[str, JSON]] = config
@classmethod
def from_toml(cls, namespace: str, file_path: os.PathLike):
with open(file_path) as file:
config = toml.load(file)
return cls(namespace, config)
@classmethod
def from_json(cls, namespace: str, file_path: os.PathLike):
with open(file_path) as file:
config = json.load(file)
return cls(namespace, config)
@classmethod
def from_file(cls, namespace: str, file_path: os.PathLike):
file, ext = os.path.splitext(file_path)
lext = ext.lower()
with open(file_path) as file:
try:
config = cls.loaders[lext](file)
except KeyError:
raise InvalidFileType(f"Invalid extension: {lext}")
return cls(namespace, config)
@classmethod @classmethod
def _validate_key(cls, item: str): def _validate_key(cls, item: str):
check = cls.key_validator.match(item) check = cls.key_validator.match(item)

View file

@ -17,9 +17,14 @@ class ParseError(ScrollException):
"""The config value could not be parsed correctly.""" """The config value could not be parsed correctly."""
class InvalidFileType(ParseError):
"""The type of the specified config file is not currently supported."""
__all__ = ( __all__ = (
"ScrollException", "ScrollException",
"NotFoundError", "NotFoundError",
"InvalidFormatError", "InvalidFormatError",
"ParseError", "ParseError",
"InvalidFileType",
) )