#!/usr/bin/env python3 """把 config.ini 同步到模板:补缺失的键,并给每个键补上模板里的注释。 - 值的来源永远是 `src/core/config.py` 的 `DEFAULT_CONFIG_CONTENT`; - 已有键保留原值,缺项用模板缺省值; - 幂等:已有注释的键不会重复插入,用户自己写的注释也不会被覆盖; - 模板以后新增键或改注释,跑一次即可同步到已有部署。 用法:: python scripts/config_upgrade.py # 改 src/config.ini python scripts/config_upgrade.py --dry-run # 只报告会改什么 python scripts/config_upgrade.py --path /path/config.ini """ from __future__ import annotations import argparse import re import sys import time from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(REPO_ROOT / "src")) from core.config import CONFIG_PATH, DEFAULT_CONFIG_CONTENT # noqa: E402 SECTION_RE = re.compile(r"^\[(?P[^\]]+)\]\s*$") KEY_RE = re.compile(r"^(?P\s*)(?P[A-Za-z_][\w.-]*)\s*=") def parse_template(text: str) -> list[tuple[str, list[tuple[list[str], str, str]]]]: """→ [(节名, [(注释行, key, value)])],保持模板顺序。""" sections: list[tuple[str, list]] = [] pending: list[str] = [] current = None for line in text.splitlines(): stripped = line.strip() match = SECTION_RE.match(stripped) if match: current = match.group("name") sections.append((current, [])) pending = [] continue if current is None: continue if stripped.startswith("#"): pending.append(line.rstrip()) elif stripped and "=" in line: key, _, value = line.partition("=") sections[-1][1].append((pending, key.strip(), value.strip())) pending = [] else: pending = [] return sections def split_live(lines: list[str]) -> tuple[list[str], list[tuple[str, list[str]]]]: """拆成 (节前内容, [(节名, 该节的行)])。""" preamble: list[str] = [] sections: list[tuple[str, list[str]]] = [] for line in lines: match = SECTION_RE.match(line.strip()) if match: sections.append((match.group("name"), [])) elif sections: sections[-1][1].append(line) else: preamble.append(line) return preamble, sections def main() -> int: parser = argparse.ArgumentParser(description="补齐 config.ini 的键与注释") parser.add_argument("--path", default=str(CONFIG_PATH), help="要升级的 config.ini") parser.add_argument("--dry-run", action="store_true", help="只报告,不写文件") args = parser.parse_args() target = Path(args.path) if not target.exists(): print(f"❌ 找不到配置文件: {target}") return 1 template = parse_template(DEFAULT_CONFIG_CONTENT) template_map = dict(template) original = target.read_text(encoding="utf-8").splitlines() preamble, sections = split_live(original) out: list[str] = [line.rstrip() for line in preamble if line.strip()] added: list[str] = [] documented: list[str] = [] custom: list[str] = [] template_keys = {key for items in template_map.values() for _, key, _ in items} def flush_section(name: str, content: list[str]) -> None: if out: out.append("") out.append(f"[{name}]") items = template_map.get(name, []) comments_by_key = {key: comments for comments, key, _ in items} present = set() for raw in content: if not raw.strip(): continue match = KEY_RE.match(raw) key = match.group("key") if match else None if key and key in comments_by_key: present.add(key) comments = comments_by_key[key] if comments and not (out and out[-1].strip().startswith("#")): out.extend(comments) documented.append(f"[{name}] {key}") elif key and key not in template_keys: if not (out and out[-1].strip().startswith("#")): custom.append(f"[{name}] {key}") out.append(raw.rstrip()) for comments, key, value in items: if key in present: continue out.extend(comments) out.append(f"{key} = {value}") added.append(f"[{name}] {key}") live_names = set() for name, content in sections: live_names.add(name) flush_section(name, content) for name, _items in template: if name in live_names: continue flush_section(name, []) new_text = "\n".join(out) + "\n" old_text = "\n".join(original) + "\n" if new_text == old_text: print("✅ 配置已是最新(键与注释齐全)") return 0 if added: print(f"将补 {len(added)} 个键:") for item in added: print(" +", item) if documented: print(f"将补 {len(documented)} 处注释:") for item in documented: print(" #", item) if custom: print(f"(另有 {len(custom)} 个模板里没有的自定义键,保持原样):") for item in custom: print(" ?", item) if args.dry_run: print("(演练,未写入)") return 0 backup = target.with_name(f"{target.name}.bak-{time.strftime('%Y%m%d-%H%M%S')}") backup.write_text(old_text, encoding="utf-8") target.write_text(new_text, encoding="utf-8") print(f"✅ 已写入;备份 {backup.name}") return 0 if __name__ == "__main__": sys.exit(main())