#!/usr/bin/env python3 """Быстрые заметки в Markdown с тегами и поиском.""" from __future__ import annotations import argparse import re import sys from datetime import datetime from pathlib import Path DEFAULT_DATA = Path.home() / ".productivity" / "notes.md" def read_blocks(path: Path) -> list[str]: if not path.exists(): return [] text = path.read_text(encoding="utf-8") parts = re.split(r"(?m)^## ", text) return ["## " + part.strip() for part in parts[1:] if part.strip()] def append_note(path: Path, text: str, tags: list[str]) -> None: path.parent.mkdir(parents=True, exist_ok=True) stamp = datetime.now().strftime("%Y-%m-%d %H:%M") cleaned = text.strip() if not cleaned: raise SystemExit("Текст заметки пустой") tag_line = " ".join(f"#{tag.lstrip('#')}" for tag in tags if tag.strip()) block = f"\n## {stamp}\n\n{cleaned}\n" if tag_line: block += f"\n{tag_line}\n" with path.open("a", encoding="utf-8") as handle: handle.write(block) def command_add(args: argparse.Namespace) -> int: text = args.text if text == "-": text = sys.stdin.read() append_note(args.data, text, args.tags.split(",") if args.tags else []) print(f"Заметка добавлена: {args.data}") return 0 def command_list(args: argparse.Namespace) -> int: blocks = read_blocks(args.data) if not blocks: print("Заметок нет.") return 0 for block in blocks[-args.limit :]: print(block) print() return 0 def command_search(args: argparse.Namespace) -> int: try: pattern = re.compile(args.query, re.IGNORECASE) except re.error as error: raise SystemExit(f"Ошибка регулярного выражения: {error}") blocks = read_blocks(args.data) found = [block for block in blocks if pattern.search(block)] if not found: print("Совпадений нет.") return 0 for block in found[-args.limit :]: print(block) print() return 0 def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Быстрые заметки в Markdown") parser.add_argument("--data", type=Path, default=DEFAULT_DATA, help="Файл заметок") sub = parser.add_subparsers(dest="command", required=True) add_parser = sub.add_parser("add", help="Добавить заметку") add_parser.add_argument("text", help="Текст или дефис для чтения из stdin") add_parser.add_argument("--tags", default="", help="Теги через запятую") add_parser.set_defaults(func=command_add) list_parser = sub.add_parser("list", help="Показать последние заметки") list_parser.add_argument("--limit", type=int, default=10) list_parser.set_defaults(func=command_list) search_parser = sub.add_parser("search", help="Найти заметки") search_parser.add_argument("query") search_parser.add_argument("--limit", type=int, default=10) search_parser.set_defaults(func=command_search) return parser def main() -> int: args = build_parser().parse_args() if getattr(args, "limit", 1) < 1: raise SystemExit("--limit должен быть положительным") return args.func(args) if __name__ == "__main__": raise SystemExit(main())