#!/usr/bin/env python3 """Иерархическая нумерация заголовков Markdown.""" from __future__ import annotations import argparse import re import shutil import sys from pathlib import Path FENCE = re.compile(r"^\s*(```|~~~)") HEADING = re.compile(r"^(#{1,6})\s+(.*)$") PREFIX = re.compile(r"^(?:\d+(?:\.\d+)*[.)]\s+|\d+(?:\.\d+)+\s+)") def process(text: str, mode: str, separator: str) -> tuple[str, int]: levels = [] in_fence = False for line in text.splitlines(): if FENCE.match(line): in_fence = not in_fence continue if not in_fence: match = HEADING.match(line) if match: levels.append(len(match.group(1))) base = min(levels) if mode == "add" and levels else 1 counters = [0] * 6 output: list[str] = [] in_fence = False changed = 0 for line in text.splitlines(): if FENCE.match(line): in_fence = not in_fence output.append(line) continue if in_fence: output.append(line) continue match = HEADING.match(line) if not match: output.append(line) continue level = len(match.group(1)) title = PREFIX.sub("", match.group(2).strip()) if mode == "add": rank = max(1, level - base + 1) for index in range(rank - 1): if counters[index] == 0: counters[index] = 1 counters[rank - 1] += 1 for index in range(rank, 6): counters[index] = 0 number = ".".join(str(counters[index]) for index in range(rank) if counters[index] > 0) title = f"{number}{separator}{title}" updated = "#" * level + " " + title if updated != line: changed += 1 output.append(updated) return "\n".join(output) + "\n", changed def main() -> int: parser = argparse.ArgumentParser(description="Автонумерация заголовков Markdown") parser.add_argument("--path", type=Path, required=True, help="Входной Markdown") parser.add_argument("--mode", choices=["add", "remove"], default="add", help="Добавить или убрать номера") parser.add_argument("--separator", default=". ", help="Разделитель после номера") parser.add_argument("--output", type=Path, help="Выходной файл") parser.add_argument("--in-place", action="store_true", help="Заменить исходный файл") args = parser.parse_args() source = args.path.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.in_place and args.output: parser.error("С --in-place не указывайте --output") if args.output and args.output.expanduser().resolve() == source.resolve(): parser.error("Выходной файл совпадает с входным, используйте --in-place") text = source.read_text(encoding="utf-8") result, changed = process(text, args.mode, args.separator) if args.in_place: backup = source.with_name(source.name + ".bak") shutil.copy2(source, backup) source.write_text(result, encoding="utf-8") print(f"Обновлено заголовков: {changed}, копия: {backup.name}") elif args.output: target = args.output.expanduser() target.parent.mkdir(parents=True, exist_ok=True) target.write_text(result, encoding="utf-8") print(f"Обновлено заголовков: {changed}, результат: {target}") else: print(result, end="") print(f"Обновлено заголовков: {changed}", file=sys.stderr) return 0 if __name__ == "__main__": raise SystemExit(main())