fix, refactor: changed file buffer mode and changed conditional sequences for shorter algorithm

This commit is contained in:
2026-01-24 14:46:08 -05:00
parent f37c2d5998
commit 6af0d4b48c

View File

@@ -25,22 +25,26 @@ class Parser:
self.__file = filepath self.__file = filepath
filepath = str(filepath) filepath = str(filepath)
else: else:
self.__is_path = False if isinstance(filepath, str) and Path(filepath).exists():
if Path(filepath).exists():
self.__file = Path(filepath) self.__file = Path(filepath)
self.__is_path = True
else: else:
self.__content = filepath self.__is_path = False
if isinstance(filepath, str):
self.__content = filepath
if self.__is_yaml(filepath) or method == "yaml": if self.__is_yaml(filepath) or method == "yaml":
self.__method = "yaml" self.__method = "yaml"
if self.__is_path: if self.__is_path:
filepath = open(str(filepath), "r") filepath = open(str(filepath), "r+")
if len(kwargs) > 0: if len(kwargs) > 0:
self.__data = yams.load(filepath, Loader=yams.Loader, **kwargs) self.__data = yams.load_all(filepath, Loader=yams.Loader, **kwargs)
else: else:
self.__data = yams.load(filepath, Loader=yams.Loader) self.__data = yams.load_all(filepath, Loader=yams.Loader)
filepath.close()
elif self.__is_config(filepath) or method == "config": elif self.__is_config(filepath) or method == "config":
self.__method = "config" self.__method = "config"
self.__data = cfg() self.__data = cfg()
@@ -60,15 +64,15 @@ class Parser:
return self.__data return self.__data
def dump(self, obj = None, method: Literal["yaml", "config", "generic"] | None = "generic", **kwargs): def dump(self, obj = None, method: Literal["yaml", "config", "generic"] | None = "generic", **kwargs):
if self.__method == "yaml" or method == "yaml": if isinstance(obj, yams.YAMLObject) or self.__method == "yaml" or method == "yaml":
if obj is None: if obj is None:
obj = self.__data obj = self.__data
if len(kwargs) > 0: if len(kwargs) > 0:
self.__content = yams.dump(obj, Dumper=yams.Dumper, **kwargs) self.__content = "---\n" + yams.dump(obj, Dumper=yams.Dumper, **kwargs)
else: else:
self.__content = yams.dump(obj, Dumper=yams.Dumper) self.__content = "---\n" + yams.dump(obj, Dumper=yams.Dumper)
elif self.__method == "config" or method == "config": elif isinstance(obj, ConfigParser) or self.__method == "config" or method == "config":
if obj is None: if obj is None:
if self.__is_path: if self.__is_path:
return self.__file.read_text() return self.__file.read_text()
@@ -77,11 +81,8 @@ class Parser:
return self.__content return self.__content
else: else:
return self.__file.read_text() return self.__file.read_text()
else:
if isinstance(obj, ConfigParser): raise NotImplementedError
return obj
else:
raise TypeError
else: else:
raise TypeError raise TypeError