pyn/pyn/todo.py
2025-12-03 21:23:01 +11:00

95 lines
3.1 KiB
Python

from pyn.common import parser, logger
from pyn.config import Config
from pyn import notes
from pyn.commands import group as parent_group
from shutil import get_terminal_size
p = parent_group.add_parser("todo", help="manipulate todo items")
group = p.add_subparsers()
### Add a todo
def cmd_add_todo(config: Config, item: list[str], notebook: str, create: bool) -> None:
item = " ".join(item)
filename = notes.get_note_filename(config, "todo", notebook)
notes.append_template(config, filename, "todo", item=item)
add_todo = group.add_parser("add", aliases=["a"])
add_todo.add_argument("--notebook", "-n", help="add to this notebook [general]")
add_todo.add_argument(
"--create", "-c", action="store_true", help="start a new todo list"
)
add_todo.add_argument("item", help="item to add", nargs="*")
add_todo.set_defaults(func=cmd_add_todo)
def cmd_list_pending(config: Config, notebook: str):
nb = None
cols, _ = get_terminal_size()
fmt = "{snippet:" + str(cols - 20) + "s} {name}"
for result in notes.search_contents(
config, "* [ ]", notebook, file_matcher="*-todo.md"
):
entry = notes.file_entry(config, result.filename)
if entry.notebook != nb:
nb = entry.notebook
print(f"\nNotebook: {entry.notebook}")
print(fmt.format(snippet=result.snippet, name=result.filename.name))
pending_todo = group.add_parser("pending", aliases="p", help="list pending tasks")
pending_todo.add_argument("--notebook", "-n", help="limit to this notebook [None]")
pending_todo.set_defaults(func=cmd_list_pending)
def cmd_mark_complete(
config: Config,
item: list[str],
notebook: str,
reverse: bool = False,
multiple: bool = False,
) -> None:
checked, unchecked = "x", " "
if reverse:
checked, unchecked = unchecked, checked
item = " ".join(item)
results = list(
notes.search_contents(
config, f"* [{unchecked}] {item}", notebook, full_line=True
)
)
if not results:
raise RuntimeError("No matching item found")
if not multiple and len(results) > 1:
raise RuntimeError("Multiple items matched - use --multiple to allow update")
update = f"* [{checked}] {item}"
for result in results:
entry = notes.file_entry(config, result.filename)
with open(result.filename, "r") as f:
lines = f.readlines()
lines[result.line_number - 1] = update + "\n"
with open(result.filename, "w") as f:
f.write("".join(lines))
print(
f"{entry.notebook:<20s} {entry.filename:30s}[{result.line_number:3d}] {update}"
)
complete_todo = group.add_parser("mark", aliases=["m"], help="mark a note complete")
complete_todo.add_argument("--notebook", "-n", help="add to this notebook [general]")
complete_todo.add_argument(
"--reverse", "-r", action="store_true", help="uncheck a previously checked item"
)
complete_todo.add_argument(
"--multiple", "-m", action="store_true", help="allow marking all matches"
)
complete_todo.add_argument("item", help="item to add", nargs="*")
complete_todo.set_defaults(func=cmd_mark_complete)