2024-08-24 20:54:36 +08:00
|
|
|
import os
|
|
|
|
|
import shutil
|
|
|
|
|
import yaml
|
|
|
|
|
|
|
|
|
|
from .. import model as file_model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class YAMLConfigFile(file_model.ConfigFile):
|
|
|
|
|
"""YAML配置文件"""
|
|
|
|
|
|
|
|
|
|
def __init__(
|
2025-04-29 17:24:07 +08:00
|
|
|
self,
|
|
|
|
|
config_file_name: str,
|
|
|
|
|
template_file_name: str = None,
|
|
|
|
|
template_data: dict = None,
|
2024-08-24 20:54:36 +08:00
|
|
|
) -> None:
|
|
|
|
|
self.config_file_name = config_file_name
|
|
|
|
|
self.template_file_name = template_file_name
|
|
|
|
|
self.template_data = template_data
|
|
|
|
|
|
|
|
|
|
def exists(self) -> bool:
|
|
|
|
|
return os.path.exists(self.config_file_name)
|
|
|
|
|
|
|
|
|
|
async def create(self):
|
|
|
|
|
if self.template_file_name is not None:
|
|
|
|
|
shutil.copyfile(self.template_file_name, self.config_file_name)
|
|
|
|
|
elif self.template_data is not None:
|
2025-04-29 17:24:07 +08:00
|
|
|
with open(self.config_file_name, 'w', encoding='utf-8') as f:
|
2024-08-24 20:54:36 +08:00
|
|
|
yaml.dump(self.template_data, f, indent=4, allow_unicode=True)
|
|
|
|
|
else:
|
2025-04-29 17:24:07 +08:00
|
|
|
raise ValueError('template_file_name or template_data must be provided')
|
2024-08-24 20:54:36 +08:00
|
|
|
|
2025-04-29 17:24:07 +08:00
|
|
|
async def load(self, completion: bool = True) -> dict:
|
2024-08-24 20:54:36 +08:00
|
|
|
if not self.exists():
|
|
|
|
|
await self.create()
|
|
|
|
|
|
|
|
|
|
if self.template_file_name is not None:
|
2025-04-29 17:24:07 +08:00
|
|
|
with open(self.template_file_name, 'r', encoding='utf-8') as f:
|
2024-08-24 20:54:36 +08:00
|
|
|
self.template_data = yaml.load(f, Loader=yaml.FullLoader)
|
|
|
|
|
|
2025-04-29 17:24:07 +08:00
|
|
|
with open(self.config_file_name, 'r', encoding='utf-8') as f:
|
2024-08-24 20:54:36 +08:00
|
|
|
try:
|
|
|
|
|
cfg = yaml.load(f, Loader=yaml.FullLoader)
|
|
|
|
|
except yaml.YAMLError as e:
|
2025-04-29 17:24:07 +08:00
|
|
|
raise Exception(f'配置文件 {self.config_file_name} 语法错误: {e}')
|
2024-08-24 20:54:36 +08:00
|
|
|
|
|
|
|
|
if completion:
|
|
|
|
|
for key in self.template_data:
|
|
|
|
|
if key not in cfg:
|
|
|
|
|
cfg[key] = self.template_data[key]
|
|
|
|
|
|
|
|
|
|
return cfg
|
|
|
|
|
|
|
|
|
|
async def save(self, cfg: dict):
|
2025-04-29 17:24:07 +08:00
|
|
|
with open(self.config_file_name, 'w', encoding='utf-8') as f:
|
2024-08-24 20:54:36 +08:00
|
|
|
yaml.dump(cfg, f, indent=4, allow_unicode=True)
|
|
|
|
|
|
|
|
|
|
def save_sync(self, cfg: dict):
|
2025-04-29 17:24:07 +08:00
|
|
|
with open(self.config_file_name, 'w', encoding='utf-8') as f:
|
|
|
|
|
yaml.dump(cfg, f, indent=4, allow_unicode=True)
|