docs(wiki): LLM-Wiki проекта + публикатор в вики Gitea; задачи — в issues
- docs/wiki/: SCHEMA, index, log, glossary, sessions/decisions/pitfalls/references (структура как в itacc.nixg.ru) - scripts/wiki_publish.py: публикация docs/wiki в нативную вики Gitea (плоские имена, index.md → Home, [[wikilink]] → код), проверено — 9 страниц - TODO.md: открытые задачи переведены в Gitea issues (#2 CardDAV-PUSH, #3 DnD доски, #4 backfill сущностей); «Разложить старые VTODO» отменена - docs/agents/issue-tracker.md: конвенция «задачи — в issues, процедуры — в вики» - WALKTHROUGH: раздел 2026-11-01 про трекер и вики + грабли Gitea wiki
This commit is contained in:
Executable
+154
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
wiki_publish.py — публикация docs/wiki в нативную вики Gitea.
|
||||
|
||||
Источник — каталог `docs/wiki/` репозитория (паттерн LLM-Wiki, см. SCHEMA.md).
|
||||
Цель — вики репозитория на gitea.nixg.ru (`Home` = docs/wiki/index.md).
|
||||
|
||||
Имена страниц плоские (вложенные Gitea сохраняет как `sessions%2F...-.md` и
|
||||
отдаёт битую ссылку):
|
||||
|
||||
index.md → Home
|
||||
SCHEMA.md → Schema
|
||||
log.md → Log
|
||||
glossary.md → Glossary
|
||||
sessions/2026-11-01-x.md → 2026-11-01-x
|
||||
decisions/decision-x.md → decision-x
|
||||
pitfalls/pitfall-x.md → pitfall-x
|
||||
references/reference-x.md → reference-x
|
||||
|
||||
`[[wikilink]]` превращаются в `код` (в Gitea они не резолвятся).
|
||||
|
||||
Запуск:
|
||||
python3 scripts/wiki_publish.py --dry-run
|
||||
python3 scripts/wiki_publish.py
|
||||
python3 scripts/wiki_publish.py --only session-2026-11-01-task-context-filters-wiki
|
||||
|
||||
Токен: env GITEA_NIXG_TOKEN, иначе читается /opt/hermes/.hermes/secrets/git-tokens.env.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parents[1]
|
||||
WIKI_DIR = BASE_DIR / "docs" / "wiki"
|
||||
SECRETS = Path("/opt/hermes/.hermes/secrets/git-tokens.env")
|
||||
|
||||
HOST = os.environ.get("GITEA_HOST", "https://gitea.nixg.ru").rstrip("/")
|
||||
REPO = os.environ.get("GITEA_WIKI_REPO", "hermes/email-assistant")
|
||||
|
||||
TOP_LEVEL = {
|
||||
"index.md": "Home",
|
||||
"SCHEMA.md": "Schema",
|
||||
"log.md": "Log",
|
||||
"glossary.md": "Glossary",
|
||||
}
|
||||
|
||||
_WIKILINK = re.compile(r"\[\[([^\]]+)\]\]")
|
||||
|
||||
|
||||
def token() -> str:
|
||||
value = os.environ.get("GITEA_NIXG_TOKEN") or os.environ.get("GITEA_TOKEN")
|
||||
if value:
|
||||
return value.strip()
|
||||
try:
|
||||
for line in SECRETS.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("GITEA_NIXG_TOKEN="):
|
||||
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
||||
except OSError:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def page_name(path: Path) -> str:
|
||||
rel = path.relative_to(WIKI_DIR).as_posix()
|
||||
if rel in TOP_LEVEL:
|
||||
return TOP_LEVEL[rel]
|
||||
return path.stem
|
||||
|
||||
|
||||
def render(text: str) -> str:
|
||||
"""Wikilinks → код-стиль: в Gitea навигация по ним не работает."""
|
||||
return _WIKILINK.sub(lambda m: f"`{m.group(1)}`", text)
|
||||
|
||||
|
||||
def api(method: str, endpoint: str, payload: dict | None = None) -> tuple[int, dict]:
|
||||
url = f"{HOST}/api/v1/repos/{REPO}/wiki{endpoint}"
|
||||
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
||||
request = urllib.request.Request(
|
||||
url, data=data, method=method,
|
||||
headers={"Authorization": f"token {token()}", "Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
body = response.read().decode("utf-8") or "{}"
|
||||
return response.status, json.loads(body)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, {"error": exc.read().decode("utf-8")[:200]}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Публикация docs/wiki в вики Gitea")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Только показать план")
|
||||
parser.add_argument("--only", default="", help="Одна страница (имя страницы)")
|
||||
parser.add_argument("--message", default="", help="Сообщение коммита вики")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not token():
|
||||
print("Нет токена: GITEA_NIXG_TOKEN / secrets/git-tokens.env", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
files = sorted(p for p in WIKI_DIR.rglob("*.md"))
|
||||
if not files:
|
||||
print(f"В {WIKI_DIR} нет .md", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
created = updated = failed = 0
|
||||
for path in files:
|
||||
name = page_name(path)
|
||||
if args.only and name != args.only:
|
||||
continue
|
||||
content = render(path.read_text(encoding="utf-8"))
|
||||
message = args.message or f"wiki: {path.relative_to(WIKI_DIR).as_posix()}"
|
||||
|
||||
if args.dry_run:
|
||||
print(f"[dry] {path.relative_to(WIKI_DIR)} → {name} ({len(content)} симв.)")
|
||||
continue
|
||||
|
||||
status, _ = api("GET", f"/page/{urllib.parse.quote(name, safe='')}")
|
||||
if status == 200:
|
||||
status, body = api("PATCH", f"/page/{urllib.parse.quote(name, safe='')}",
|
||||
{"title": name, "content": content, "message": message})
|
||||
action = "обновлена"
|
||||
else:
|
||||
status, body = api("POST", "/new",
|
||||
{"title": name, "content": content, "message": message})
|
||||
action = "создана"
|
||||
|
||||
if status in (200, 201):
|
||||
created += action == "создана"
|
||||
updated += action == "обновлена"
|
||||
print(f" ✓ {name}: {action}")
|
||||
else:
|
||||
failed += 1
|
||||
print(f" ✗ {name}: HTTP {status} {body.get('error', '')}", file=sys.stderr)
|
||||
|
||||
if args.dry_run:
|
||||
print("(dry-run: ничего не отправлено)")
|
||||
return 0
|
||||
print(f"\nГотово: создано={created}, обновлено={updated}, ошибок={failed}")
|
||||
print(f"Вики: {HOST}/{REPO}/wiki")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user