Compare commits
3 commits
d0f34de620
...
319e32ad34
| Author | SHA1 | Date | |
|---|---|---|---|
| 319e32ad34 | |||
| df0d8c5113 | |||
| 8e187c9790 |
4 changed files with 165 additions and 133 deletions
16
README.md
16
README.md
|
|
@ -1,3 +1,17 @@
|
||||||
# Ajal Todo CLI
|
# Ajal Todo CLI
|
||||||
|
|
||||||
A todo utility
|
A todo utility - enhanced
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
You should have `uv` installed or have `virtualenv` or `venv` already set up, and using python 3.12+
|
||||||
|
|
||||||
|
Run (assuming you are using `uv`):
|
||||||
|
|
||||||
|
```shell
|
||||||
|
uv venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
uv sync
|
||||||
|
```
|
||||||
|
|
||||||
|
Now you can run commands, start by running `uv run todo.py --help` and continue from there
|
||||||
|
|
|
||||||
9
pyproject.toml
Normal file
9
pyproject.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
[project]
|
||||||
|
name = "ajal-todo-cli"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Add your description here"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.12"
|
||||||
|
dependencies = [
|
||||||
|
"typer>=0.13.0",
|
||||||
|
]
|
||||||
17
todo.md
17
todo.md
|
|
@ -1,10 +1,11 @@
|
||||||
# A ToDo list
|
# A ToDo list
|
||||||
|
|
||||||
- Buy:
|
- [ ] Buy:
|
||||||
- Milk
|
- [ ] Milk
|
||||||
- Eggs
|
- [ ] Eggs
|
||||||
- Coffee
|
- [ ] Coffee
|
||||||
- Wine
|
- [ ] Wine
|
||||||
- Clean
|
- [ ] Clean
|
||||||
- Gutters
|
- [ ] Gutters
|
||||||
|
- [x] Love
|
||||||
|
- [x] Myself
|
||||||
|
|
|
||||||
256
todo.py
256
todo.py
|
|
@ -1,148 +1,156 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
import os
|
|
||||||
import re
|
import re
|
||||||
import sys
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
base_dir = os.path.abspath(os.path.dirname(__file__))
|
import typer
|
||||||
todo_file = os.path.join(base_dir, "todo.md")
|
|
||||||
|
cli = typer.Typer()
|
||||||
|
base_dir = Path(__file__).absolute().parent
|
||||||
|
|
||||||
|
|
||||||
def add_task(task: str, parent=None):
|
# == Helper classes and functions ==
|
||||||
print(f"Adding task '{task}' to '{parent if parent else 'root'}'")
|
|
||||||
todo = parse_todo()
|
|
||||||
if parent and parent not in todo:
|
|
||||||
print(f"Could not find parent task '{parent}' in root task list")
|
|
||||||
exit(1)
|
|
||||||
if parent:
|
|
||||||
todo[parent]["sub_tasks"][task] = {"completed": False}
|
|
||||||
else:
|
|
||||||
todo[task] = {"completed": False, "sub_tasks": {}}
|
|
||||||
write_todo(todo)
|
|
||||||
|
|
||||||
|
|
||||||
def list_tasks(parent=None):
|
@dataclass
|
||||||
print(f"Listing tasks in '{parent if parent else 'root'}'")
|
class LeafTask:
|
||||||
todo = parse_todo()
|
completed: bool = False
|
||||||
if parent and parent not in todo:
|
|
||||||
print(f"Could not find parent task '{parent}' in root task list")
|
|
||||||
exit(1)
|
|
||||||
if parent:
|
|
||||||
todo = {parent: todo[parent]}
|
|
||||||
print(render_todo(todo))
|
|
||||||
|
|
||||||
|
|
||||||
def complete_task(task, parent=None):
|
@dataclass
|
||||||
print(f"Marking task '{task}' in '{parent if parent else 'root'}' as completed")
|
class RootTask(LeafTask):
|
||||||
todo = parse_todo()
|
tasks: dict[str, LeafTask] = field(default_factory=dict)
|
||||||
if parent:
|
|
||||||
if parent not in todo:
|
|
||||||
print(f"Could not find parent task '{parent}' in root task list")
|
|
||||||
exit(1)
|
|
||||||
if task not in todo[parent]["sub_tasks"]:
|
|
||||||
print(f"Could not find task '{task}' in parent task '{parent}'")
|
|
||||||
exit(1)
|
|
||||||
if task not in todo:
|
|
||||||
print(f"Could not find task '{task}' in root task list")
|
|
||||||
exit(1)
|
|
||||||
if parent:
|
|
||||||
task = todo[parent]["sub_tasks"][task]
|
|
||||||
else:
|
|
||||||
task = todo[task]
|
|
||||||
task["completed"] = True
|
|
||||||
write_todo(todo)
|
|
||||||
|
|
||||||
|
|
||||||
def remove_task(task, parent=None):
|
def todo_parse(todo_file: Path) -> dict[str, RootTask]:
|
||||||
print(f"Removing task '{task}' from '{parent if parent else 'root'}'")
|
root_task = None
|
||||||
todo = parse_todo()
|
tasks = {}
|
||||||
if parent:
|
for line in todo_file.read_text().splitlines():
|
||||||
if parent not in todo:
|
if matches := re.match(r"^-\s+(\[(?P<status>[x ])]\s+)?(?P<task>.+)$", line.rstrip()):
|
||||||
print(f"Could not find parent task '{parent}' in root task list")
|
task_name = matches.group("task")
|
||||||
exit(1)
|
root_task = RootTask(completed=matches.group("status") == "x")
|
||||||
if task not in todo[parent]["sub_tasks"]:
|
tasks[task_name] = root_task
|
||||||
print(f"Could not find task '{task}' in parent task '{parent}'")
|
elif matches := re.match(r"^\s+-\s+(\[(?P<status>[x ])]\s+)?(?P<task>.+)$", line.rstrip()):
|
||||||
exit(1)
|
root_task.tasks[matches.group("task")] = LeafTask(completed=matches.group("status") == "x")
|
||||||
if task not in todo:
|
return tasks
|
||||||
print(f"Could not find task '{task}' in root task list")
|
|
||||||
exit(1)
|
|
||||||
if parent:
|
|
||||||
del todo[parent]["sub_tasks"][task]
|
|
||||||
else:
|
|
||||||
del todo[task]
|
|
||||||
write_todo(todo)
|
|
||||||
|
|
||||||
|
|
||||||
def print_help():
|
def todo_render(tasks: dict[str, RootTask]) -> str:
|
||||||
print("""Usage: todo.py [add|complete|remove] TASK [PARENT]
|
|
||||||
todo.py list [PARENT]
|
|
||||||
|
|
||||||
Manages todo.md file as a ToDo file""")
|
|
||||||
|
|
||||||
|
|
||||||
def parse_todo() -> dict[str, dict]:
|
|
||||||
todo = {}
|
|
||||||
with open(todo_file, "r") as f:
|
|
||||||
lines = f.readlines()
|
|
||||||
root_task = None
|
|
||||||
for line in lines:
|
|
||||||
if matches := re.match(r"^-\s+(\[(?P<status>[x ])]\s+)?(?P<task>.*)$", line.rstrip()):
|
|
||||||
root_task_name = matches.group("task")
|
|
||||||
root_task = {
|
|
||||||
"completed": matches.group("status") == "x",
|
|
||||||
"sub_tasks": {},
|
|
||||||
}
|
|
||||||
todo[root_task_name] = root_task
|
|
||||||
elif matches := re.match(r"^\s+-\s+(\[(?P<status>[x ])]\s+)?(?P<task>.*)$", line.rstrip()):
|
|
||||||
leaf_task = matches.group("task")
|
|
||||||
root_task["sub_tasks"][leaf_task] = {
|
|
||||||
"completed": matches.group("status") == "x",
|
|
||||||
}
|
|
||||||
return todo
|
|
||||||
|
|
||||||
|
|
||||||
def render_todo(todo: dict[str, dict]) -> str:
|
|
||||||
lines = ["# A ToDo list", ""]
|
lines = ["# A ToDo list", ""]
|
||||||
for task, task_data in todo.items(): # type: str, dict
|
for root_task_name, root_task in tasks.items(): # type: str, RootTask
|
||||||
lines.append(f"- [{'x' if task_data["completed"] else ' '}] {task}")
|
lines.append(f"- [{'x' if root_task.completed else ' '}] {root_task_name}")
|
||||||
for leaf_task, leaf_task_data in task_data["sub_tasks"].items():
|
for leaf_task_name, task in root_task.tasks.items():
|
||||||
lines.append(f" - [{'x' if leaf_task_data["completed"] else ' '}] {leaf_task}")
|
lines.append(f" - [{'x' if task.completed else ' '}] {leaf_task_name}")
|
||||||
lines += [""]
|
lines += [""]
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def write_todo(todo: dict[str, dict]):
|
def todo_write(todo_file: Path, todo: dict[str, RootTask]):
|
||||||
with open(todo_file, "w") as f:
|
todo_file.write_text(todo_render(tasks=todo))
|
||||||
f.write(render_todo(todo))
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
# == CLI helpers ==
|
||||||
if len(sys.argv) < 2:
|
|
||||||
print_help()
|
|
||||||
exit(1)
|
|
||||||
|
|
||||||
match sys.argv[1]:
|
|
||||||
case "help" | "--help" | "h" | "-h":
|
def root_callback(ctx: typer.Context, root: str = None) -> str | None:
|
||||||
print_help()
|
if root is None:
|
||||||
case "list":
|
return root
|
||||||
match sys.argv[2:]:
|
|
||||||
case [parent]:
|
if root not in ctx.obj["tasks"]:
|
||||||
list_tasks(parent)
|
typer.echo(f"Root task '{root}' does not exist", err=True)
|
||||||
case _:
|
raise typer.Exit(1)
|
||||||
list_tasks()
|
else:
|
||||||
case "add" | "complete" | "remove" as task_name:
|
ctx.obj.update({
|
||||||
task_func = f"{task_name}_task"
|
"tasks_root": ctx.obj["tasks"][root].tasks,
|
||||||
match sys.argv[2:]:
|
"tasks_class": LeafTask,
|
||||||
case [task]:
|
})
|
||||||
globals()[task_func](task)
|
|
||||||
case [task, parent]:
|
return root
|
||||||
globals()[task_func](task, parent)
|
|
||||||
case _:
|
|
||||||
print_help()
|
@cli.callback()
|
||||||
exit(1)
|
def main_callback(
|
||||||
case _:
|
ctx: typer.Context,
|
||||||
print_help()
|
todo_file: Path = lambda: base_dir / "todo.md",
|
||||||
exit(1)
|
verbose: bool = typer.Option(False, "--verbose", "-v", help="Set verbosity"),
|
||||||
|
):
|
||||||
|
ctx.obj = dict(ctx.params)
|
||||||
|
if not todo_file.exists():
|
||||||
|
typer.echo(f"--todo-file '{todo_file}' does not exist", err=True)
|
||||||
|
raise typer.Exit(1)
|
||||||
|
tasks = todo_parse(todo_file)
|
||||||
|
ctx.obj.update({
|
||||||
|
"tasks": tasks,
|
||||||
|
"tasks_root": tasks,
|
||||||
|
"task_class": RootTask,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# == CLI definitions ==
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command(name="list")
|
||||||
|
def task_list(
|
||||||
|
ctx: typer.Context,
|
||||||
|
root: Optional[str] = typer.Option(None, "--root", "-r", help="Root task", callback=root_callback),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
List all tasks in todo.md
|
||||||
|
|
||||||
|
Returns all tasks if no root task is passed, otherwise only the root task and subtasks
|
||||||
|
"""
|
||||||
|
ctx.obj["verbose"] and typer.echo(f"Listing tasks in '{root if root else 'root'}'")
|
||||||
|
if root is None:
|
||||||
|
typer.echo(todo_render(ctx.obj["tasks"]))
|
||||||
|
else:
|
||||||
|
typer.echo(todo_render({root: ctx.obj["tasks"][root]}))
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command(name="add")
|
||||||
|
def task_add(
|
||||||
|
ctx: typer.Context,
|
||||||
|
task: str = typer.Argument(..., help="Task name"),
|
||||||
|
root: Optional[str] = typer.Option(None, "--root", "-r", help="Root task", callback=root_callback),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Add a task to todo.md
|
||||||
|
"""
|
||||||
|
ctx.obj["verbose"] and typer.echo(f"Adding task '{task}' to '{root if root else 'root'}'")
|
||||||
|
ctx.obj["tasks_root"][task] = ctx.obj["task_class"]()
|
||||||
|
todo_write(ctx.obj["todo_file"], ctx.obj["tasks"])
|
||||||
|
typer.echo(todo_render(ctx.obj["tasks"]))
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command(name="complete")
|
||||||
|
def task_complete(
|
||||||
|
ctx: typer.Context,
|
||||||
|
task: str = typer.Argument(..., help="Task name"),
|
||||||
|
root: Optional[str] = typer.Option(None, "--root", "-r", help="Root task", callback=root_callback),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Mark a task in todo.md as completed
|
||||||
|
"""
|
||||||
|
ctx.obj["verbose"] and typer.echo(f"Marking task '{task}' in '{root if root else 'root'}' as completed")
|
||||||
|
ctx.obj["tasks_root"][task].completed = True
|
||||||
|
todo_write(ctx.obj["todo_file"], ctx.obj["tasks"])
|
||||||
|
typer.echo(todo_render(ctx.obj["tasks"]))
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command(name="remove")
|
||||||
|
def task_remove(
|
||||||
|
ctx: typer.Context,
|
||||||
|
task: str = typer.Argument(..., help="Task name"),
|
||||||
|
root: Optional[str] = typer.Option(None, "--root", "-r", help="Root task", callback=root_callback),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Remove a task from todo.md
|
||||||
|
"""
|
||||||
|
ctx.obj["verbose"] and typer.echo(f"Removing task '{task}' from '{root if root else 'root'}'")
|
||||||
|
del ctx.obj["tasks_root"][task]
|
||||||
|
todo_write(ctx.obj["todo_file"], ctx.obj["tasks"])
|
||||||
|
typer.echo(todo_render(ctx.obj["tasks"]))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
cli()
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue