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:
parent
6e05026f9f
commit
57fd4cd8c3
2 changed files with 37 additions and 0 deletions
|
@ -2,6 +2,8 @@ from royalnet.typing import *
|
|||
import os
|
||||
import json
|
||||
import re
|
||||
import toml
|
||||
import json
|
||||
|
||||
from .errors import *
|
||||
|
||||
|
@ -11,10 +13,40 @@ class Scroll:
|
|||
|
||||
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):
|
||||
self.namespace: str = namespace
|
||||
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
|
||||
def _validate_key(cls, item: str):
|
||||
check = cls.key_validator.match(item)
|
||||
|
|
|
@ -17,9 +17,14 @@ class ParseError(ScrollException):
|
|||
"""The config value could not be parsed correctly."""
|
||||
|
||||
|
||||
class InvalidFileType(ParseError):
|
||||
"""The type of the specified config file is not currently supported."""
|
||||
|
||||
|
||||
__all__ = (
|
||||
"ScrollException",
|
||||
"NotFoundError",
|
||||
"InvalidFormatError",
|
||||
"ParseError",
|
||||
"InvalidFileType",
|
||||
)
|
||||
|
|
Loading…
Reference in a new issue