Files
dedinit.ru/tools/publish_drafts.py
estorozhenko f70179be4d
deploy-dedinit / Build & SFTP Deploy (push) Successful in 8m9s
feat(content): публикация 148 импортированных черновиков (change publish-imported-drafts)
- tools/publish_drafts.py: slug из имени каталога (транслитерация, дата-префикс отброшен),
  проверки (тело, hero.svg, tags, дата не в будущем), --dry-run, отчёт
- 148 бандлов: draft: false, 22 slug сгенерировано/исправлено (кириллица, blog-post_N, пробелы)
- удалён дубль 20141031 nanocad — осталась более поздняя версия 20141125 (тот же текст, чище вёрстка)
- 20161205 «Ежемесячный экономический отчёт»: битая ссылка с %20 (артефакт импорта) заменена на страницу отчёта CCP
- 4 черновика оставлены (пустое тело): dochka-obyasnyaet-pape, ya-ne-sharli-yavanya, 10-sposobov, netbox start
- openspec change publish-imported-drafts (proposal/specs/design/tasks)
2026-11-04 17:43:04 +00:00

204 lines
7.2 KiB
Python
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
"""Публикация импортированных черновиков dedinit.ru.
Что делает:
1. Находит бандлы content/posts/*/index.md с `draft: true`.
2. Исключает те, что публиковать нельзя: пустое тело (< MIN_BODY символов текста),
нет hero.svg, нет tags, дата в будущем, нет title.
3. Нормализует slug: если slug валиден (^[a-z0-9][a-z0-9-]*$) — оставляет, иначе выводит
из имени каталога (дата-префикс отбрасывается, кириллица транслитерируется,
пробелы и _ → дефис).
4. Проверяет уникальность slug; при коллизии бандл не публикуется и попадает в отчёт.
5. Ставит `draft: false`.
Использование:
python3 tools/publish_drafts.py --dry-run # только отчёт
python3 tools/publish_drafts.py # переписать frontmatter
"""
from __future__ import annotations
import datetime as dt
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
POSTS = REPO_ROOT / "content" / "posts"
MIN_BODY = 20
SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
DATE_PREFIX_RE = re.compile(r"^\d{8}\s*-?\s*")
TRANSLIT = {
"а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e",
"ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m",
"н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u",
"ф": "f", "х": "kh", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "shch",
"ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya",
}
DRY_RUN = "--dry-run" in sys.argv
def translit(text: str) -> str:
out = []
for ch in text.lower():
if ch in TRANSLIT:
out.append(TRANSLIT[ch])
elif ch.isascii():
out.append(ch)
else:
out.append("-")
return "".join(out)
def slug_from_dir(name: str) -> str:
stem = DATE_PREFIX_RE.sub("", name)
stem = translit(stem)
stem = re.sub(r"[^a-z0-9-]+", "-", stem)
stem = re.sub(r"-{2,}", "-", stem).strip("-")
return stem or "post"
def split_doc(text: str):
if not text.startswith("---"):
return None, None
parts = text.split("---", 2)
if len(parts) < 3:
return None, None
fm = parts[1].strip("\n").splitlines()
body = parts[2]
return fm, body
def fm_get(fm: list[str], key: str) -> str | None:
"""Значение однострочного ключа frontmatter."""
for line in fm:
m = re.match(rf"^{key}:\s*(.*)$", line)
if m:
return m.group(1).strip().strip("'\"")
return None
def fm_list(fm: list[str], key: str) -> list[str]:
"""Элементы ключа: и inline `[a, b]`, и блочный список `- 'a'`."""
for pos, line in enumerate(fm):
m = re.match(rf"^{key}:\s*(.*)$", line)
if not m:
continue
inline = m.group(1).strip()
if inline:
return [x.strip().strip("'\"") for x in inline.strip("[]").split(",") if x.strip()]
items = []
for nxt in fm[pos + 1:]:
if re.match(r"^\s+-\s*", nxt):
items.append(re.sub(r"^\s+-\s*", "", nxt).strip().strip("'\""))
elif nxt.strip() == "":
continue
else:
break
return items
return []
def body_text(body: str) -> str:
text = re.sub(r"<!--.*?-->", "", body, flags=re.S)
return re.sub(r"<[^>]+>|\s", "", text)
def main() -> int:
now = dt.datetime.now(dt.timezone.utc)
publish: list[dict] = []
excluded: list[tuple[str, str]] = []
for index in sorted(POSTS.glob("*/index.md")):
bundle = index.parent
raw = index.read_text(encoding="utf-8")
fm, body = split_doc(raw)
if fm is None:
if "draft: true" in raw:
excluded.append((bundle.name, "нет frontmatter при draft: true"))
continue
draft = (fm_get(fm, "draft") or "").lower()
if draft not in {"true", "yes", "on"}:
continue
reason = None
if len(body_text(body)) < MIN_BODY:
reason = "пустое тело"
elif not (bundle / "hero.svg").exists():
reason = "нет hero.svg"
elif fm_get(fm, "tags") is None and not fm_list(fm, "tags"):
reason = "нет ключа tags"
elif (fm_get(fm, "title") or "").strip() in {"", "Без названия", "Content Placeholder"}:
reason = "нет осмысленного title"
else:
date_raw = fm_get(fm, "date")
if date_raw:
try:
parsed = dt.datetime.fromisoformat(date_raw.replace(" ", "T", 1))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=dt.timezone.utc)
if parsed > now:
reason = "дата в будущем"
except ValueError:
pass
if reason:
excluded.append((bundle.name, reason))
continue
current = fm_get(fm, "slug")
if current and SLUG_RE.match(current):
slug = current
else:
slug = slug_from_dir(bundle.name)
publish.append({"bundle": bundle, "index": index, "fm": fm, "body": body,
"slug": slug, "old_slug": current, "raw": raw})
# уникальность slug
seen: dict[str, str] = {}
ready: list[dict] = []
for item in publish:
slug = item["slug"]
if slug in seen:
excluded.append((item["bundle"].name,
f"коллизия slug '{slug}' с {seen[slug]}"))
continue
seen[slug] = item["bundle"].name
ready.append(item)
print(f"К публикации: {len(ready)}")
print(f"Исключено: {len(excluded)}")
for name, reason in excluded:
print(f" - {name}: {reason}")
generated = [i for i in ready if i["slug"] != (i["old_slug"] or "")]
print(f"Slug сгенерирован/исправлен: {len(generated)}")
for i in generated:
print(f" {i['old_slug'] or '—':>28} → {i['slug']}")
if DRY_RUN:
print("\nDRY-RUN: файлы не изменены")
return 0
for item in ready:
fm = item["fm"]
new_fm: list[str] = []
for line in fm:
if re.match(r"^slug:", line) or re.match(r"^draft:", line):
continue
new_fm.append(line)
if re.match(r"^title:", line):
new_fm.append(f"slug: '{item['slug']}'")
if not any(re.match(r"^slug:", ln) for ln in new_fm):
new_fm.insert(0, f"slug: '{item['slug']}'")
new_fm.append("draft: false")
item["index"].write_text("---\n" + "\n".join(new_fm) + "\n---" + item["body"],
encoding="utf-8")
print(f"\nОпубликовано: {len(ready)} бандлов")
return 0
if __name__ == "__main__":
sys.exit(main())