From 87cf07bf82a7d5394cc3a887f48003519ef5e37e Mon Sep 17 00:00:00 2001 From: minecraft1024a Date: Tue, 23 Sep 2025 16:13:00 +0800 Subject: [PATCH] =?UTF-8?q?feat(config):=20=E8=87=AA=E5=8A=A8=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E6=9B=B4=E6=96=B0=E4=B8=AD=E5=B7=B2=E5=BA=9F=E5=BC=83?= =?UTF-8?q?=E7=9A=84=E9=85=8D=E7=BD=AE=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在版本更新过程中,新增一个步骤来对比用户配置与最新的模板文件。 此变更会自动删除用户配置文件中所有在模板中不再存在的键,以保持配置的整洁性,并防止因过时的配置项导致潜在的兼容性问题或混淆。 --- src/config/config.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/config/config.py b/src/config/config.py index 7f89e0009..1d7857a26 100644 --- a/src/config/config.py +++ b/src/config/config.py @@ -170,6 +170,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字典中 @@ -348,6 +360,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))