feat(config): 自动移除更新中已废弃的配置项

在版本更新过程中,新增一个步骤来对比用户配置与最新的模板文件。

此变更会自动删除用户配置文件中所有在模板中不再存在的键,以保持配置的整洁性,并防止因过时的配置项导致潜在的兼容性问题或混淆。
This commit is contained in:
minecraft1024a
2025-09-23 16:13:00 +08:00
parent 8bafd15800
commit a6b6acc1a6

View File

@@ -164,6 +164,18 @@ def _version_tuple(v):
return tuple(int(x) if x.isdigit() else 0 for x in str(v).replace("v", "").split("-")[0].split("."))
def _remove_obsolete_keys(target: TOMLDocument | dict | Table, reference: TOMLDocument | dict | Table):
"""
递归地从目标字典中移除所有不存在于参考字典中的键。
"""
# 使用 list() 创建键的副本,以便在迭代期间安全地修改字典
for key in list(target.keys()):
if key not in reference:
del target[key]
elif isinstance(target.get(key), (dict, Table)) and isinstance(reference.get(key), (dict, Table)):
_remove_obsolete_keys(target[key], reference[key])
def _update_dict(target: TOMLDocument | dict | Table, source: TOMLDocument | dict):
"""
将source字典的值更新到target字典中
@@ -334,6 +346,13 @@ def _update_config_generic(config_name: str, template_name: str):
logger.info(f"开始合并{config_name}新旧配置...")
_update_dict(new_config, old_config)
# 移除在新模板中已不存在的旧配置项
logger.info(f"开始移除{config_name}中已废弃的配置项...")
with open(template_path, "r", encoding="utf-8") as f:
template_doc = tomlkit.load(f)
_remove_obsolete_keys(new_config, template_doc)
logger.info(f"已移除{config_name}中已废弃的配置项")
# 保存更新后的配置(保留注释和格式)
with open(new_config_path, "w", encoding="utf-8") as f:
f.write(tomlkit.dumps(new_config))