163 lines
5.9 KiB
Python
163 lines
5.9 KiB
Python
#!/usr/bin/env python3
|
||
"""Baut das Zauber-/Liturgie-Seed aus dem Vault.
|
||
|
||
Liest alle Zauberdateien unter ``RPG/5-Regeln/Zauber/{Arkan,Klerikal}/Grad N``
|
||
und schreibt ``w estreiche_website/sql/seed_spells.sql`` (INSERT IGNORE, damit
|
||
der Installer mehrfach laufen darf).
|
||
|
||
python3 tools/build_spell_seed.py
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
SPELL_DIR = ROOT / "RPG" / "5-Regeln" / "Zauber"
|
||
OUT = ROOT / "westreiche_website" / "sql" / "seed_spells.sql"
|
||
|
||
FIELD_RE = re.compile(r"\*\*(?P<key>[^:*]+):\*\*\s*(?P<value>[^·»]+)")
|
||
|
||
|
||
def plain(text: str) -> str:
|
||
"""Markdown-Reste entfernen: Wikilinks, Fettungen, Kursiv-Satzzeichen."""
|
||
text = re.sub(r"\[\[([^|\]]*\|)?([^\]]*)\]\]", r"\2", text)
|
||
text = text.replace("**", "").replace("''", "")
|
||
return text.strip()
|
||
|
||
|
||
def extract_body(text: str) -> str:
|
||
"""Regeltext für den Detail-Schirm: Abschnitte „Wirkung“ und „Regelhinweise“.
|
||
|
||
Stichpunkte werden zu „• “-Zeilen, Absätze bleiben als Leerzeile erhalten.
|
||
"""
|
||
blocks: list[str] = []
|
||
for heading in ("Wirkung", "Regelhinweise"):
|
||
match = re.search(r"^##\s*" + heading + r"\s*$(.*?)(?=^##\s|\Z)", text, re.S | re.M)
|
||
if not match:
|
||
continue
|
||
lines: list[str] = []
|
||
for raw in match.group(1).splitlines():
|
||
line = raw.strip()
|
||
if not line:
|
||
continue
|
||
if line.startswith("###"):
|
||
lines.append(plain(line.lstrip("#").strip()))
|
||
continue
|
||
bullet = re.match(r"^([-*])\s+(.*)$", line)
|
||
line = plain(bullet.group(2) if bullet else line)
|
||
if line == "":
|
||
continue
|
||
lines.append("• " + line if bullet else line)
|
||
if lines:
|
||
blocks.append("\n".join(lines))
|
||
return "\n\n".join(blocks).strip()
|
||
|
||
|
||
def parse_file(path: Path, school: str, grade: int) -> dict | None:
|
||
text = path.read_text(encoding="utf-8", errors="replace")
|
||
if not text.lstrip().startswith("#"):
|
||
return None
|
||
name = path.stem.strip()
|
||
fields: dict[str, str] = {}
|
||
for line in text.splitlines()[:12]:
|
||
if "**Schule:**" in line or "**Dauer:**" in line or "**Klasse:**" in line:
|
||
for m in FIELD_RE.finditer(line):
|
||
fields[m.group("key").strip().lower()] = m.group("value").strip()
|
||
# Kurzfassung: erster Stichpunkt unter "## Wirkung"
|
||
summary = ""
|
||
match = re.search(r"##\s*Wirkung\s*(.+?)(?:\n##\s|\Z)", text, re.S)
|
||
if match:
|
||
for line in match.group(1).splitlines():
|
||
line = line.strip()
|
||
if line.startswith(("-", "*")):
|
||
summary = re.sub(r"^[-*]\s*", "", line)
|
||
summary = plain(summary)
|
||
break
|
||
return {
|
||
"name": name,
|
||
"school": school,
|
||
"grade": grade,
|
||
"classes": fields.get("klasse", "")[:120],
|
||
"tradition": fields.get("schule", "")[:120],
|
||
"duration": fields.get("dauer", "")[:80],
|
||
"range_text": fields.get("reichweite", "")[:80],
|
||
"summary": summary[:400],
|
||
"body": extract_body(text),
|
||
}
|
||
|
||
|
||
def sql_quote(value: str) -> str:
|
||
return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
|
||
|
||
|
||
def main() -> int:
|
||
if not SPELL_DIR.is_dir():
|
||
print(f"Zauberordner fehlt: {SPELL_DIR}", file=sys.stderr)
|
||
return 1
|
||
|
||
rows: list[dict] = []
|
||
for school, folder in (("arkan", "Arkan"), ("klerikal", "Klerikal")):
|
||
for grade_dir in sorted((SPELL_DIR / folder).glob("Grad *")):
|
||
match = re.search(r"Grad\s*(\d+)", grade_dir.name)
|
||
if not match:
|
||
continue
|
||
grade = int(match.group(1))
|
||
for path in sorted(grade_dir.glob("*.md")):
|
||
row = parse_file(path, school, grade)
|
||
if row:
|
||
rows.append(row)
|
||
|
||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||
lines = [
|
||
"-- Automatisch erzeugt von tools/build_spell_seed.py – nicht von Hand ändern.",
|
||
"-- Quelle: RPG/5-Regeln/Zauber/{Arkan,Klerikal}/Grad N/*.md",
|
||
f"-- {sum(1 for r in rows if r['school'] == 'arkan')} arkane Zauber, "
|
||
f"{sum(1 for r in rows if r['school'] == 'klerikal')} Liturgien.",
|
||
"",
|
||
]
|
||
chunk: list[str] = []
|
||
for row in rows:
|
||
chunk.append(
|
||
"({}, {}, {}, {}, {}, {}, {}, {}, {})".format(
|
||
sql_quote(row["name"]),
|
||
sql_quote(row["school"]),
|
||
row["grade"],
|
||
sql_quote(row["classes"]),
|
||
sql_quote(row["tradition"]),
|
||
sql_quote(row["duration"]),
|
||
sql_quote(row["range_text"]),
|
||
sql_quote(row["summary"]),
|
||
sql_quote(row["body"]),
|
||
)
|
||
)
|
||
if len(chunk) == 40:
|
||
lines.append(
|
||
"INSERT INTO spells (name, school, grade, classes, tradition, duration, range_text, summary, body) VALUES\n"
|
||
+ ",\n".join(chunk)
|
||
+ "\nON DUPLICATE KEY UPDATE classes = VALUES(classes), tradition = VALUES(tradition),\n"
|
||
" duration = VALUES(duration), range_text = VALUES(range_text),\n"
|
||
" summary = VALUES(summary), body = VALUES(body);"
|
||
)
|
||
lines.append("")
|
||
chunk = []
|
||
if chunk:
|
||
lines.append(
|
||
"INSERT INTO spells (name, school, grade, classes, tradition, duration, range_text, summary, body) VALUES\n"
|
||
+ ",\n".join(chunk)
|
||
+ "\nON DUPLICATE KEY UPDATE classes = VALUES(classes), tradition = VALUES(tradition),\n"
|
||
" duration = VALUES(duration), range_text = VALUES(range_text),\n"
|
||
" summary = VALUES(summary), body = VALUES(body);"
|
||
)
|
||
lines.append("")
|
||
|
||
OUT.write_text("\n".join(lines), encoding="utf-8")
|
||
print(f"{len(rows)} Zauber/Liturgien → {OUT.relative_to(ROOT)}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|