Files
hermes 1fa6aef6ab
wiki-sync / Publish docs/wiki to Gitea wiki (push) Successful in 24s
fix(wiki): содержимое страниц через content_base64
Gitea игнорирует поле content в POST/PATCH wiki API — страницы создавались
пустыми (0 байт, видно только по git clone вики-репозитория). Теперь содержимое
передаётся в content_base64; проверено — 9 страниц с реальным текстом, CI-прогон
и публикация зелёные. Питфолл записан в reference-wiki-publishing.
2026-11-01 20:10:28 +00:00

183 lines
6.8 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 base64
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("WIKI_TOKEN") or 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 _b64(text: str) -> str:
"""Gitea wiki API принимает содержимое только в content_base64.
Поле `content` молча игнорируется — страница создаётся пустой (0 байт).
"""
return base64.b64encode(text.encode("utf-8")).decode("ascii")
def existing_pages() -> dict[str, str]:
"""title → sub_url для уже созданных страниц.
Gitea хранит часть страниц с суффиксом «.-» (`decision-x.-.md`), поэтому
GET /wiki/page/<title> для них отвечает 404. Список страниц отдаёт и
настоящий title, и рабочий sub_url — по нему и адресуем.
"""
status, body = api("GET", "/pages")
if status != 200 or not isinstance(body, list):
return {}
return {page.get("title", ""): page.get("sub_url") or page.get("title", "")
for page in body if page.get("title")}
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
pages = existing_pages()
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:
action = "обновить" if name in pages else "создать"
print(f"[dry] {path.relative_to(WIKI_DIR)} → {name} ({action}, {len(content)} симв.)")
continue
if name in pages:
target = urllib.parse.quote(pages[name], safe="")
status, body = api("PATCH", f"/page/{target}",
{"title": name, "content_base64": _b64(content),
"message": message})
action = "обновлена"
else:
status, body = api("POST", "/new",
{"title": name, "content_base64": _b64(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())