renamer 附属字幕/保留名/语言正则、variety 特典词表、subtitle 文本编码与语言词表、jellyfin 扫描面、分辨率分档、字幕探测阈值全部改读 config.ini(缺省回落原值)。 fix(renamer): 附属文件跟随 <目标名>-日期.期名,避免整库整理时 NFO/字幕与视频失联(原先会把尾巴抹掉)。
129 lines
4.7 KiB
Python
129 lines
4.7 KiB
Python
#!/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 normalize(lines: list[str]) -> list[str]:
|
||
"""节标题前统一留一个空行(补项后不会和上一节黏在一起)。"""
|
||
formatted: 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
|
||
|
||
|
||
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)
|
||
original_lines = target.read_text(encoding="utf-8").splitlines()
|
||
lines = list(original_lines)
|
||
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}")
|
||
|
||
lines = normalize(lines)
|
||
formatting_changed = lines != original_lines
|
||
if not added and not formatting_changed:
|
||
print("✅ 配置已是最新,无需补项")
|
||
return 0
|
||
|
||
if added:
|
||
print(f"将补 {len(added)} 项到 {target}:")
|
||
for item in added:
|
||
print(" +", item)
|
||
if formatting_changed and not added:
|
||
print(f"将整理 {target} 的节间空行")
|
||
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")
|
||
print(f"✅ 已写入;备份 {backup.name}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|