[FIX] рефакторинг: C1-C4 критичные + W1-W10 предупреждения
C1: LaTeX escaping спецсимволов (& % $ # _ { } ~ ^ \)
C2: text.capitalize() → first char uppercase only
C3: run_xelatex проверяет returncode
C4: парсинг лога при ошибке второго прохода
W1: Удалены мёртвые счётчики section/subsection/subsubsection
W2: text.upper() вычисляется один раз
W3: Единая сигнатура хендлеров (r, tok) для всех
W4: Джэгged строки таблицы паддятся до max колонок
W5: Пустой lang в code fence → без [language=]
W6: hr() вынесен из code.py в hr.py
W7: Валидация обязательных полей front matter
W8: Имя вуза конфигурируется через front matter
W9: -> None аннотация main()
W10: \n в конце END_DOCUMENT
+ Dockerfile: добавлен texlive-fonts-recommended
This commit is contained in:
+11
-12
@@ -9,6 +9,13 @@ from md2gost.parser import Parser
|
||||
from md2gost.render import Renderer
|
||||
|
||||
|
||||
def _print_latex_errors(log_path: Path) -> None:
|
||||
if log_path.exists():
|
||||
for line in log_path.read_text(errors="replace").splitlines():
|
||||
if line.startswith("!"):
|
||||
print(f" {line}", file=sys.stderr)
|
||||
|
||||
|
||||
def run_xelatex(tex_path: Path, output_dir: Path) -> bool:
|
||||
result = subprocess.run(
|
||||
["xelatex", "-interaction=nonstopmode",
|
||||
@@ -16,10 +23,10 @@ def run_xelatex(tex_path: Path, output_dir: Path) -> bool:
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
pdf_path = output_dir / tex_path.with_suffix(".pdf").name
|
||||
return pdf_path.exists()
|
||||
return pdf_path.exists() and result.returncode == 0
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
cli = argparse.ArgumentParser(
|
||||
prog="md2gost",
|
||||
description="Markdown → LaTeX конвертер по ГОСТ Р 7.0.5-2008",
|
||||
@@ -46,36 +53,28 @@ def main():
|
||||
renderer = Renderer(parser.tokens, parser.front_matter)
|
||||
latex = renderer.render()
|
||||
|
||||
# Собираем во временную директорию, копируем только .tex и .pdf
|
||||
with tempfile.TemporaryDirectory(prefix="md2gost-") as cache:
|
||||
cache_dir = Path(cache)
|
||||
|
||||
# Генерируем .tex в кэш
|
||||
tex_name = args.input.with_suffix(".tex").name
|
||||
tex_path = cache_dir / tex_name
|
||||
tex_path.write_text(latex, encoding="utf-8")
|
||||
|
||||
# Копируем .tex в выходную директорию
|
||||
final_tex = args.output / tex_name
|
||||
shutil.copy2(tex_path, final_tex)
|
||||
print(f"→ {final_tex}")
|
||||
|
||||
if not args.no_pdf:
|
||||
# Компилируем PDF в кэше (два прохода для TOC)
|
||||
if not run_xelatex(tex_path, cache_dir):
|
||||
print("ошибка: xelatex не собрал PDF", file=sys.stderr)
|
||||
log_path = cache_dir / "report.log"
|
||||
if log_path.exists():
|
||||
for line in log_path.read_text(errors="replace").splitlines():
|
||||
if line.startswith("!"):
|
||||
print(f" {line}", file=sys.stderr)
|
||||
_print_latex_errors(cache_dir / "report.log")
|
||||
sys.exit(1)
|
||||
|
||||
if not run_xelatex(tex_path, cache_dir):
|
||||
print("ошибка: xelatex (2-й проход) не собрал PDF", file=sys.stderr)
|
||||
_print_latex_errors(cache_dir / "report.log")
|
||||
sys.exit(1)
|
||||
|
||||
# Копируем .pdf в выходную директорию
|
||||
pdf_name = args.input.with_suffix(".pdf").name
|
||||
pdf_path = cache_dir / pdf_name
|
||||
final_pdf = args.output / pdf_name
|
||||
|
||||
Reference in New Issue
Block a user