-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
268 lines (221 loc) · 6.6 KB
/
cli.py
File metadata and controls
268 lines (221 loc) · 6.6 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
"""CLI for todo-app. Manipulates todos.json and completed.json directly."""
import json
import sys
import os
import uuid
import copy
from datetime import datetime
DATA_DIR = os.path.expanduser("~/Library/Application Support/Todor")
os.makedirs(DATA_DIR, exist_ok=True)
DATA_FILE = os.path.join(DATA_DIR, "todos.json")
COMPLETED_FILE = os.path.join(DATA_DIR, "completed.json")
def load():
if not os.path.exists(DATA_FILE):
return []
with open(DATA_FILE) as f:
return json.load(f)
def save(todos):
with open(DATA_FILE, "w") as f:
json.dump(todos, f, indent=2)
def load_completed():
if not os.path.exists(COMPLETED_FILE):
return []
with open(COMPLETED_FILE) as f:
return json.load(f)
def save_completed(completed):
with open(COMPLETED_FILE, "w") as f:
json.dump(completed, f, indent=2)
def make_todo(text):
return {
"id": str(uuid.uuid4())[:8],
"text": text,
"completed": False,
"notes": "",
"created": datetime.now().isoformat(),
"children": [],
}
def find_by_path(todos, path):
"""Find a todo by dot-separated index path like '0', '1.2', '0.1.3'."""
parts = [int(p) for p in path.split(".")]
current = todos
node = None
for i, idx in enumerate(parts):
if idx < 0 or idx >= len(current):
print(f"Error: index {path} out of range")
sys.exit(1)
node = current[idx]
if i < len(parts) - 1:
current = node["children"]
return node, current, parts[-1]
def print_todos(todos, indent=0):
for i, t in enumerate(todos):
check = "x" if t["completed"] else " "
prefix = " " * indent
idx = str(i)
due_str = ""
if t.get("due") and indent == 0:
from datetime import date
try:
due = date.fromisoformat(t["due"])
diff = (due - date.today()).days
if diff < 0:
due_str = f" ({abs(diff)}d overdue)"
elif diff == 0:
due_str = " (due today)"
elif diff == 1:
due_str = " (due tomorrow)"
else:
due_str = f" ({diff}d left)"
except ValueError:
due_str = f" (due: {t['due']})"
print(f"{prefix}[{check}] {idx}. {t['text']}{due_str}")
if t.get("notes"):
for line in t["notes"].split("\n"):
print(f"{prefix} | {line}")
if t["children"]:
print_todos(t["children"], indent + 1)
def complete_all(t):
t["completed"] = True
for c in t["children"]:
complete_all(c)
def cmd_add(args):
todos = load()
parent_path = None
due_date = None
text_parts = []
for a in args:
if a.startswith("--parent="):
parent_path = a.split("=", 1)[1]
elif a.startswith("--due="):
due_date = a.split("=", 1)[1]
else:
text_parts.append(a)
text = " ".join(text_parts)
if not text:
print("Error: provide todo text")
sys.exit(1)
new = make_todo(text)
if due_date:
new["due"] = due_date
if parent_path:
node, _, _ = find_by_path(todos, parent_path)
node["children"].append(new)
else:
todos.append(new)
save(todos)
print(f"Added: {text}")
def cmd_complete(args):
todos = load()
completed = load_completed()
path = args[0]
is_top_level = "." not in path
node, parent_list, idx = find_by_path(todos, path)
complete_all(node)
node["completed_at"] = datetime.now().isoformat()
# Add to completed record
completed.insert(0, copy.deepcopy(node))
save_completed(completed)
if is_top_level:
# Top-level: remove from active
parent_list.pop(idx)
# Sub-todo: stays in active (already marked completed)
save(todos)
print(f"Completed: {node['text']}")
def cmd_uncomplete(args):
todos = load()
path = args[0]
node, _, _ = find_by_path(todos, path)
node["completed"] = False
save(todos)
print(f"Uncompleted: {node['text']}")
def cmd_note(args):
todos = load()
path = args[0]
note_text = " ".join(args[1:])
node, _, _ = find_by_path(todos, path)
node["notes"] = note_text
save(todos)
print(f"Note set on: {node['text']}")
def cmd_remove(args):
todos = load()
path = args[0]
node, parent_list, idx = find_by_path(todos, path)
removed = parent_list.pop(idx)
save(todos)
print(f"Removed: {removed['text']}")
def cmd_edit(args):
todos = load()
path = args[0]
new_text = " ".join(args[1:])
node, _, _ = find_by_path(todos, path)
node["text"] = new_text
save(todos)
print(f"Edited: {new_text}")
def cmd_due(args):
todos = load()
path = args[0]
node, _, _ = find_by_path(todos, path)
if len(args) < 2 or args[1] == "clear":
node.pop("due", None)
save(todos)
print(f"Due date cleared on: {node['text']}")
else:
node["due"] = args[1]
save(todos)
print(f"Due date set on: {node['text']} → {args[1]}")
def cmd_today(args):
todos = load()
path = args[0]
node, _, _ = find_by_path(todos, path)
if len(args) > 1 and args[1] == "--off":
node.pop("today", None)
save(todos)
print(f"Today flag cleared on: {node['text']}")
return
if node.get("today"):
node.pop("today", None)
save(todos)
print(f"Today flag cleared on: {node['text']}")
else:
node["today"] = True
save(todos)
print(f"Today flag set on: {node['text']}")
def cmd_list(args):
todos = load()
if not todos:
print("No todos.")
return
print_todos(todos)
def cmd_completed(args):
completed = load_completed()
if not completed:
print("No completed todos.")
return
print("=== Completed ===")
print_todos(completed)
def cmd_clear(args):
save([])
print("Cleared all todos.")
COMMANDS = {
"add": cmd_add,
"complete": cmd_complete,
"done": cmd_complete,
"uncomplete": cmd_uncomplete,
"note": cmd_note,
"remove": cmd_remove,
"rm": cmd_remove,
"edit": cmd_edit,
"due": cmd_due,
"today": cmd_today,
"list": cmd_list,
"ls": cmd_list,
"completed": cmd_completed,
"clear": cmd_clear,
}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
print("Usage: python3 cli.py <command> [args]")
print(f"Commands: {', '.join(COMMANDS.keys())}")
sys.exit(1)
COMMANDS[sys.argv[1]](sys.argv[2:])