117 lines
4.6 KiB
Python
117 lines
4.6 KiB
Python
#!/usr/bin/env python3
|
||
"""Финальный гейт: каждый проверенный документ лежит парой MD/DOCX в GOTOVO."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import case_paths
|
||
import verdict
|
||
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
VYDACHA = ("_ГОТОВ_К_ПОДАЧЕ", "_ЧЕРНОВИК", "") # суффиксы .docx в GOTOVO; те же держит faza_sborka
|
||
|
||
|
||
def _documents(case: Path) -> list[str]:
|
||
names = set()
|
||
for journal in (case_paths.verdicts_legacy(case), case_paths.verdicts(case)):
|
||
try:
|
||
lines = journal.read_text(encoding="utf-8").splitlines()
|
||
except OSError:
|
||
continue
|
||
for line in lines:
|
||
try:
|
||
entry = json.loads(line)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if not isinstance(entry, dict):
|
||
continue
|
||
name = entry.get("document")
|
||
if entry.get("kind") != "preflight" and isinstance(name, str):
|
||
names.add(name)
|
||
return sorted(names)
|
||
|
||
|
||
def check(case: Path, only: str | None = None) -> list[str]:
|
||
"""only — один документ прогона: прежние выдачи дела (вердикты старого конвейера) его сборку не судят."""
|
||
problems = []
|
||
documents = _documents(case)
|
||
if not documents:
|
||
return [f"{case}: в журнале вердиктов нет документов"]
|
||
if only is not None:
|
||
if only not in documents:
|
||
return [f"{case}: документа {only} нет в журнале вердиктов"]
|
||
documents = [only]
|
||
|
||
ready = case_paths.ready(case)
|
||
drafts = case_paths.drafts(case)
|
||
guard = ROOT / "scripts/document_guard.py"
|
||
for name in documents:
|
||
if Path(name).name != name or Path(name).suffix.lower() != ".md":
|
||
problems.append(f"{case}: недопустимое имя документа в журнале: {name!r}")
|
||
continue
|
||
md = ready / name
|
||
# T439: выдача с суффиксом готовности или черновика; старое имя без суффикса — для прежних выдач
|
||
docx = next((ready / f"{Path(name).stem}{s}.docx" for s in VYDACHA
|
||
if (ready / f"{Path(name).stem}{s}.docx").is_file()), ready / f"{Path(name).stem}.docx")
|
||
draft = drafts / name
|
||
missing = False
|
||
for path in (md, docx):
|
||
if not path.is_file() or path.is_symlink():
|
||
problems.append(f"{path}: файла нет")
|
||
missing = True
|
||
if missing:
|
||
continue
|
||
|
||
verdict_problems = verdict.check(draft)
|
||
if not verdict_problems and verdict.sha(md) != verdict.sha(draft):
|
||
verdict_problems = [
|
||
f"редакция в GOTOVO отличается от одобренной {draft}"
|
||
]
|
||
if not verdict_problems and docx.stem.endswith(VYDACHA[0]): # готовый к подаче — тот самый подписанный файл
|
||
verdict_problems = verdict.check_docx(draft, docx)
|
||
problems.extend(f"{md}: {problem}" for problem in verdict_problems)
|
||
|
||
try:
|
||
result = subprocess.run(
|
||
[sys.executable, str(guard), str(docx), "--md", str(md)],
|
||
cwd=ROOT, capture_output=True, text=True, timeout=360,
|
||
stdin=subprocess.DEVNULL)
|
||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||
problems.append(f"{docx}: document_guard.py не отработал: {exc}")
|
||
continue
|
||
if result.returncode:
|
||
detail = ((result.stdout or "") + (result.stderr or "")).strip()
|
||
problems.append(
|
||
f"{docx}: document_guard.py дал код {result.returncode}"
|
||
+ (f": {detail[-2000:]}" if detail else ""))
|
||
return problems
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
args = sys.argv[1:] if argv is None else argv
|
||
only = None
|
||
if len(args) == 3 and args[1] == "--doc":
|
||
args, only = args[:1], args[2]
|
||
if len(args) != 1:
|
||
print("usage: final_document.py CASE [--doc NAME.md]", file=sys.stderr)
|
||
return 2
|
||
raw_case = Path(args[0])
|
||
if raw_case.is_symlink() or not raw_case.is_dir():
|
||
print(f"{raw_case}: дело не найдено")
|
||
return 1
|
||
case = raw_case.resolve()
|
||
problems = check(case, only)
|
||
if problems:
|
||
for problem in problems:
|
||
print(problem)
|
||
return 1
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|