summaryrefslogtreecommitdiff
path: root/skills/todo/todo.py
blob: 1aa740e4b954a3c9fd866c6934b9162cf31233d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3

import argparse
import json
import os
import sys
import tempfile
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path

ITEM_WIDTH = 100
TAIL = 5


@dataclass
class TodoItem:
    text: str
    done: bool = False
    created: int = field(default_factory=lambda: int(time.time()))

    @classmethod
    def from_json(cls, obj: object) -> "TodoItem":
        if not isinstance(obj, dict):
            return cls(text="")
        return cls(
            text=str(obj.get("text", "")),
            done=bool(obj["done"]),
            created=int(obj["created"]),
        )


def _stat_fields(pid: int) -> tuple[str, int, int]:
    with open(f"/proc/{pid}/stat", "rb") as fh:
        data = fh.read()
    # comm sits in parens and may contain spaces; split after the final ')'.
    head, _, rest = data.rpartition(b") ")
    comm = head.split(b"(", 1)[1].decode("utf-8", "replace")
    fields = rest.split()
    return comm, int(fields[1]), int(fields[19])  # comm, ppid, starttime


def harness_pid() -> int | None:
    pid = os.getpid()
    for _ in range(64):
        try:
            _comm, ppid, _start = _stat_fields(pid)
        except (OSError, IndexError, ValueError):
            return None
        if ppid <= 1 or ppid == pid:
            return None
        try:
            comm, _, _ = _stat_fields(ppid)
        except (OSError, IndexError, ValueError):
            return None
        if comm == "hax":
            return ppid
        pid = ppid
    return None


def state_path() -> Path:
    pid = harness_pid()
    if pid is not None:
        try:
            _comm, _ppid, start = _stat_fields(pid)
            key = f"{pid}-{start}"
        except (OSError, IndexError, ValueError):
            key = str(pid)
    else:
        key = "manual"
    root = Path(tempfile.gettempdir()) / f"hax-todo-{os.getuid()}"
    return root / f"{key}.json"


def truncate(text: str) -> str:
    text = " ".join(text.split())
    if len(text) > ITEM_WIDTH:
        text = text[: ITEM_WIDTH - 1] + "…"
    return text


class Todo:
    def __init__(self, path: Path) -> None:
        self.path = path
        self.items: dict[int, TodoItem]
        self.next_id: int
        self.items, self.next_id = self._read()

    @classmethod
    def open(cls) -> "Todo":
        return cls(state_path())

    def _read(self) -> tuple[dict[int, TodoItem], int]:
        try:
            data = json.loads(self.path.read_text())
        except (OSError, ValueError):
            return {}, 0
        if not isinstance(data, dict) or not isinstance(data.get("items"), dict):
            return {}, 0
        items = {}
        for key, obj in data["items"].items():
            try:
                items[int(key)] = TodoItem.from_json(obj)
            except ValueError:
                continue
        try:
            next_id = int(data["next_id"])
        except (KeyError, TypeError, ValueError):
            next_id = max(items, default=-1) + 1
        return items, next_id

    def _write(self) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        tmp = self.path.with_name(self.path.name + ".tmp")
        payload = {
            "next_id": self.next_id,
            "items": {str(id): asdict(item) for id, item in self.items.items()},
        }
        tmp.write_text(json.dumps(payload, indent=1))
        os.replace(tmp, self.path)

    def _line(self, id: int, *, full: bool) -> str:
        item = self.items[id]
        mark = "x" if item.done else " "
        text = item.text if full else truncate(item.text)
        return f"{id:3d}. [{mark}] {text}"

    def render(self, ids: list[int]) -> str:
        if not self.items:
            return "(no todos)"
        if ids:
            lines = [self._line(id, full=True) for id in ids]
        else:
            lines = [self._line(id, full=False) for id in sorted(self.items)]
        return "\n".join(lines) if lines else "(no todos)"

    def tail_view(self) -> str:
        lines = [self._line(id, full=False) for id in sorted(self.items)[-TAIL:]]
        return "\n".join(lines) if lines else "(no todos)"

    def checked(self, ids: list[int]) -> list[int]:
        checked = []
        for id in ids:
            if id not in self.items:
                sys.exit(f"error: no todo with id {id} (have {len(self.items)})")
            checked.append(id)
        return checked

    def add(self, text: str) -> tuple[int, TodoItem]:
        item = TodoItem(text=text)
        id = self.next_id
        self.next_id += 1
        self.items[id] = item
        self._write()
        return id, item

    def mark_done(self, ids: list[int]) -> list[tuple[int, TodoItem]]:
        marked = [(id, self.items[id]) for id in self.checked(ids)]
        for _id, item in marked:
            item.done = True
        self._write()
        return marked

    def remove(self, ids: list[int]) -> list[tuple[int, TodoItem]]:
        removed = [(id, self.items[id]) for id in self.checked(ids)]
        for id in set(ids):
            del self.items[id]
        self._write()
        return removed


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="todo", description="Per-session todo list for the hax harness."
    )
    sub = parser.add_subparsers(dest="command", required=True)

    sub_list = sub.add_parser("list", help="print every item, or specific ones in full")
    sub_list.add_argument("id", nargs="*", type=int, metavar="ID")

    sub_add = sub.add_parser("add", help="append an item")
    sub_add.add_argument("text", nargs="+", metavar="TEXT")

    sub_done = sub.add_parser("done", help="mark items done")
    sub_done.add_argument("id", nargs="+", type=int, metavar="ID")

    sub_remove = sub.add_parser("remove", help="delete items")
    sub_remove.add_argument("id", nargs="+", type=int, metavar="ID")

    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    todo = Todo.open()

    match args.command:
        case "list":
            print(todo.render(todo.checked(args.id)))
        case "add":
            id, item = todo.add(" ".join(args.text))
            print(f"added {id}: {truncate(item.text)}")
            print(todo.tail_view())
        case "done":
            for id, item in todo.mark_done(args.id):
                print(f"done {id}: {item.text}")
            print(todo.tail_view())
        case "remove":
            for id, item in todo.remove(args.id):
                print(f"removed {id}: {item.text}")
            print(todo.tail_view())

    return 0


if __name__ == "__main__":
    sys.exit(main())