1
- from inspect import isfunction
1
+ from io import StringIO
2
2
from pathlib import Path
3
- from typing import Any , Callable , Dict , Optional , Tuple , TypeVar , Union
3
+ from typing import Optional , Tuple , Union
4
4
5
- from pydantic import BaseModel , Extra
5
+ from pydantic import BaseModel
6
6
from typing_extensions import Self
7
7
8
8
from easyconfig .__const__ import MISSING , MISSING_TYPE
9
9
from easyconfig .yaml import cmap_from_model , CommentedMap , write_aligned_yaml , yaml_rt
10
10
11
+ from ..errors import DefaultNotSet
11
12
from .object_config import ConfigObj
12
13
13
14
@@ -43,9 +44,9 @@ def load_config_file(self, path: Union[Path, str] = None):
43
44
44
45
# create default config file
45
46
if self ._file_defaults is not None and not self ._file_path .is_file ():
46
- c_map = cmap_from_model ( self ._file_defaults )
47
+ __yaml = self .generate_default_yaml ( )
47
48
with self ._file_path .open (mode = 'w' , encoding = 'utf-8' ) as f :
48
- write_aligned_yaml ( c_map , f , extra_indent = 1 )
49
+ f . write ( __yaml )
49
50
50
51
# Load data from file
51
52
with self ._file_path .open ('r' , encoding = 'utf-8' ) as file :
@@ -56,35 +57,12 @@ def load_config_file(self, path: Union[Path, str] = None):
56
57
# load c_map data (which is a dict)
57
58
self .load_config_dict (cfg )
58
59
60
+ def generate_default_yaml (self ) -> str :
59
61
60
- TYPE_WRAPPED = TypeVar ('TYPE_WRAPPED' , bound = BaseModel )
62
+ if self ._file_defaults is None :
63
+ raise DefaultNotSet ()
61
64
62
-
63
- def create_app_config (model : TYPE_WRAPPED ,
64
- file_values : Union [MISSING_TYPE , None , BaseModel , Dict [str , Any ],
65
- Callable [[], Union [BaseModel , Dict [str , Any ]]]] = MISSING ,
66
- validate_file_values = True ) -> TYPE_WRAPPED :
67
-
68
- # Implicit default
69
- if file_values is MISSING :
70
- file_values = model
71
-
72
- # if it's a callback we get the values
73
- if isfunction (file_values ):
74
- file_values = file_values ()
75
-
76
- # Validate default
77
- if file_values is not None :
78
- if isinstance (file_values , dict ):
79
- if validate_file_values :
80
- class NoExtraEntries (model .__class__ , extra = Extra .forbid ):
81
- pass
82
- NoExtraEntries .parse_obj (file_values )
83
-
84
- file_values = model .__class__ .parse_obj (file_values )
85
-
86
- app_cfg = AppConfig .from_model (model )
87
-
88
- assert file_values is None or isinstance (file_values , BaseModel )
89
- app_cfg ._file_defaults = file_values
90
- return app_cfg
65
+ buffer = StringIO ()
66
+ c_map = cmap_from_model (self ._file_defaults )
67
+ write_aligned_yaml (c_map , buffer , extra_indent = 1 )
68
+ return buffer .getvalue ()
0 commit comments