-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo
More file actions
executable file
·875 lines (784 loc) · 31.8 KB
/
Copy pathtodo
File metadata and controls
executable file
·875 lines (784 loc) · 31.8 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
#!/usr/bin/env python3
"""
todo — a friendly terminal task manager
No dependencies beyond Python 3 stdlib.
"""
import json
import os
import shutil
import subprocess
import sys
import textwrap
import threading
import time
from datetime import datetime
from pathlib import Path
# ── Paths ────────────────────────────────────────────────────────────────────
DATA_DIR = Path.home() / ".todo"
DATA_FILE = DATA_DIR / "tasks.json"
CONFIG_FILE = DATA_DIR / "config.json"
# ── ANSI colours & styles ────────────────────────────────────────────────────
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
ITALIC = "\033[3m"
ULINE = "\033[4m"
STRIKE = "\033[9m"
REVERSE = "\033[7m"
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BG_BLACK = "\033[40m"
BG_RED = "\033[41m"
BG_GREEN = "\033[42m"
BG_YELLOW = "\033[43m"
BG_BLUE = "\033[44m"
BG_MAGENTA = "\033[45m"
BG_CYAN = "\033[46m"
BG_WHITE = "\033[47m"
BRIGHT_BLACK = "\033[90m"
BRIGHT_RED = "\033[91m"
BRIGHT_GREEN = "\033[92m"
BRIGHT_YELLOW = "\033[93m"
BRIGHT_BLUE = "\033[94m"
BRIGHT_MAGENTA = "\033[95m"
BRIGHT_CYAN = "\033[96m"
BRIGHT_WHITE = "\033[97m"
# ── Box-drawing pieces ───────────────────────────────────────────────────────
TL = "╭"; TR = "╮"; BL = "╰"; BR = "╯"
H = "─"; V = "│"
TL2 = "┌"; TR2 = "┐"; BL2 = "└"; BR2 = "┘"
H2 = "─"; V2 = "│"
T_DOWN = "┬"; T_UP = "┴"; T_RIGHT = "├"; T_LEFT = "┤"; CROSS = "┼"
# ── ASCII art ────────────────────────────────────────────────────────────────
ROBOT_SMALL = f"""{BRIGHT_GREEN} ┌─┤▪├─┐{RESET} {BOLD}{BRIGHT_WHITE}t o d o b o t{RESET}
{BRIGHT_GREEN} │ ◕ ◕ │{RESET} {DIM}your friendly task buddy{RESET}
{BRIGHT_GREEN} └─┤_├─┘{RESET}
"""
# ── Data layer ───────────────────────────────────────────────────────────────
def _load_all_tasks():
"""Load all tasks including soft-deleted ones (for sync)."""
if not DATA_FILE.exists():
return []
with open(DATA_FILE, "r") as f:
return json.load(f)
def _load_tasks():
"""Load tasks, filtering out soft-deleted ones."""
return [t for t in _load_all_tasks() if not t.get("deleted")]
def _save_tasks(tasks):
DATA_DIR.mkdir(parents=True, exist_ok=True)
with open(DATA_FILE, "w") as f:
json.dump(tasks, f, indent=2)
# Auto-push to gist if configured
_auto_push()
def _auto_push():
"""Silently push to gist if configured. Failures are ignored."""
config = _load_config()
if not config.get("gist_id"):
return
ok, _ = _gh_available()
if not ok:
return
try:
subprocess.run(
["gh", "gist", "edit", config["gist_id"], "-f", "tasks.json", str(DATA_FILE)],
capture_output=True, text=True, timeout=10,
)
except Exception:
pass
def _next_id(tasks):
all_tasks = _load_all_tasks()
if not all_tasks:
return 1
return max(t["id"] for t in all_tasks) + 1
# ── Config layer ─────────────────────────────────────────────────────────────
def _load_config():
if not CONFIG_FILE.exists():
return {}
with open(CONFIG_FILE, "r") as f:
return json.load(f)
def _save_config(config):
DATA_DIR.mkdir(parents=True, exist_ok=True)
with open(CONFIG_FILE, "w") as f:
json.dump(config, f, indent=2)
# ── Spinner ──────────────────────────────────────────────────────────────────
def _with_spinner(message, fn):
"""Run fn() in a thread while showing a spinner. Returns fn's result."""
frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
result = [None]
error = [None]
done = threading.Event()
def _worker():
try:
result[0] = fn()
except Exception as e:
error[0] = e
finally:
done.set()
t = threading.Thread(target=_worker, daemon=True)
t.start()
i = 0
while not done.is_set():
frame = frames[i % len(frames)]
sys.stdout.write(f"\r {BRIGHT_CYAN}{frame}{RESET} {message}")
sys.stdout.flush()
done.wait(timeout=0.08)
i += 1
sys.stdout.write(f"\r {' ' * (len(message) + 4)}\r")
sys.stdout.flush()
if error[0]:
raise error[0]
return result[0]
# ── Gist sync ────────────────────────────────────────────────────────────────
def _gh_available():
if not shutil.which("gh"):
return False, "gh CLI not found. Install it from https://cli.github.com"
try:
r = subprocess.run(
["gh", "auth", "status"],
capture_output=True, text=True, timeout=10,
)
if r.returncode != 0:
return False, "gh is not authenticated. Run: gh auth login"
except subprocess.TimeoutExpired:
return False, "gh auth check timed out"
return True, None
def _sync_push():
"""Push local tasks.json to the configured gist."""
config = _load_config()
gist_id = config.get("gist_id")
if not gist_id:
return False, "No gist configured. Run: todo sync"
ok, err = _gh_available()
if not ok:
return False, err
if not DATA_FILE.exists():
_save_tasks([])
def _do_push():
return subprocess.run(
["gh", "gist", "edit", gist_id, "-f", "tasks.json", str(DATA_FILE)],
capture_output=True, text=True, timeout=30,
)
try:
r = _with_spinner("Pushing to gist...", _do_push)
except subprocess.TimeoutExpired:
return False, "Push timed out"
if r.returncode != 0:
return False, f"Push failed: {r.stderr.strip()}"
return True, None
def _merge_tasks(local, remote):
"""Merge local and remote task lists by ID. Newest modified wins."""
def _ts(t):
s = t.get("modified", t.get("created", ""))
return s.replace("Z", "+00:00") if s else ""
local_by_id = {t["id"]: t for t in local}
remote_by_id = {t["id"]: t for t in remote}
all_ids = set(local_by_id.keys()) | set(remote_by_id.keys())
merged = []
for tid in sorted(all_ids):
lt = local_by_id.get(tid)
rt = remote_by_id.get(tid)
if lt and not rt:
merged.append(lt)
elif rt and not lt:
merged.append(rt)
else:
merged.append(lt if _ts(lt) >= _ts(rt) else rt)
return merged
def _sync_pull():
"""Pull tasks.json from the configured gist and merge with local."""
config = _load_config()
gist_id = config.get("gist_id")
if not gist_id:
return False, "No gist configured. Run: todo sync"
ok, err = _gh_available()
if not ok:
return False, err
def _do_pull():
return subprocess.run(
["gh", "gist", "view", gist_id, "-f", "tasks.json", "--raw"],
capture_output=True, text=True, timeout=30,
)
try:
r = _with_spinner("Pulling from gist...", _do_pull)
except subprocess.TimeoutExpired:
return False, "Pull timed out"
if r.returncode != 0:
return False, f"Pull failed: {r.stderr.strip()}"
try:
remote_tasks = json.loads(r.stdout)
except json.JSONDecodeError:
return False, "Remote data is not valid JSON"
local_tasks = _load_all_tasks()
merged = _merge_tasks(local_tasks, remote_tasks)
_save_tasks(merged)
return True, None
def _setup_gist():
"""Interactive setup: create a new gist or enter an existing gist ID."""
ok, err = _gh_available()
if not ok:
print(f"\n {BRIGHT_RED}✘{RESET} {err}\n")
return False
print(f"\n {BOLD}{BRIGHT_WHITE}Gist sync setup{RESET}\n")
print(f" {BRIGHT_CYAN}[{BRIGHT_WHITE}c{BRIGHT_CYAN}]{RESET} Create a new private gist")
print(f" {BRIGHT_CYAN}[{BRIGHT_WHITE}e{BRIGHT_CYAN}]{RESET} Enter an existing gist ID")
print()
choice = _input_prompt("Choose: ")
if not choice:
return False
choice = choice.strip().lower()
if choice == "c":
if not DATA_FILE.exists():
_save_tasks([])
def _do_create():
return subprocess.run(
["gh", "gist", "create", "--private", "-f", "tasks.json", str(DATA_FILE)],
capture_output=True, text=True, timeout=30,
)
try:
r = _with_spinner("Creating private gist...", _do_create)
except subprocess.TimeoutExpired:
print(f"\n {BRIGHT_RED}✘{RESET} Timed out creating gist.\n")
return False
if r.returncode != 0:
print(f"\n {BRIGHT_RED}✘{RESET} Failed: {r.stderr.strip()}\n")
return False
gist_url = r.stdout.strip()
gist_id = gist_url.rstrip("/").split("/")[-1]
config = _load_config()
config["gist_id"] = gist_id
_save_config(config)
print(f" {BRIGHT_GREEN}✔{RESET} Gist created: {DIM}{gist_id}{RESET}\n")
return True
elif choice == "e":
gist_id = _input_prompt("Gist ID (or URL): ")
if not gist_id or not gist_id.strip():
print(f"\n {DIM}Cancelled.{RESET}\n")
return False
gist_id = gist_id.strip().rstrip("/").split("/")[-1]
config = _load_config()
config["gist_id"] = gist_id
_save_config(config)
print(f" {BRIGHT_GREEN}✔{RESET} Gist configured: {DIM}{gist_id}{RESET}\n")
return True
else:
print(f"\n {DIM}Cancelled.{RESET}\n")
return False
def cmd_sync(sub=None):
"""Handle todo sync [pull|status]."""
config = _load_config()
gist_id = config.get("gist_id")
if sub == "status":
if gist_id:
print(f"\n {BRIGHT_GREEN}✔{RESET} Gist configured: {DIM}{gist_id}{RESET}\n")
else:
print(f"\n {DIM}No gist configured. Run: {BRIGHT_CYAN}todo sync{RESET}\n")
return
if sub == "pull":
if not gist_id:
print(f"\n {BRIGHT_RED}✘{RESET} No gist configured. Run: {BRIGHT_CYAN}todo sync{RESET}\n")
return
ok, err = _sync_pull()
if ok:
print(f" {BRIGHT_GREEN}✔{RESET} Pulled from gist\n")
else:
print(f" {BRIGHT_RED}✘{RESET} {err}\n")
return
# Default: pull (merge) then push (or setup if no gist)
if not gist_id:
if not _setup_gist():
return
config = _load_config()
gist_id = config.get("gist_id")
if not gist_id:
return
# Pull first to merge remote changes
pull_ok, pull_err = _sync_pull()
if not pull_ok:
print(f" {BRIGHT_YELLOW}⚠{RESET} Pull failed: {DIM}{pull_err}{RESET}")
ok, err = _sync_push()
if ok:
print(f" {BRIGHT_GREEN}✔{RESET} Synced with gist\n")
else:
print(f" {BRIGHT_RED}✘{RESET} {err}\n")
# ── Helpers ──────────────────────────────────────────────────────────────────
def _term_width():
try:
return os.get_terminal_size().columns
except OSError:
return 80
def _relative_date(iso_str):
try:
created = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
now = datetime.now(created.tzinfo)
except (ValueError, TypeError):
return "?"
delta = now - created
if delta.days == 0:
hours = delta.seconds // 3600
if hours == 0:
mins = delta.seconds // 60
return "just now" if mins < 2 else f"{mins}m ago"
return f"{hours}h ago" if hours == 1 else f"{hours}h ago"
if delta.days == 1:
return "yesterday"
if delta.days < 7:
return f"{delta.days}d ago"
if delta.days < 30:
weeks = delta.days // 7
return f"{weeks}w ago"
return created.strftime("%b %d")
def _wrap_text(text, width):
"""Wrap text to width, returning list of lines."""
if len(text) <= width:
return [text]
return textwrap.wrap(text, width=width)
def _highlight_tags(text, style_before):
"""Replace #tags in text with reverse-video highlighted versions."""
import re
def _repl(m):
return f"{REVERSE}{BRIGHT_CYAN}{m.group()}{RESET}{style_before}"
return re.sub(r"#\w+", _repl, text)
# ── Table rendering ──────────────────────────────────────────────────────────
def _print_table(tasks, show_done=True, status_msg=None, tag_filter=None):
if not tasks:
print(f"\n {BRIGHT_GREEN} ┌─┤▪├─┐{RESET}")
print(f" {BRIGHT_GREEN} │ ◕ ◕ │{RESET} {DIM}No tasks yet! Add one with:{RESET} {BRIGHT_CYAN}todo add \"your task\"{RESET}")
print(f" {BRIGHT_GREEN} └─┤_├─┘{RESET}\n")
return
filtered = tasks if show_done else [t for t in tasks if not t["done"]]
if tag_filter:
tag = f"#{tag_filter.lstrip('#')}".lower()
filtered = [t for t in filtered if tag in t["text"].lower()]
if not filtered:
if tag_filter:
print(f"\n {DIM}No tasks matching {RESET}#{tag_filter.lstrip('#')}{DIM}.{RESET}\n")
else:
print(f"\n {BRIGHT_GREEN}✨ All done! Nothing to do.{RESET}\n")
return
# Pending first, completed at the bottom
filtered.sort(key=lambda t: (t["done"], t["id"]))
tw = min(_term_width(), 120)
id_w = 4
status_w = 4
date_w = 11
# task text gets the rest, minus borders and padding
task_w = tw - id_w - status_w - date_w - 17
task_w = max(task_w, 20)
# Build all output lines first, then pair with robot
table_lines = []
# Header
table_lines.append(
f"{BRIGHT_CYAN}{TL}{H * (id_w + 2)}{T_DOWN}"
f"{H * (status_w + 2)}{T_DOWN}"
f"{H * (task_w + 2)}{T_DOWN}"
f"{H * (date_w + 2)}{TR}{RESET}"
)
table_lines.append(
f"{BRIGHT_CYAN}{V}{RESET} {BOLD}{BRIGHT_WHITE}{'ID':^{id_w}}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET} {BOLD}{BRIGHT_WHITE}{'':^{status_w}}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET} {BOLD}{BRIGHT_WHITE}{'TASK':<{task_w}}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET} {BOLD}{BRIGHT_WHITE}{'ADDED':^{date_w}}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET}"
)
table_lines.append(
f"{BRIGHT_CYAN}{T_RIGHT}{H * (id_w + 2)}{CROSS}"
f"{H * (status_w + 2)}{CROSS}"
f"{H * (task_w + 2)}{CROSS}"
f"{H * (date_w + 2)}{T_LEFT}{RESET}"
)
for idx, t in enumerate(filtered):
tid = str(t["id"])
done = t["done"]
task_text = t["text"]
date_str = _relative_date(t["created"])
if idx > 0:
table_lines.append(
f"{BRIGHT_CYAN}{T_RIGHT}{BRIGHT_BLACK}{H * (id_w + 2)}{BRIGHT_CYAN}{CROSS}"
f"{BRIGHT_BLACK}{H * (status_w + 2)}{BRIGHT_CYAN}{CROSS}"
f"{BRIGHT_BLACK}{H * (task_w + 2)}{BRIGHT_CYAN}{CROSS}"
f"{BRIGHT_BLACK}{H * (date_w + 2)}{BRIGHT_CYAN}{T_LEFT}{RESET}"
)
if done:
status_icon = f"{BRIGHT_GREEN}✔{RESET}"
text_style = f"{DIM}{STRIKE}"
id_style = f"{DIM}"
date_style = f"{DIM}"
else:
status_icon = f"{BRIGHT_YELLOW}○{RESET}"
text_style = f"{BRIGHT_WHITE}"
id_style = f"{BRIGHT_MAGENTA}"
date_style = f"{BRIGHT_BLACK}"
lines = _wrap_text(task_text, task_w)
first = f"{lines[0]:<{task_w}}"
first_hl = _highlight_tags(first, text_style)
table_lines.append(
f"{BRIGHT_CYAN}{V}{RESET} {id_style}{tid:>{id_w}}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET} {status_icon} "
f"{BRIGHT_CYAN}{V}{RESET} {text_style}{first_hl}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET} {date_style}{date_str:^{date_w}}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET}"
)
for extra_line in lines[1:]:
padded = f"{extra_line:<{task_w}}"
padded_hl = _highlight_tags(padded, text_style)
table_lines.append(
f"{BRIGHT_CYAN}{V}{RESET} {'':>{id_w}} "
f"{BRIGHT_CYAN}{V}{RESET} {'':^{status_w}} "
f"{BRIGHT_CYAN}{V}{RESET} {text_style}{padded_hl}{RESET} "
f"{BRIGHT_CYAN}{V}{RESET} {'':^{date_w}} "
f"{BRIGHT_CYAN}{V}{RESET}"
)
table_lines.append(
f"{BRIGHT_CYAN}{BL}{H * (id_w + 2)}{T_UP}"
f"{H * (status_w + 2)}{T_UP}"
f"{H * (task_w + 2)}{T_UP}"
f"{H * (date_w + 2)}{BR}{RESET}"
)
# Progress bar
total = len(tasks)
done_count = sum(1 for t in tasks if t["done"])
pending = total - done_count
bar_w = 20
filled = int((done_count / total) * bar_w) if total else 0
bar = f"{BRIGHT_GREEN}{'█' * filled}{RESET}{DIM}{'░' * (bar_w - filled)}{RESET}"
table_lines.append(f" {BRIGHT_GREEN}┌─┤▪├─┐{RESET}")
eyes_extra = f" {status_msg.strip()}" if status_msg else ""
filter_info = f" • {BRIGHT_CYAN}#{tag_filter.lstrip('#')}{RESET}" if tag_filter else ""
table_lines.append(f" {BRIGHT_GREEN}│ ◕ ◕ │{RESET} {bar} {done_count}/{total} done • {pending} pending{filter_info}{eyes_extra}")
table_lines.append(f" {BRIGHT_GREEN}└─┤_├─┘{RESET} {DIM}add \"task\" • done <id> • rm <id>{RESET}")
print()
for tline in table_lines:
print(f" {tline}")
# ── Commands ─────────────────────────────────────────────────────────────────
def cmd_add(text):
tasks = _load_all_tasks()
new_id = _next_id(tasks)
now = datetime.now().isoformat()
task = {
"id": new_id,
"text": text,
"done": False,
"created": now,
"modified": now,
}
tasks.append(task)
_save_tasks(tasks)
print(f"\n {BRIGHT_GREEN}✔{RESET} Added task {BRIGHT_MAGENTA}#{new_id}{RESET}: {BRIGHT_WHITE}{text}{RESET}\n")
def cmd_list():
config = _load_config()
if config.get("gist_id"):
ok, _ = _gh_available()
if ok:
pull_ok, _ = _sync_pull()
tasks = _load_tasks()
_print_table(tasks)
def cmd_done(task_id):
tasks = _load_all_tasks()
for t in tasks:
if t.get("deleted"):
continue
if t["id"] == task_id:
if t["done"]:
print(f"\n {BRIGHT_YELLOW}⚠{RESET} Task {BRIGHT_MAGENTA}#{task_id}{RESET} is already done.\n")
return
t["done"] = True
t["modified"] = datetime.now().isoformat()
_save_tasks(tasks)
print(f"\n {BRIGHT_GREEN}✔{RESET} Nice! Completed {BRIGHT_MAGENTA}#{task_id}{RESET}: {DIM}{STRIKE}{t['text']}{RESET}\n")
return
print(f"\n {BRIGHT_RED}✘{RESET} Task {BRIGHT_MAGENTA}#{task_id}{RESET} not found.\n")
def cmd_remove(task_id):
tasks = _load_all_tasks()
for t in tasks:
if t.get("deleted"):
continue
if t["id"] == task_id:
t["deleted"] = True
t["modified"] = datetime.now().isoformat()
_save_tasks(tasks)
print(f"\n {BRIGHT_RED}🗑{RESET} Removed {BRIGHT_MAGENTA}#{task_id}{RESET}: {DIM}{t['text']}{RESET}\n")
return
print(f"\n {BRIGHT_RED}✘{RESET} Task {BRIGHT_MAGENTA}#{task_id}{RESET} not found.\n")
def cmd_help():
print()
print(f" {BOLD}{BRIGHT_WHITE}USAGE{RESET} {BRIGHT_CYAN}todo{RESET} {DIM}[command]{RESET}")
print(f" {BRIGHT_CYAN}add{RESET} {DIM}\"text\"{RESET} {BRIGHT_CYAN}ls{RESET} {BRIGHT_CYAN}done{RESET} {DIM}<id>{RESET} {BRIGHT_CYAN}rm{RESET} {DIM}<id>{RESET} {BRIGHT_CYAN}help{RESET}")
print(f" {BRIGHT_CYAN}sync{RESET} {DIM}[pull|status]{RESET} {DIM}(no args = interactive){RESET}")
print()
# ── Interactive wizard ───────────────────────────────────────────────────────
def _clear():
os.system("clear" if os.name != "nt" else "cls")
def _input_prompt(prompt_text):
try:
return input(f" {BRIGHT_CYAN}▸{RESET} {prompt_text}")
except (EOFError, KeyboardInterrupt):
print()
return None
def _select_action():
print()
print(f" {BOLD}{BRIGHT_WHITE}What would you like to do?{RESET} {DIM}(tip: {RESET}d 3{DIM} or {RESET}r 5{DIM} to skip ID prompt){RESET}\n")
actions = [
("a", "Add", BRIGHT_GREEN),
("d", "Done", BRIGHT_YELLOW),
("r", "Remove", BRIGHT_RED),
("f", "Filter", BRIGHT_BLUE),
("s", "Sync", BRIGHT_MAGENTA),
("l", "List", BRIGHT_CYAN),
("q", "Quit", DIM),
]
line = " " + " ".join(
f"{BRIGHT_CYAN}[{BRIGHT_WHITE}{key}{BRIGHT_CYAN}]{RESET} {color}{label}{RESET}"
for key, label, color in actions
)
print(line)
print()
choice = _input_prompt("Choose: ")
if not choice:
return None, None
parts = choice.strip().lower().split(None, 1)
action = parts[0]
arg = parts[1] if len(parts) > 1 else None
return action, arg
def _select_task(tasks, prompt="Select task ID: ", filter_done=None):
filtered = tasks
if filter_done is not None:
filtered = [t for t in tasks if t["done"] == filter_done]
if not filtered:
if filter_done is False:
print(f"\n {BRIGHT_GREEN}✨ No pending tasks!{RESET}\n")
elif filter_done is True:
print(f"\n {DIM}No completed tasks.{RESET}\n")
else:
print(f"\n {DIM}No tasks.{RESET}\n")
return None
_print_table(filtered)
val = _input_prompt(prompt)
if val is None:
return None
try:
return int(val.strip())
except ValueError:
print(f"\n {BRIGHT_RED}✘{RESET} Please enter a valid task ID.\n")
return None
def _redraw(message=None, tag_filter=None):
"""Clear screen, show current tasks, and optional message."""
_clear()
tasks = _load_tasks()
if tasks:
_print_table(tasks, status_msg=message, tag_filter=tag_filter)
else:
print(f" {DIM}No tasks yet. Let's add one!{RESET}\n")
if message:
print(message)
def interactive():
config = _load_config()
gist_id = config.get("gist_id")
active_filter = None
# Auto-pull on open
if gist_id:
ok, err = _gh_available()
if ok:
pull_ok, pull_err = _sync_pull()
if not pull_ok:
_redraw(f" {BRIGHT_YELLOW}⚠{RESET} Sync pull failed: {DIM}{pull_err}{RESET}\n")
else:
_redraw(f" {BRIGHT_GREEN}✔{RESET} Synced from gist\n")
else:
_redraw(f" {BRIGHT_YELLOW}⚠{RESET} {DIM}{err}{RESET}\n")
else:
_redraw()
while True:
action, arg = _select_action()
if action is None or action == "q":
# Auto-push on quit
config = _load_config()
if config.get("gist_id"):
ok, err = _gh_available()
if ok:
push_ok, push_err = _sync_push()
# Show result briefly before goodbye
if not push_ok:
print(f"\n {BRIGHT_YELLOW}⚠{RESET} Sync push failed: {DIM}{push_err}{RESET}")
_clear()
print(f"\n {BRIGHT_GREEN} ┌─┤▪├─┐{RESET}")
print(f" {BRIGHT_GREEN} │ ◕ ◕ │{RESET} {DIM}See you later!{RESET}")
print(f" {BRIGHT_GREEN} └─┤_├─┘{RESET}\n")
break
elif action == "a":
if arg is not None:
text = arg
else:
text = _input_prompt("What do you need to do? ")
if text and text.strip():
tasks = _load_all_tasks()
new_id = _next_id(tasks)
now = datetime.now().isoformat()
task = {
"id": new_id,
"text": text.strip(),
"done": False,
"created": now,
"modified": now,
}
tasks.append(task)
_save_tasks(tasks)
_redraw(f" {BRIGHT_GREEN}✔{RESET} Added task {BRIGHT_MAGENTA}#{new_id}{RESET}: {BRIGHT_WHITE}{text.strip()}{RESET}\n", tag_filter=active_filter)
else:
_redraw(tag_filter=active_filter)
elif action == "d":
tasks = _load_tasks()
pending = [t for t in tasks if not t["done"]]
if not pending:
_redraw(f" {BRIGHT_GREEN}✨ No pending tasks!{RESET}\n", tag_filter=active_filter)
continue
if arg is not None:
tid_str = arg
else:
_redraw(tag_filter=active_filter)
tid_str = _input_prompt("Which task did you finish? ID: ")
if tid_str is None:
_redraw(tag_filter=active_filter)
continue
try:
tid = int(tid_str.strip())
except ValueError:
_redraw(f" {BRIGHT_RED}✘{RESET} Please enter a valid task ID.\n", tag_filter=active_filter)
continue
tasks = _load_all_tasks()
found = False
for t in tasks:
if t.get("deleted"):
continue
if t["id"] == tid:
found = True
if t["done"]:
_redraw(f" {BRIGHT_YELLOW}⚠{RESET} Task {BRIGHT_MAGENTA}#{tid}{RESET} is already done.\n", tag_filter=active_filter)
else:
t["done"] = True
t["modified"] = datetime.now().isoformat()
_save_tasks(tasks)
_redraw(f" {BRIGHT_GREEN}✔{RESET} Nice! Completed {BRIGHT_MAGENTA}#{tid}{RESET}: {DIM}{STRIKE}{t['text']}{RESET}\n", tag_filter=active_filter)
break
if not found:
_redraw(f" {BRIGHT_RED}✘{RESET} Task {BRIGHT_MAGENTA}#{tid}{RESET} not found.\n", tag_filter=active_filter)
elif action == "r":
tasks = _load_tasks()
if not tasks:
_redraw(f" {DIM}No tasks to remove.{RESET}\n", tag_filter=active_filter)
continue
if arg is not None:
tid_str = arg
else:
_redraw(tag_filter=active_filter)
tid_str = _input_prompt("Which task to remove? ID: ")
if tid_str is None:
_redraw(tag_filter=active_filter)
continue
try:
tid = int(tid_str.strip())
except ValueError:
_redraw(f" {BRIGHT_RED}✘{RESET} Please enter a valid task ID.\n", tag_filter=active_filter)
continue
tasks = _load_all_tasks()
found = False
for t in tasks:
if t.get("deleted"):
continue
if t["id"] == tid:
found = True
t["deleted"] = True
t["modified"] = datetime.now().isoformat()
_save_tasks(tasks)
_redraw(f" {BRIGHT_RED}🗑{RESET} Removed {BRIGHT_MAGENTA}#{tid}{RESET}: {DIM}{t['text']}{RESET}\n", tag_filter=active_filter)
break
if not found:
_redraw(f" {BRIGHT_RED}✘{RESET} Task {BRIGHT_MAGENTA}#{tid}{RESET} not found.\n", tag_filter=active_filter)
elif action == "f":
if arg:
active_filter = arg.strip().lstrip("#")
_redraw(f" {BRIGHT_CYAN}▸{RESET} Filtering by {BRIGHT_CYAN}#{active_filter}{RESET}\n", tag_filter=active_filter)
else:
active_filter = None
_redraw(f" {DIM}Filter cleared{RESET}\n")
elif action == "s":
config = _load_config()
if not config.get("gist_id"):
_setup_gist()
_redraw(tag_filter=active_filter)
else:
push_ok, push_err = _sync_push()
if push_ok:
_redraw(f" {BRIGHT_GREEN}✔{RESET} Synced to gist\n", tag_filter=active_filter)
else:
_redraw(f" {BRIGHT_RED}✘{RESET} {push_err}\n", tag_filter=active_filter)
elif action == "l":
config = _load_config()
if config.get("gist_id"):
ok, _ = _gh_available()
if ok:
pull_ok, pull_err = _sync_pull()
if pull_ok:
_redraw(f" {BRIGHT_GREEN}✔{RESET} Synced from gist\n", tag_filter=active_filter)
else:
_redraw(f" {BRIGHT_YELLOW}⚠{RESET} Pull failed: {DIM}{pull_err}{RESET}\n", tag_filter=active_filter)
else:
_redraw(tag_filter=active_filter)
else:
_redraw(tag_filter=active_filter)
else:
_redraw(f" {DIM}Unknown option. Try again.{RESET}\n", tag_filter=active_filter)
# ── Entry point ──────────────────────────────────────────────────────────────
def main():
args = sys.argv[1:]
if not args:
interactive()
return
cmd = args[0].lower()
if cmd == "add":
if len(args) < 2:
print(f"\n {BRIGHT_RED}✘{RESET} Usage: {BRIGHT_CYAN}todo add \"task text\"{RESET}\n")
sys.exit(1)
text = " ".join(args[1:])
cmd_add(text)
elif cmd in ("ls", "list"):
cmd_list()
elif cmd == "done":
if len(args) < 2:
print(f"\n {BRIGHT_RED}✘{RESET} Usage: {BRIGHT_CYAN}todo done <id>{RESET}\n")
sys.exit(1)
try:
tid = int(args[1])
except ValueError:
print(f"\n {BRIGHT_RED}✘{RESET} ID must be a number.\n")
sys.exit(1)
cmd_done(tid)
elif cmd in ("rm", "remove", "del", "delete"):
if len(args) < 2:
print(f"\n {BRIGHT_RED}✘{RESET} Usage: {BRIGHT_CYAN}todo rm <id>{RESET}\n")
sys.exit(1)
try:
tid = int(args[1])
except ValueError:
print(f"\n {BRIGHT_RED}✘{RESET} ID must be a number.\n")
sys.exit(1)
cmd_remove(tid)
elif cmd == "sync":
sub = args[1].lower() if len(args) > 1 else None
if sub and sub not in ("pull", "status"):
print(f"\n {BRIGHT_RED}✘{RESET} Usage: {BRIGHT_CYAN}todo sync [pull|status]{RESET}\n")
sys.exit(1)
cmd_sync(sub)
elif cmd in ("help", "-h", "--help"):
cmd_help()
else:
print(f"\n {BRIGHT_RED}✘{RESET} Unknown command: {BRIGHT_WHITE}{cmd}{RESET}")
cmd_help()
sys.exit(1)
if __name__ == "__main__":
main()