docs(config): 配置模板每行加注释,config_upgrade 同步注释到已有配置
模板 85 个键全部带注释;新增 [Media] extras_dirs;config_upgrade 现在会把缺失的注释补进已有 config.ini(不改原值、不覆盖用户注释、幂等)。
This commit is contained in:
+101
-66
@@ -1,18 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把 config.ini 里缺的新配置项补上(幂等,保留注释与原有值)。
|
||||
"""把 config.ini 同步到模板:补缺失的键,并给每个键补上模板里的注释。
|
||||
|
||||
默认值来自 `media/src/core/config.py` 的 `DEFAULT_CONFIG_CONTENT`:
|
||||
以后模板里加了新 key,跑一次这个脚本就能补进已有部署,不用手抄。
|
||||
- 值的来源永远是 `media/src/core/config.py` 的 `DEFAULT_CONFIG_CONTENT`;
|
||||
- 已有键保留原值,缺项用模板缺省值;
|
||||
- 幂等:已有注释的键不会重复插入,用户自己写的注释也不会被覆盖;
|
||||
- 模板以后新增键或改注释,跑一次即可同步到已有部署。
|
||||
|
||||
用法::
|
||||
|
||||
python scripts/config_upgrade.py # 改 media/src/config.ini
|
||||
python scripts/config_upgrade.py --dry-run # 只报告会补哪些项
|
||||
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
|
||||
@@ -22,50 +25,53 @@ sys.path.insert(0, str(REPO_ROOT / "media" / "src"))
|
||||
|
||||
from core.config import CONFIG_PATH, DEFAULT_CONFIG_CONTENT # noqa: E402
|
||||
|
||||
SECTION_RE = re.compile(r"^\[(?P<name>[^\]]+)\]\s*$")
|
||||
KEY_RE = re.compile(r"^(?P<indent>\s*)(?P<key>[A-Za-z_][\w.-]*)\s*=")
|
||||
|
||||
def parse_template(text: str) -> dict[str, list[tuple[str, str]]]:
|
||||
"""模板 → {节名: [(key, value)]}(忽略注释与空行)。"""
|
||||
sections: dict[str, list[tuple[str, str]]] = {}
|
||||
|
||||
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()
|
||||
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("#"):
|
||||
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[current].append((key.strip(), value.strip()))
|
||||
sections[-1][1].append((pending, key.strip(), value.strip()))
|
||||
pending = []
|
||||
else:
|
||||
pending = []
|
||||
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 normalize(lines: list[str]) -> list[str]:
|
||||
"""节标题前统一留一个空行(补项后不会和上一节黏在一起)。"""
|
||||
formatted: list[str] = []
|
||||
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:
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("[") and stripped.endswith("]") and formatted and formatted[-1].strip():
|
||||
formatted.append("")
|
||||
formatted.append(line)
|
||||
return formatted
|
||||
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 = 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()
|
||||
@@ -76,50 +82,79 @@ def main() -> int:
|
||||
return 1
|
||||
|
||||
template = parse_template(DEFAULT_CONFIG_CONTENT)
|
||||
original_lines = target.read_text(encoding="utf-8").splitlines()
|
||||
lines = list(original_lines)
|
||||
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] = []
|
||||
added_keys: set[tuple[str, str]] = set()
|
||||
documented: list[str] = []
|
||||
custom: list[str] = []
|
||||
template_keys = {key for items in template_map.values() for _, key, _ in items}
|
||||
|
||||
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:
|
||||
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
|
||||
lines.insert(insert_at, f"{key} = {value}")
|
||||
insert_at += 1
|
||||
added_keys.add((section, key))
|
||||
added.append(f"[{section}] {key}")
|
||||
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}")
|
||||
|
||||
lines = normalize(lines)
|
||||
formatting_changed = lines != original_lines
|
||||
if not added and not formatting_changed:
|
||||
print("✅ 配置已是最新,无需补项")
|
||||
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)} 项到 {target}:")
|
||||
print(f"将补 {len(added)} 个键:")
|
||||
for item in added:
|
||||
print(" +", item)
|
||||
if formatting_changed and not added:
|
||||
print(f"将整理 {target} 的节间空行")
|
||||
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("\n".join(original_lines) + "\n", encoding="utf-8")
|
||||
target.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
backup.write_text(old_text, encoding="utf-8")
|
||||
target.write_text(new_text, encoding="utf-8")
|
||||
print(f"✅ 已写入;备份 {backup.name}")
|
||||
return 0
|
||||
|
||||
|
||||
Reference in New Issue
Block a user