#!/usr/bin/env python3 """Сбор и закрытие Markdown-задач.""" from __future__ import annotations import argparse import re from datetime import date, timedelta from pathlib import Path TASK_RE = re.compile(r"^(?P\s*[-*]\s+\[)(?P[ xX])(?P\]\s+)(?P.+)$") TAG_RE = re.compile(r"(?:^|\s)#([\w-]+)") DUE_RE = re.compile(r"@due\((\d{4}-\d{2}-\d{2})\)") def iter_markdown(root: Path): for path in sorted(root.rglob("*.md")): if any(part.startswith(".") for part in path.parts): continue yield path def collect(root: Path): tasks = [] for path in iter_markdown(root): try: lines = path.read_text(encoding="utf-8").splitlines() except UnicodeDecodeError: continue for number, line in enumerate(lines, start=1): match = TASK_RE.match(line) if not match: continue tasks.append( { "path": path, "line": number, "done": match.group("state").lower() == "x", "text": match.group("text").strip(), } ) return tasks def tags_of(text: str) -> set[str]: return {tag.lower() for tag in TAG_RE.findall(text)} def due_of(text: str) -> date | None: match = DUE_RE.search(text) if not match: return None try: return date.fromisoformat(match.group(1)) except ValueError: return None def command_list(args: argparse.Namespace) -> int: root = args.dir.expanduser().resolve() if not root.is_dir(): raise SystemExit(f"Папка не найдена: {root}") today = date.today() limit = today + timedelta(days=args.due_within) shown = 0 for task in collect(root): if task["done"]: continue if args.tag and args.tag.lower() not in tags_of(task["text"]): continue if args.due_within >= 0: due = due_of(task["text"]) if due is None or due > limit: continue relative = task["path"].relative_to(root) print(f"{relative}:{task['line']} {task['text']}") shown += 1 if shown == 0: print("Открытых задач по фильтру нет.") return 0 def write_result(path: Path, text: str, force: bool) -> None: if path.exists() and not force: raise SystemExit(f"Файл уже существует: {path}. Добавьте --force для замены.") path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") print(f"Записано: {path}") def command_done(args: argparse.Namespace) -> int: source = args.file.expanduser() if not source.is_file(): raise SystemExit(f"Файл не найден: {source}") lines = source.read_text(encoding="utf-8").splitlines(keepends=True) if not 1 <= args.line <= len(lines): raise SystemExit(f"Строка {args.line} вне файла") match = TASK_RE.match(lines[args.line - 1].rstrip("\n")) if not match: raise SystemExit("В указанной строке нет Markdown-чекбокса") state = " " if args.reopen else "x" newline = lines[args.line - 1][len(lines[args.line - 1].rstrip("\n")) :] lines[args.line - 1] = match.group("prefix") + state + match.group("suffix") + match.group("text") + newline text = "".join(lines) if args.in_place: if not args.yes: raise SystemExit("Для изменения оригинала добавьте --yes") backup = source.with_name(source.name + ".bak") backup.write_bytes(source.read_bytes()) source.write_text(text, encoding="utf-8") print(f"Обновлено: {source}, копия: {backup}") return 0 if not args.output: raise SystemExit("Укажите --output или --in-place --yes") write_result(args.output.expanduser(), text, args.force) return 0 def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Задачи из Markdown") sub = parser.add_subparsers(dest="command", required=True) list_parser = sub.add_parser("list", help="Показать открытые задачи") list_parser.add_argument("--dir", type=Path, default=Path(".")) list_parser.add_argument("--tag", default="") list_parser.add_argument("--due-within", type=int, default=-1, help="Дней до срока, -1 отключает фильтр") list_parser.set_defaults(func=command_list) done_parser = sub.add_parser("done", help="Закрыть или открыть задачу") done_parser.add_argument("--file", type=Path, required=True) done_parser.add_argument("--line", type=int, required=True) done_parser.add_argument("--output", type=Path) done_parser.add_argument("--in-place", action="store_true") done_parser.add_argument("--reopen", action="store_true") done_parser.add_argument("--force", action="store_true") done_parser.add_argument("--yes", action="store_true") done_parser.set_defaults(func=command_done) return parser def main() -> int: args = build_parser().parse_args() if getattr(args, "due_within", 0) < -1: raise SystemExit("--due-within не может быть меньше -1") return args.func(args) if __name__ == "__main__": raise SystemExit(main())