eyconf 0.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.
eyconf/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ from .config import EYConf
2
+ from .generate_yaml import dataclass_to_yaml
3
+
4
+ __all__ = [
5
+ "dataclass_to_yaml",
6
+ "EYConf",
7
+ "validate",
8
+ ]
eyconf/config.py ADDED
@@ -0,0 +1,139 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ from dataclasses import asdict, is_dataclass
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Generic, TypeVar, cast
8
+
9
+ import yaml
10
+
11
+ from .generate_yaml import dataclass_to_yaml
12
+ from .validate import to_json_schema, validate
13
+
14
+ if TYPE_CHECKING:
15
+ from _typeshed import DataclassInstance
16
+
17
+ # Needs the string escaping to work at runtime as _typeshed is not a real module
18
+ D = TypeVar("D", bound="DataclassInstance")
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ __all__ = [
23
+ "EYConf",
24
+ ]
25
+
26
+
27
+ class EYConf(Generic[D]):
28
+ """Configuration class.
29
+
30
+ This class is used to generate a default configuration file from a schema
31
+ represented by a dataclass.
32
+
33
+ It allows to generate, validate and load a configuration file.
34
+ """
35
+
36
+ path: Path
37
+ _schema: type[D]
38
+ _data: D
39
+ _json_schema: dict
40
+
41
+ def __init__(
42
+ self,
43
+ schema: type[D],
44
+ path: str | Path,
45
+ ):
46
+
47
+ if isinstance(path, str):
48
+ path = Path(path)
49
+ self.path = path
50
+
51
+ # At the moment we only support dataclass classes
52
+ if not is_dataclass(schema) or not isinstance(schema, type):
53
+ raise ValueError(
54
+ "Schema must be a dataclass class. Instances are not supported yet."
55
+ )
56
+ self._schema = schema
57
+
58
+ # Generate default configuration if it does not exist
59
+ if not self.path.exists():
60
+ self.write_default()
61
+
62
+ # Create schema
63
+ self._json_schema = to_json_schema(self._schema)
64
+
65
+ # Load the configuration file
66
+ self._data = self._load()
67
+ print(self._data)
68
+
69
+ def write_default(self):
70
+ """Generate default yaml configuration."""
71
+ if self.path.exists():
72
+ log.warning(f"Configuration file {self.path} already exists. Overwriting!")
73
+
74
+ yaml_str = dataclass_to_yaml(self._schema)
75
+ os.makedirs(self.path.parent, exist_ok=True)
76
+ with open(self.path, "w") as f:
77
+ f.write(yaml_str)
78
+ f.write("\n") # Add a newline at the end of the file
79
+ log.info(f"Configuration file created at '{self.path.absolute()}'")
80
+
81
+ def _load(self) -> D:
82
+ """Load the configuration file and validate it against the schema."""
83
+ log.info(f"Loading config file: {self.path.absolute()}")
84
+
85
+ if not self.path.exists():
86
+ raise FileNotFoundError(
87
+ f"Configuration file '{self.path.absolute()}' not found. Please generate with `write_default()`."
88
+ )
89
+
90
+ # Load the config file
91
+ with open(self.path, "r") as file:
92
+ data = yaml.safe_load(file)
93
+
94
+ # Will raise ConfigurationError if the data does not comply with the schema
95
+ validate(data, self._json_schema)
96
+
97
+ return cast(D, dataclass_from_dict(self._schema, data))
98
+
99
+ def refresh(self):
100
+ """Reload the configuration file."""
101
+ self._data = self._load()
102
+
103
+ def __getattr__(self, key: str):
104
+ """Get an item from the configuration."""
105
+ return getattr(self._data, key)
106
+
107
+ def __str__(self):
108
+ """Return a custom formatted string representation of the configuration data."""
109
+ data_dict = asdict(self._data)
110
+ class_name = type(self).__name__
111
+ memory_address = hex(id(self))
112
+ prefix = f"<{class_name} object at {memory_address} loaded from {self.path.absolute()}>:\n"
113
+ s = "\n".join(
114
+ " " + line for line in self._pretty_format(data_dict).splitlines()
115
+ )
116
+ return f"{prefix}{s}"
117
+
118
+ def _pretty_format(self, data, indent=0):
119
+ """Format the dict with pretty indentation."""
120
+ result = []
121
+ for key, value in data.items():
122
+ if isinstance(value, dict):
123
+ result.append(" " * indent + f"{key}:")
124
+ result.append(self._pretty_format(value, indent + 4))
125
+ else:
126
+ result.append(" " * indent + f"{key}: {value}")
127
+ return "\n".join(result)
128
+
129
+ __repr__ = __str__ # Use the same formatted string for repr, if desired
130
+
131
+
132
+ def dataclass_from_dict(klass, dikt):
133
+ try:
134
+ fieldtypes = klass.__annotations__
135
+ return klass(**{f: dataclass_from_dict(fieldtypes[f], dikt[f]) for f in dikt})
136
+ except AttributeError:
137
+ if isinstance(dikt, (tuple, list)):
138
+ return [dataclass_from_dict(klass.__args__[0], f) for f in dikt]
139
+ return dikt
@@ -0,0 +1,363 @@
1
+ """Generate a default yaml file from a dataclass schema.
2
+
3
+ This is relatively dirty and not all edge cases might be covered. Works for most
4
+ simple cases though.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import re
11
+ from abc import ABC, abstractmethod
12
+ from dataclasses import _MISSING_TYPE, Field, fields, is_dataclass
13
+ from types import NoneType, UnionType
14
+ from typing import (
15
+ TYPE_CHECKING,
16
+ Annotated,
17
+ Any,
18
+ Union,
19
+ get_args,
20
+ get_origin,
21
+ )
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+ if TYPE_CHECKING:
26
+ from _typeshed import DataclassInstance
27
+
28
+
29
+ class Line(ABC):
30
+ """A line of yaml content."""
31
+
32
+ is_comment: bool = False
33
+ indent: int = 0
34
+
35
+ def __init__(self, is_comment: bool = False, indent: int = 0):
36
+ self.is_comment = is_comment
37
+ self.indent = indent
38
+
39
+ @property
40
+ @abstractmethod
41
+ def _content(self) -> str:
42
+ """Return the formatted line. Without indentation or comment."""
43
+ pass
44
+
45
+ @property
46
+ def content(self) -> str:
47
+ """Return the formatted line."""
48
+ return f"{' ' * self.indent}{'# ' if self.is_comment else ''}{self._content}"
49
+
50
+
51
+ class EmptyLine(Line):
52
+ """An empty line of yaml content."""
53
+
54
+ def __init__(self):
55
+ super().__init__(is_comment=False, indent=0)
56
+
57
+ @property
58
+ def _content(self) -> str:
59
+ """Return the formatted line. Without indentation or comment."""
60
+ return ""
61
+
62
+ @property
63
+ def content(self) -> str:
64
+ """Return the formatted line."""
65
+ return ""
66
+
67
+
68
+ class CommentLine(Line):
69
+ """A comment line of yaml content."""
70
+
71
+ def __init__(self, comment: str, indent: int = 0):
72
+ super().__init__(is_comment=True, indent=indent)
73
+ self.comment = comment
74
+
75
+ @property
76
+ def _content(self) -> str:
77
+ """Return the formatted line. Without indentation or comment."""
78
+ return self.comment.strip()
79
+
80
+
81
+ class MapLine(Line):
82
+ """A map line of yaml content."""
83
+
84
+ name: str
85
+ default_value: Primitives
86
+
87
+ def __init__(self, name: str, default_value: Primitives, **kwargs):
88
+ super().__init__(**kwargs)
89
+ self.name = name
90
+ self.default_value = default_value
91
+
92
+ @property
93
+ def _content(self) -> str:
94
+ """Return the formatted line. Without indentation or comment."""
95
+ value = self.default_value
96
+ if value is None:
97
+ value = "null"
98
+ elif isinstance(value, bool):
99
+ value = str(value).lower()
100
+ return f"{self.name}: {value}"
101
+
102
+
103
+ class SequenceLine(Line):
104
+ """A sequence line of yaml content."""
105
+
106
+ default_value: Primitives
107
+
108
+ def __init__(self, default_value: Primitives, **kwargs):
109
+ super().__init__(**kwargs)
110
+ self.default_value = default_value
111
+
112
+ @property
113
+ def _content(self) -> str:
114
+ """Return the formatted line. Without indentation or comment."""
115
+ return f"- {self.default_value}"
116
+
117
+
118
+ class SectionLine(Line):
119
+ """A section line of yaml content."""
120
+
121
+ name: str
122
+
123
+ def __init__(self, name: str, **kwargs):
124
+ super().__init__(**kwargs)
125
+ self.name = name
126
+
127
+ @property
128
+ def _content(self) -> str:
129
+ """Return the formatted line. Without indentation or comment."""
130
+ return f"{self.name}:"
131
+
132
+
133
+ def dataclass_to_yaml(schema: type[DataclassInstance] | DataclassInstance) -> str:
134
+ """Generate a yaml string from a dataclass schema."""
135
+ lines = _dataclass_to_lines(schema)
136
+ return "\n".join([line.content for line in lines])
137
+
138
+
139
+ def _dataclass_to_lines(
140
+ schema: type[DataclassInstance] | DataclassInstance,
141
+ indent: int = 0,
142
+ ) -> list[Line]:
143
+ """Generate yaml from a dataclass schema."""
144
+ lines: list[Line] = []
145
+
146
+ # Parse docstring
147
+ if schema.__doc__ is not None and __is_custom_docstring(schema):
148
+ lines += __split_docstring(schema.__doc__, indent=indent)
149
+ lines.append(EmptyLine())
150
+
151
+ # Handle dataclass instances
152
+ if __is_dataclass_instance(schema):
153
+ dict = schema.__dict__
154
+ for key, value in dict.items():
155
+ lines.append(MapLine(name=key, default_value=value, indent=indent))
156
+ return lines
157
+
158
+ # Handle dataclass types
159
+ # by parsing type hints
160
+ all_fields = fields(schema)
161
+ for field in all_fields:
162
+ lines += __field_to_lines(field, indent=indent)
163
+
164
+ return lines
165
+
166
+
167
+ def __field_to_lines(field: Field[Any], indent=0) -> list[Line]:
168
+ """Parse a primitive field and return a list of lines.
169
+
170
+ Parameters
171
+ ----------
172
+ field : Field
173
+ The field to parse.
174
+
175
+ Returns
176
+ -------
177
+ list[str]
178
+ A list of lines, each no longer than `l` characters.
179
+ """
180
+ lines = []
181
+ origin = get_origin(field.type)
182
+ args = get_args(field.type)
183
+
184
+ if is_dataclass(field.type):
185
+ # Add section
186
+ lines.append(SectionLine(field.name, indent=indent))
187
+ lines += _dataclass_to_lines(field.type, indent=indent + 1)
188
+ lines.append(EmptyLine())
189
+ return lines
190
+
191
+ # Extract docstring from annotated
192
+ if origin is Annotated:
193
+ annotations = [arg for arg in args if isinstance(arg, str)]
194
+ args = [arg for arg in args if not isinstance(arg, str)]
195
+ for annotation in annotations:
196
+ lines += __split_docstring(annotation, indent=indent)
197
+
198
+ # Check if field is optional
199
+ is_optional = False
200
+ if origin is UnionType or origin is Union:
201
+ is_optional = type(None) in args or NoneType in args
202
+ args = [arg for arg in args if arg is not type(None) and arg is not NoneType]
203
+
204
+ # Parse default
205
+ default_missing = True
206
+ default_value = None
207
+ if isinstance(field.default, _MISSING_TYPE):
208
+ if isinstance(field.default_factory, _MISSING_TYPE):
209
+ default_missing = True
210
+ else:
211
+ default_value = field.default_factory()
212
+ default_missing = False
213
+ else:
214
+ default_value = field.default
215
+ default_missing = False
216
+
217
+ # No default value only allowed if the field is optional
218
+ if default_missing and not is_optional:
219
+ raise ValueError(
220
+ f"Field '{field.name}' has no default value! You may set one using direct assignment or a default factory."
221
+ )
222
+
223
+ # Lists/Sequences
224
+ if isinstance(default_value, list):
225
+ if len(default_value) == 0:
226
+ default_value = None
227
+ else:
228
+ """
229
+ Stuff:
230
+ - 1
231
+ - 2
232
+ - 3
233
+ """
234
+ lines.append(SectionLine(field.name, indent=indent))
235
+ for value in default_value:
236
+ if __is_primitive_instance(value):
237
+ lines.append(SequenceLine(default_value=value, indent=indent + 1))
238
+ continue
239
+
240
+ if __is_dataclass_instance(value):
241
+ lines.append(SequenceLine("", indent=indent + 1))
242
+ lines += _dataclass_to_lines(value, indent=indent + 2)
243
+ continue
244
+
245
+ raise NotImplementedError(
246
+ f"Field type {field.type} {args} {origin} is not supported."
247
+ )
248
+
249
+ return lines
250
+
251
+ # Primitives as mapping
252
+ if (
253
+ all([__is_primitive_type(arg) for arg in args])
254
+ or __is_primitive_type(field.type)
255
+ or is_optional
256
+ ):
257
+ lines.append(
258
+ MapLine(name=field.name, default_value=default_value, indent=indent)
259
+ )
260
+ return lines
261
+
262
+ raise NotImplementedError(
263
+ f"Field type {field.type} {args} {origin} is not supported."
264
+ )
265
+
266
+
267
+ def __split_docstring(docstring: str, l=80, indent=0) -> list[Line]:
268
+ """Parse a docstring and return a list of lines.
269
+
270
+ Tries to split full words if possible.
271
+
272
+ Parameters
273
+ ----------
274
+ docstring : str
275
+ The docstring to parse.
276
+
277
+ l : int
278
+ The line length.
279
+
280
+ Returns
281
+ -------
282
+ list[str]
283
+ A list of lines, each no longer than `l` characters.
284
+ """
285
+ lines = []
286
+ for line in docstring.split("\n"):
287
+ while len(line) > l:
288
+ split_at = line.rfind(" ", 0, l)
289
+ if split_at == -1:
290
+ # If no space is found, split at the maximum length
291
+ split_at = l
292
+ lines.append(line[:split_at])
293
+ line = line[split_at:].lstrip()
294
+ lines.append(line)
295
+ return [CommentLine(line.strip(), indent=indent) for line in lines if line.strip()]
296
+
297
+
298
+ def __is_custom_docstring(dataclass_obj):
299
+ # Create a regex pattern to match the default docstring format
300
+ default_docstring_pattern = r"^[^\(]+\([^\)]*\)(\w*|.*)$"
301
+
302
+ # Check if the docstring matches the default pattern
303
+ return re.match(default_docstring_pattern, dataclass_obj.__doc__) is None
304
+
305
+
306
+ Primitives = Union[int, float, str, bool, type(None), NoneType]
307
+
308
+
309
+ def __is_primitive_type(t: Any) -> bool:
310
+ """Check if the field type is supported.
311
+
312
+ Parameters
313
+ ----------
314
+ field : Field
315
+ The field to check.
316
+
317
+ Returns
318
+ -------
319
+ bool
320
+ True if the field type is supported, False otherwise.
321
+ """
322
+ if t in [int, float, str, bool, type(None), NoneType]:
323
+ return True
324
+ return False
325
+
326
+
327
+ def __is_primitive_instance(t: Any) -> bool:
328
+ """Check if the field type is a primitive instance.
329
+
330
+ Parameters
331
+ ----------
332
+ field : Field
333
+ The field to check.
334
+
335
+ Returns
336
+ -------
337
+ bool
338
+ True if the field type is a primitive instance, False otherwise.
339
+ """
340
+ if isinstance(t, (int, float, str, bool, type(None), NoneType)):
341
+ return True
342
+ return False
343
+
344
+
345
+ def __is_dataclass_instance(t: Any) -> bool:
346
+ """Check if the field type is a dataclass instance.
347
+
348
+ Parameters
349
+ ----------
350
+ field : Field
351
+ The field to check.
352
+
353
+ Returns
354
+ -------
355
+ bool
356
+ True if the field type is a dataclass instance, False otherwise.
357
+ """
358
+ return is_dataclass(t) and not isinstance(t, type)
359
+
360
+
361
+ __all__ = [
362
+ "dataclass_to_yaml",
363
+ ]
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import cast
5
+
6
+ log = logging.getLogger(__name__)
7
+
8
+
9
+ from jsonschema import Draft202012Validator, ValidationError
10
+
11
+ from ._to_json import to_json_schema
12
+
13
+ __all__ = [
14
+ "to_json_schema",
15
+ "validate",
16
+ "ConfigurationError",
17
+ "MultiConfigurationError",
18
+ ]
19
+
20
+
21
+ def validate(data: dict, schema: dict) -> None:
22
+ """Validate the provided data against the given JSON schema.
23
+
24
+ This function uses the Draft202012Validator to check if the data
25
+ conforms to the specified schema. If there are any validation errors,
26
+ it raises a ConfigurationError containing the details of the errors.
27
+
28
+ Parameters
29
+ ----------
30
+ - data (dict): The data to be validated.
31
+ - schema (dict): The JSON schema to validate against.
32
+
33
+ Raises
34
+ ------
35
+ - ConfigurationError: If the data does not comply with the schema,
36
+ this error is raised with details of the violations.
37
+ """
38
+ schema = allow_none_in_schema(schema)
39
+ validator = Draft202012Validator(schema)
40
+
41
+ errors = list(validator.iter_errors(data))
42
+ if errors:
43
+ import json
44
+
45
+ log.error("Validation errors in configuration data!")
46
+ log.debug(f"Data: {data}")
47
+ log.debug(f"Schema: {json.dumps(schema, indent=2)}")
48
+ raise ConfigurationError.from_ValidationErrors(errors)
49
+
50
+
51
+ def allow_none_in_schema(schema: dict | list) -> dict: # -> dict[Any, Any] | list[Any]:
52
+ """Recursively modifies a JSON schema to allow `null` values for all fields."""
53
+ if isinstance(schema, dict):
54
+ # If current schema block has "type"
55
+ if "type" in schema:
56
+ # If the type is a list of types, add 'null' if it's not already present
57
+ if isinstance(schema["type"], list):
58
+ if "null" not in schema["type"]:
59
+ schema["type"].append("null")
60
+ else:
61
+ # Else, make it a list with the current type and 'null'
62
+ schema["type"] = [schema["type"], "null"]
63
+
64
+ # Recursively process properties in objects
65
+ for key, value in schema.items():
66
+ if isinstance(value, (dict, list)):
67
+ allow_none_in_schema(value)
68
+
69
+ elif isinstance(schema, list):
70
+ for item in schema:
71
+ allow_none_in_schema(item)
72
+
73
+ return cast(dict, schema)
74
+
75
+
76
+ class ConfigurationError(Exception):
77
+ """Exception raised for configuration validation errors."""
78
+
79
+ def __init__(self, message="Configuration error", section=None):
80
+ self.message = message
81
+ self.section = section
82
+ super().__init__(self.message)
83
+
84
+ def __str__(self):
85
+ """Return the error message."""
86
+ return (
87
+ f"{self.message} in section '{self.section}'"
88
+ if self.section
89
+ else self.message
90
+ )
91
+
92
+ @classmethod
93
+ def from_ValidationErrors(cls, error: ValidationError | list[ValidationError]):
94
+ """Create a ConfigurationError from a ValidationError or a list of ValidationErrors."""
95
+ if isinstance(error, list):
96
+ errors = []
97
+ for e in error:
98
+ path = [str(p) for p in e.path]
99
+ errors.append(cls(e.message, ".".join(path)))
100
+ return MultiConfigurationError(errors)
101
+ else:
102
+ return cls(error.message, str(error.path))
103
+
104
+
105
+ class MultiConfigurationError(Exception):
106
+ """Exception raised for multiple configuration validation errors."""
107
+
108
+ def __init__(self, errors: list[ConfigurationError]):
109
+ self.errors = errors
110
+ super().__init__("Multiple configuration errors")
111
+
112
+ def __str__(self):
113
+ """Return the error message."""
114
+ return "\n".join([str(e) for e in self.errors])