refactor(config): 设备能力/外部服务/阈值等硬编码收敛到 config.ini(P0+P1)

This commit is contained in:
ali
2026-11-20 11:11:42 +08:00
parent 0289ca9d66
commit cc46f8e3c3
15 changed files with 366 additions and 82 deletions
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""把 config.ini 里缺的新配置项补上(幂等,保留注释与原有值)。
默认值来自 `media/src/core/config.py` 的 `DEFAULT_CONFIG_CONTENT`:
以后模板里加了新 key,跑一次这个脚本就能补进已有部署,不用手抄。
用法::
python scripts/config_upgrade.py # 改 media/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 sys
import time
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT / "media" / "src"))
from core.config import CONFIG_PATH, DEFAULT_CONFIG_CONTENT # noqa: E402
def parse_template(text: str) -> dict[str, list[tuple[str, str]]]:
"""模板 → {节名: [(key, value)]}(忽略注释与空行)。"""
sections: dict[str, list[tuple[str, str]]] = {}
current = None
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
current = stripped[1:-1]
sections.setdefault(current, [])
elif current is not None and "=" in line and not stripped.startswith("#"):
key, _, value = line.partition("=")
sections[current].append((key.strip(), value.strip()))
return sections
def section_spans(lines: list[str]) -> dict[str, tuple[int, int]]:
"""每个节的 [起始行, 结束行) ;起始行是节标题本身。"""
starts = {}
for idx, line in enumerate(lines):
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
starts[stripped[1:-1]] = idx
ordered = sorted(starts.values())
spans = {}
for name, start in starts.items():
later = [pos for pos in ordered if pos > start]
spans[name] = (start, later[0] if later else len(lines))
return spans
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)
lines = target.read_text(encoding="utf-8").splitlines()
added: list[str] = []
added_keys: set[tuple[str, str]] = set()
for section, items in template.items():
spans = section_spans(lines)
if section not in spans:
lines += ["", f"[{section}]"]
spans = section_spans(lines)
start, end = spans[section]
existing = {line.split("=", 1)[0].strip()
for line in lines[start + 1:end] if "=" in line and not line.strip().startswith("#")}
# 插在本节最后一个非空行之后,避免把注释和上一节隔开
insert_at = end
while insert_at > start + 1 and not lines[insert_at - 1].strip():
insert_at -= 1
for key, value in items:
if key in existing or (section, key) in added_keys:
continue
lines.insert(insert_at, f"{key} = {value}")
insert_at += 1
added_keys.add((section, key))
added.append(f"[{section}] {key}")
if not added:
print("✅ 配置已是最新,无需补项")
return 0
print(f"将补 {len(added)} 项到 {target}:")
for item in added:
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(target.read_text(encoding="utf-8"), encoding="utf-8")
target.write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"✅ 已写入;备份 {backup.name}")
return 0
if __name__ == "__main__":
sys.exit(main())