#!/usr/bin/env python3 """Kanban-доска в Markdown.""" from __future__ import annotations import argparse from pathlib import Path COLUMNS = [("backlog", "Backlog"), ("doing", "Doing"), ("done", "Done")] HEADERS = {"backlog": "Backlog", "doing": "Doing", "done": "Done"} TEMPLATE = "# Kanban\n\n## Backlog\n\n## Doing\n\n## Done\n" def parse_board(path: Path) -> dict[str, list[str]]: sections = {key: [] for key, _ in COLUMNS} current = None if not path.exists(): return sections for line in path.read_text(encoding="utf-8").splitlines(): stripped = line.strip() if stripped.startswith("## "): title = stripped[3:].strip().lower() current = title if title in sections else None elif current and (stripped.startswith("- [ ]") or stripped.startswith("- [x]")): sections[current].append(stripped) return sections def render_board(sections: dict[str, list[str]]) -> str: lines = ["# Kanban", ""] for key, _ in COLUMNS: lines.append(f"## {HEADERS[key]}") lines.append("") lines.extend(sections[key]) if sections[key]: lines.append("") return "\n".join(lines).rstrip() + "\n" def save_board(path: Path, sections: dict[str, list[str]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): path.with_name(path.name + ".bak").write_bytes(path.read_bytes()) path.write_text(render_board(sections), encoding="utf-8") def task_title(line: str) -> str: return line.split("]", 1)[1].strip() if "]" in line else line def command_init(args: argparse.Namespace) -> int: path = args.file.expanduser() if path.exists() and not args.force: raise SystemExit(f"Файл уже существует: {path}. Добавьте --force для замены.") path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): path.with_name(path.name + ".bak").write_bytes(path.read_bytes()) path.write_text(TEMPLATE, encoding="utf-8") print(f"Доска создана: {path}") return 0 def command_add(args: argparse.Namespace) -> int: path = args.file.expanduser() sections = parse_board(path) title = args.title.strip() if not title or "\n" in title: raise SystemExit("Название карточки пустое или содержит перевод строки") sections[args.column].append(f"- [ ] {title}") save_board(path, sections) print(f"Добавлено в {HEADERS[args.column]}: {title}") return 0 def command_move(args: argparse.Namespace) -> int: path = args.file.expanduser() sections = parse_board(path) matches = [] for key, lines in sections.items(): for index, line in enumerate(lines): if args.title.lower() in task_title(line).lower(): matches.append((key, index, line)) if not matches: raise SystemExit(f"Карточка не найдена: {args.title}") if len(matches) > 1: raise SystemExit("Найдено несколько карточек, уточните название") old_key, index, line = matches[0] if old_key == args.to: print("Карточка уже в этой колонке.") return 0 sections[old_key].pop(index) if args.to == "done": line = line.replace("- [ ]", "- [x]", 1) else: line = line.replace("- [x]", "- [ ]", 1) sections[args.to].append(line) save_board(path, sections) print(f"Перенесено в {HEADERS[args.to]}: {task_title(line)}") return 0 def command_list(args: argparse.Namespace) -> int: sections = parse_board(args.file.expanduser()) for key, _ in COLUMNS: print(f"{HEADERS[key]}: {len(sections[key])}") for line in sections[key]: print(f" {task_title(line)}") return 0 def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Kanban в Markdown") parser.add_argument("--file", type=Path, default=Path("kanban.md")) sub = parser.add_subparsers(dest="command", required=True) init_parser = sub.add_parser("init", help="Создать доску") init_parser.add_argument("--force", action="store_true") init_parser.set_defaults(func=command_init) add_parser = sub.add_parser("add", help="Добавить карточку") add_parser.add_argument("title") add_parser.add_argument("--column", choices=[key for key, _ in COLUMNS], default="backlog") add_parser.set_defaults(func=command_add) move_parser = sub.add_parser("move", help="Перенести карточку") move_parser.add_argument("title") move_parser.add_argument("--to", choices=[key for key, _ in COLUMNS], required=True) move_parser.set_defaults(func=command_move) list_parser = sub.add_parser("list", help="Показать доску") list_parser.set_defaults(func=command_list) return parser def main() -> int: args = build_parser().parse_args() return args.func(args) if __name__ == "__main__": raise SystemExit(main())