pboot-kernel 1.10.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kernel/config.py ADDED
@@ -0,0 +1,142 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import warnings
5
+ from collections.abc import Callable, Iterator, Mapping, MutableMapping
6
+ from pathlib import Path
7
+ from typing import Any, TypeVar, overload
8
+
9
+
10
+ class undefined:
11
+ pass
12
+
13
+
14
+ class EnvironError(Exception):
15
+ pass
16
+
17
+
18
+ class Environ(MutableMapping[str, str]):
19
+ def __init__(self, environ: MutableMapping[str, str] = os.environ):
20
+ self._environ = environ
21
+ self._has_been_read: set[str] = set()
22
+
23
+ def __getitem__(self, key: str) -> str:
24
+ self._has_been_read.add(key)
25
+ return self._environ.__getitem__(key)
26
+
27
+ def __setitem__(self, key: str, value: str) -> None:
28
+ if key in self._has_been_read:
29
+ raise EnvironError(f"Attempting to set environ['{key}'], but the value has already been read.")
30
+ self._environ.__setitem__(key, value)
31
+
32
+ def __delitem__(self, key: str) -> None:
33
+ if key in self._has_been_read:
34
+ raise EnvironError(f"Attempting to delete environ['{key}'], but the value has already been read.")
35
+ self._environ.__delitem__(key)
36
+
37
+ def __iter__(self) -> Iterator[str]:
38
+ return iter(self._environ)
39
+
40
+ def __len__(self) -> int:
41
+ return len(self._environ)
42
+
43
+
44
+ environ = Environ()
45
+
46
+ T = TypeVar("T")
47
+
48
+
49
+ class Config:
50
+ def __init__(
51
+ self,
52
+ env_file: str | Path | None = None,
53
+ environ: Mapping[str, str] = environ,
54
+ env_prefix: str = "",
55
+ encoding: str = "utf-8",
56
+ ) -> None:
57
+ self.environ = environ
58
+ self.env_prefix = env_prefix
59
+ self.file_values: dict[str, str] = {}
60
+ if env_file is not None:
61
+ if not os.path.isfile(env_file):
62
+ warnings.warn(f"Config file '{env_file}' not found.")
63
+ else:
64
+ self.file_values = self._read_file(env_file, encoding)
65
+
66
+ @overload
67
+ def __call__(self, key: str, *, default: None) -> str | None: ...
68
+
69
+ @overload
70
+ def __call__(self, key: str, cast: type[T], default: T = ...) -> T: ...
71
+
72
+ @overload
73
+ def __call__(self, key: str, cast: type[str] = ..., default: str = ...) -> str: ...
74
+
75
+ @overload
76
+ def __call__(
77
+ self,
78
+ key: str,
79
+ cast: Callable[[Any], T] = ...,
80
+ default: Any = ...,
81
+ ) -> T: ...
82
+
83
+ @overload
84
+ def __call__(self, key: str, cast: type[str] = ..., default: T = ...) -> T | str: ...
85
+
86
+ def __call__(
87
+ self,
88
+ key: str,
89
+ cast: Callable[[Any], Any] | None = None,
90
+ default: Any = undefined,
91
+ ) -> Any:
92
+ return self.get(key, cast, default)
93
+
94
+ def get(
95
+ self,
96
+ key: str,
97
+ cast: Callable[[Any], Any] | None = None,
98
+ default: Any = undefined,
99
+ ) -> Any:
100
+ key = self.env_prefix + key
101
+ if key in self.environ:
102
+ value = self.environ[key]
103
+ return self._perform_cast(key, value, cast)
104
+ if key in self.file_values:
105
+ value = self.file_values[key]
106
+ return self._perform_cast(key, value, cast)
107
+ if default is not undefined:
108
+ return self._perform_cast(key, default, cast)
109
+ raise KeyError(f"Config '{key}' is missing, and has no default.")
110
+
111
+ def _read_file(self, file_name: str | Path, encoding: str) -> dict[str, str]:
112
+ file_values: dict[str, str] = {}
113
+ with open(file_name, encoding=encoding) as input_file:
114
+ for line in input_file.readlines():
115
+ line = line.strip()
116
+ if "=" in line and not line.startswith("#"):
117
+ key, value = line.split("=", 1)
118
+ key = key.strip()
119
+ value = value.strip()
120
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
121
+ value = value[1:-1]
122
+ file_values[key] = value
123
+ return file_values
124
+
125
+ def _perform_cast(
126
+ self,
127
+ key: str,
128
+ value: Any,
129
+ cast: Callable[[Any], Any] | None = None,
130
+ ) -> Any:
131
+ if cast is None or value is None:
132
+ return value
133
+ elif cast is bool and isinstance(value, str):
134
+ mapping = {"true": True, "1": True, "false": False, "0": False}
135
+ value = value.lower()
136
+ if value not in mapping:
137
+ raise ValueError(f"Config '{key}' has value '{value}'. Not a valid bool.")
138
+ return mapping[value]
139
+ try:
140
+ return cast(value)
141
+ except (TypeError, ValueError):
142
+ raise ValueError(f"Config '{key}' has value '{value}'. Not a valid {cast.__name__}.")
kernel/convertors.py ADDED
@@ -0,0 +1,89 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import uuid
5
+ from typing import Any, ClassVar, Generic, TypeVar
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ class Convertor(Generic[T]):
11
+ regex: ClassVar[str] = ""
12
+
13
+ def convert(self, value: str) -> T:
14
+ raise NotImplementedError() # pragma: no cover
15
+
16
+ def to_string(self, value: T) -> str:
17
+ raise NotImplementedError() # pragma: no cover
18
+
19
+
20
+ class StringConvertor(Convertor[str]):
21
+ regex = "[^/]+"
22
+
23
+ def convert(self, value: str) -> str:
24
+ return value
25
+
26
+ def to_string(self, value: str) -> str:
27
+ value = str(value)
28
+ assert "/" not in value, "May not contain path separators"
29
+ assert value, "Must not be empty"
30
+ return value
31
+
32
+
33
+ class PathConvertor(Convertor[str]):
34
+ regex = ".*"
35
+
36
+ def convert(self, value: str) -> str:
37
+ return str(value)
38
+
39
+ def to_string(self, value: str) -> str:
40
+ return str(value)
41
+
42
+
43
+ class IntegerConvertor(Convertor[int]):
44
+ regex = "[0-9]+"
45
+
46
+ def convert(self, value: str) -> int:
47
+ return int(value)
48
+
49
+ def to_string(self, value: int) -> str:
50
+ value = int(value)
51
+ assert value >= 0, "Negative integers are not supported"
52
+ return str(value)
53
+
54
+
55
+ class FloatConvertor(Convertor[float]):
56
+ regex = r"[0-9]+(\.[0-9]+)?"
57
+
58
+ def convert(self, value: str) -> float:
59
+ return float(value)
60
+
61
+ def to_string(self, value: float) -> str:
62
+ value = float(value)
63
+ assert not math.isnan(value), "NaN values are not supported"
64
+ assert not math.isinf(value), "Infinite values are not supported"
65
+ assert value >= 0.0, "Negative floats are not supported"
66
+ return ("%0.20f" % value).rstrip("0").rstrip(".")
67
+
68
+
69
+ class UUIDConvertor(Convertor[uuid.UUID]):
70
+ regex = "[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}"
71
+
72
+ def convert(self, value: str) -> uuid.UUID:
73
+ return uuid.UUID(value)
74
+
75
+ def to_string(self, value: uuid.UUID) -> str:
76
+ return str(value)
77
+
78
+
79
+ CONVERTOR_TYPES: dict[str, Convertor[Any]] = {
80
+ "str": StringConvertor(),
81
+ "path": PathConvertor(),
82
+ "int": IntegerConvertor(),
83
+ "float": FloatConvertor(),
84
+ "uuid": UUIDConvertor(),
85
+ }
86
+
87
+
88
+ def register_url_convertor(key: str, convertor: Convertor[Any]) -> None:
89
+ CONVERTOR_TYPES[key] = convertor