-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtasks
More file actions
executable file
·611 lines (536 loc) · 21.3 KB
/
Copy pathtasks
File metadata and controls
executable file
·611 lines (536 loc) · 21.3 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
#!/usr/bin/env python3
"""TaskManager CLI entrypoint.
Parses arguments, runs confirmations/prompts, and prints via render.py. The
data model (tasks.py) stays free of terminal I/O. Every legacy single-dash
flag is preserved: translate_legacy() rewrites old-style argv into the new
subcommand form before argparse ever sees it.
"""
import argparse
import sys
import render
from devlogger import devlog, read_today
from tasks import (TaskManager, resolve_mode,
SHORTTERM, LONGTERM, WAIT, BACKLOG,
FIRST, LAST, UP, DOWN)
DESCRIPTION = """\
A tiny task manager. Tasks live in four categories -- short-term, long-term,
wait/watch and backlog -- inside a named list (a file like Today.txt).
"""
EXAMPLES = """\
examples:
tasks show the active list
tasks add "buy milk" add a task (omit text to be prompted)
tasks -L backlog add "..." add to the backlog category
tasks done 2 finish task 2 (logged to your devlog)
tasks done --today show what you finished today
tasks rm 1 delete task 1
tasks mv 0 bottom reorder task 0 (up|down|top|bottom)
tasks type 0 wait move task 0 to another category
tasks edit 0 "new title" rename task 0 (omit text to be prompted)
tasks status 0 "PR open" set task 0's status (omit text to clear)
tasks note 0 "ping Bob" add a note to task 0
tasks i interactive mode (browse, edit, annotate)
tasks all show every category
tasks lists list available lists
tasks lists use Errands switch the active list
categories (-L): short | long | wait | backlog
global flags go before the verb, e.g. tasks -y done 2 tasks --dry-run rm 0
"""
# --- legacy flag compatibility ------------------------------------------
LEGACY_FLAGS = {
'-lt', '--longterm', '-w', '--wait', '-bl', '--backlog',
'-a', '--append', '-p', '--prepend', '-A', '--all',
'-d', '--delete', '-ct', '--changetype',
'-mu', '--moveup', '-md', '--movedown', '-m1', '--promote', '-ml', '--demote',
'-cd', '--change-list', '-rm', '--delete-list',
'-ls', '--list-lists', '-mv', '--rename-list', '-f', '--finish',
}
def _legacy_parser():
p = argparse.ArgumentParser(add_help=False)
p.add_argument('-lt', '--longterm', dest='lt', action='store_true')
p.add_argument('-w', '--wait', dest='w', action='store_true')
p.add_argument('-bl', '--backlog', dest='bl', action='store_true')
p.add_argument('-a', '--append', dest='a', action='store_true')
p.add_argument('-A', '--all', dest='A', action='store_true')
p.add_argument('-p', '--prepend', dest='p', action='store_true')
p.add_argument('-d', '--delete', dest='d', type=int)
p.add_argument('-ct', '--changetype', dest='ct', type=int)
p.add_argument('-mu', '--moveup', dest='mu', type=int)
p.add_argument('-md', '--movedown', dest='md', type=int)
p.add_argument('-m1', '--promote', dest='m1', type=int)
p.add_argument('-ml', '--demote', dest='ml', type=int)
p.add_argument('-cd', '--change-list', dest='cd')
p.add_argument('-rm', '--delete-list', dest='rm')
p.add_argument('-ls', '--list-lists', dest='ls', action='store_true')
p.add_argument('-mv', '--rename-list', dest='mv')
p.add_argument('-f', '--finish', dest='f', type=int)
return p
def translate_legacy(argv):
"""Rewrite old-style argv into the new subcommand form. If no legacy flag
is present, return argv unchanged. Never mixes the two syntaxes."""
if not any(a in LEGACY_FLAGS for a in argv):
return argv
a = _legacy_parser().parse_args(argv)
out = []
if a.lt:
out += ['-L', 'long']
elif a.w:
out += ['-L', 'wait']
elif a.bl:
out += ['-L', 'backlog']
# First action wins, mirroring the original if/elif dispatch order.
if a.ls:
out += ['lists']
elif a.A:
out += ['all']
elif a.rm is not None:
out += ['lists', 'delete', a.rm]
elif a.cd is not None:
out += ['lists', 'use', a.cd]
elif a.d is not None:
out += ['rm', str(a.d)]
elif a.f is not None:
out += ['done', str(a.f)]
elif a.ct is not None:
out += ['type', str(a.ct)]
elif a.mu is not None:
out += ['mv', str(a.mu), 'up']
elif a.md is not None:
out += ['mv', str(a.md), 'down']
elif a.m1 is not None:
out += ['mv', str(a.m1), 'top']
elif a.ml is not None:
out += ['mv', str(a.ml), 'bottom']
elif a.a:
out += ['add']
elif a.p:
out += ['add', '--prepend']
elif a.mv is not None:
out += ['lists', 'rename', a.mv]
return out
# --- argument parser -----------------------------------------------------
def build_parser():
p = argparse.ArgumentParser(
prog='tasks', description=DESCRIPTION, epilog=EXAMPLES,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('-L', '--list', dest='target', metavar='CATEGORY',
help='category to act on: short|long|wait|backlog')
p.add_argument('-y', '--yes', action='store_true',
help='skip confirmation prompts')
p.add_argument('--dry-run', dest='dry_run', action='store_true',
help='show what would happen; write nothing')
p.add_argument('--no-color', dest='no_color', action='store_true',
help='disable colored output')
sub = p.add_subparsers(dest='cmd')
add = sub.add_parser('add', help='add a task (prompts if no text given)')
add.add_argument('text', nargs='*', help='task text')
add.add_argument('-p', '--prepend', action='store_true',
help='add to the top instead of the end')
done = sub.add_parser('done', help='finish a task (logs to your devlog)')
done.add_argument('index', nargs='?', type=int, help='task index')
done.add_argument('--today', action='store_true',
help='show tasks finished today instead')
rm = sub.add_parser('rm', help='delete a task')
rm.add_argument('index', type=int, help='task index')
mv = sub.add_parser('mv', help='reorder a task')
mv.add_argument('index', type=int, help='task index')
mv.add_argument('where', choices=['up', 'down', 'top', 'bottom'])
typ = sub.add_parser('type', help='move a task to another category')
typ.add_argument('index', type=int, help='task index')
typ.add_argument('to', nargs='?',
help='target category (prompts if omitted)')
edit = sub.add_parser('edit', help='edit a task title (prompts if no text)')
edit.add_argument('index', type=int, help='task index')
edit.add_argument('text', nargs='*', help='new title')
stt = sub.add_parser('status', help="set a task's status (blank clears it)")
stt.add_argument('index', type=int, help='task index')
stt.add_argument('text', nargs='*', help='status text')
note = sub.add_parser('note', help='add a note to a task')
note.add_argument('index', type=int, help='task index')
note.add_argument('text', nargs='*', help='note text')
sub.add_parser('i', aliases=['interactive'],
help='interactive mode (browse, edit, status, notes)')
sub.add_parser('all', help='show every category')
lists = sub.add_parser('lists', help='show or manage lists')
lsub = lists.add_subparsers(dest='listcmd')
use = lsub.add_parser('use', help='switch the active list')
use.add_argument('name')
ren = lsub.add_parser('rename', help='rename the active list')
ren.add_argument('name')
dele = lsub.add_parser('delete', help='delete a list')
dele.add_argument('name')
return p
# --- helpers -------------------------------------------------------------
def _show(tm, show_all=False):
print(render.render_list(tm.lists, tm.active_list, tm.mode, show_all=show_all))
def _confirm(prompt, yes):
if yes:
return True
try:
return input('%s (y/N): ' % prompt).strip().lower() == 'y'
except EOFError:
return False
def _ask(prompt):
"""Prompt for a line of input; return '' on EOF (piped/closed stdin)."""
try:
return input(prompt).strip()
except EOFError:
return ''
def _peek(tm, index, mode):
"""Return (task, None) or (None, error_message)."""
try:
return tm.peek_task(index, mode=mode), None
except IndexError:
return None, render.warn('no task %d in %s' % (index, mode))
# --- command handlers ----------------------------------------------------
def cmd_add(tm, args, mode, dry):
text = ' '.join(args.text).strip() if args.text else ''
if not text:
try:
text = input('task: ').strip()
except EOFError:
text = ''
if not text:
print(render.warn('nothing added'))
return 1
if args.prepend:
tm.prepend_task(text, mode=mode, dry_run=dry)
verb = 'Would add (top)' if dry else 'Added (top)'
else:
tm.append_task(text, mode=mode, dry_run=dry)
verb = 'Would add' if dry else 'Added'
print(render.success('%s "%s" to %s' % (verb, text, mode)))
print()
_show(tm)
return 0
def cmd_done(tm, args, mode, dry, yes):
if args.today:
prefix = 'Finished task: '
finished = [e[len(prefix):] for e in read_today() if e.startswith(prefix)]
print(render.render_today(finished))
return 0
if args.index is None:
print(render.warn('usage: tasks done <index> (or: tasks done --today)'))
return 1
task, err = _peek(tm, args.index, mode)
if err:
print(err)
return 1
if not _confirm('Finish "%s"' % task, yes):
print(render.info('cancelled'))
return 0
tm.finish_task(args.index, mode=mode, dry_run=dry)
if dry:
print(render.success('Would finish "%s"' % task))
else:
devlog('Finished task: %s' % task)
print(render.success('Finished "%s" (logged)' % task))
print()
_show(tm)
return 0
def cmd_rm(tm, args, mode, dry, yes):
task, err = _peek(tm, args.index, mode)
if err:
print(err)
return 1
if not _confirm('Delete "%s"' % task, yes):
print(render.info('cancelled'))
return 0
tm.delete_task(args.index, mode=mode, dry_run=dry)
print(render.success('%s "%s"' % ('Would delete' if dry else 'Deleted', task)))
print()
_show(tm)
return 0
_WHERE = {'up': ('direction', UP), 'down': ('direction', DOWN),
'top': ('new_slot', FIRST), 'bottom': ('new_slot', LAST)}
def cmd_mv(tm, args, mode, dry):
task, err = _peek(tm, args.index, mode)
if err:
print(err)
return 1
kind, value = _WHERE[args.where]
tm.move_task(args.index, mode=mode, dry_run=dry, **{kind: value})
print(render.success('%s "%s" %s' % ('Would move' if dry else 'Moved',
task, args.where)))
print()
_show(tm)
return 0
def cmd_type(tm, args, mode, dry):
task, err = _peek(tm, args.index, mode)
if err:
print(err)
return 1
if args.to is None:
# Menu order preserved from the original tool for muscle memory.
menu = [SHORTTERM, WAIT, LONGTERM, BACKLOG]
print('Change type of "%s":' % task)
for i, m in enumerate(menu):
print(' %d: %s' % (i + 1, m))
try:
resp = input('new type (1-4, blank to cancel): ').strip()
except EOFError:
resp = ''
if not resp.isdigit() or int(resp) not in (1, 2, 3, 4):
print(render.info('cancelled'))
return 0
new_type = menu[int(resp) - 1]
else:
try:
new_type = resolve_mode(args.to)
except ValueError as e:
print(render.warn(str(e)))
return 1
if new_type == mode:
print(render.info('already in %s' % mode))
return 0
tm.change_type(args.index, new_type, mode=mode, dry_run=dry)
print(render.success('%s "%s" to %s' % ('Would move' if dry else 'Moved',
task, new_type)))
print()
_show(tm)
return 0
def cmd_edit(tm, args, mode, dry):
task, err = _peek(tm, args.index, mode)
if err:
print(err)
return 1
title = ' '.join(args.text).strip() if args.text else \
_ask('new title [%s]: ' % task.title)
if not title:
print(render.info('cancelled'))
return 0
tm.set_title(args.index, title, mode=mode, dry_run=dry)
print(render.success('%s title -> "%s"' %
('Would set' if dry else 'Set', title)))
print()
_show(tm)
return 0
def cmd_status(tm, args, mode, dry):
task, err = _peek(tm, args.index, mode)
if err:
print(err)
return 1
status = ' '.join(args.text).strip() if args.text else \
_ask('status [%s] (blank to clear): ' % (task.status or ''))
tm.set_status(args.index, status, mode=mode, dry_run=dry)
if status:
print(render.success('%s status of "%s" to "%s"' %
('Would set' if dry else 'Set', task.title, status)))
else:
print(render.success('%s status of "%s"' %
('Would clear' if dry else 'Cleared', task.title)))
print()
_show(tm)
return 0
def cmd_note(tm, args, mode, dry):
task, err = _peek(tm, args.index, mode)
if err:
print(err)
return 1
note = ' '.join(args.text).strip() if args.text else _ask('note: ')
if not note:
print(render.warn('nothing added'))
return 0
tm.add_note(args.index, note, mode=mode, dry_run=dry)
print(render.success('%s note to "%s"' %
('Would add' if dry else 'Added', task.title)))
print()
_show(tm)
return 0
# --- interactive mode ----------------------------------------------------
_INTERACTIVE_HELP = """\
commands:
<number> focus a task (edit title, status, notes, ...)
a add a task to the current category
short | long | wait | backlog switch the active category
? this help
q quit"""
_TASK_HELP = ('(e)dit title (s)tatus (n)ote remove-(N)ote '
'(t)ype (m)ove (d)one (x)delete (b)ack')
def _interactive_task(tm, index):
"""Focused menu for a single task; returns when the user backs out or the
task leaves the current category (finished, deleted, moved, retyped)."""
mode = tm.mode
while True:
try:
task = tm.peek_task(index, mode=mode)
except IndexError:
print(render.warn('no task %d in %s' % (index, mode)))
return
print()
print(render.breadcrumb(tm.active_list, mode, index))
print(render.render_task_detail(task, index, mode))
print(render.info(_TASK_HELP))
choice = _ask('task %d > ' % index)
if choice in ('', 'b', 'q', 'back'):
return
elif choice == 'e':
title = _ask('new title [%s]: ' % task.title)
if title:
tm.set_title(index, title, mode=mode)
print(render.success('title updated'))
elif choice == 's':
status = _ask('status [%s] (blank to clear): ' % (task.status or ''))
tm.set_status(index, status, mode=mode)
print(render.success('status updated'))
elif choice == 'n':
note = _ask('note: ')
if note:
tm.add_note(index, note, mode=mode)
print(render.success('note added'))
elif choice == 'N':
if not task.notes:
print(render.info('no notes to remove'))
continue
which = _ask('remove note # (blank to cancel): ')
if which.isdigit() and int(which) < len(task.notes):
tm.remove_note(index, int(which), mode=mode)
print(render.success('note removed'))
else:
print(render.info('cancelled'))
elif choice == 't':
menu = [SHORTTERM, WAIT, LONGTERM, BACKLOG]
for i, m in enumerate(menu):
print(' %d: %s' % (i + 1, m))
resp = _ask('new type (1-4, blank to cancel): ')
if resp.isdigit() and int(resp) in (1, 2, 3, 4):
new_type = menu[int(resp) - 1]
if new_type != mode:
tm.change_type(index, new_type, mode=mode)
print(render.success('moved to %s' % new_type))
return
print(render.info('already in %s' % mode))
elif choice == 'm':
where = _ask('move (up/down/top/bottom): ').lower()
if where in _WHERE:
kind, value = _WHERE[where]
tm.move_task(index, mode=mode, **{kind: value})
print(render.success('moved %s' % where))
return # index may have shifted
print(render.info('cancelled'))
elif choice == 'd':
if _confirm('Finish "%s"' % task.title, False):
finished = tm.finish_task(index, mode=mode)
devlog('Finished task: %s' % finished.title)
print(render.success('finished (logged)'))
return
elif choice == 'x':
if _confirm('Delete "%s"' % task.title, False):
tm.delete_task(index, mode=mode)
print(render.success('deleted'))
return
else:
print(render.warn('unknown: %s (type b to go back)' % choice))
def cmd_interactive(tm):
print(render.info('interactive mode -- type ? for help, q to quit'))
while True:
print()
print(render.render_category(tm.lists, tm.active_list, tm.mode))
choice = _ask('\n%s > ' % tm.mode)
if choice in ('q', 'quit', 'exit'):
break
if choice == '':
continue
if choice in ('?', 'h', 'help'):
print(_INTERACTIVE_HELP)
continue
if choice in ('a', 'add'):
text = _ask('task: ')
if text:
tm.append_task(text, mode=tm.mode)
print(render.success('added "%s"' % text))
continue
if choice.lstrip('-').isdigit():
_interactive_task(tm, int(choice))
continue
try:
target = resolve_mode(choice)
except ValueError:
target = None
if target:
tm.set_mode(target)
continue
print(render.warn('unknown command: %s (type ? for help)' % choice))
print(render.info('bye'))
return 0
def cmd_lists(tm, args, dry, yes):
sub = args.listcmd
if sub is None:
print(render.render_lists_index(tm.list_names, active=tm.active_list))
return 0
if sub == 'use':
name = tm.change_default(args.name, dry_run=dry)
print(render.success('%s list "%s"' %
('Would switch to' if dry else 'Switched to', name)))
if not dry:
print()
_show(tm)
return 0
if sub == 'rename':
old = tm.active_list
if tm.list_exists(args.name) and not _confirm(
'List "%s" exists; replace it?' % args.name, yes):
print(render.info('cancelled'))
return 0
tm.move_list(args.name, dry_run=dry)
print(render.success('%s "%s" -> "%s"' %
('Would rename' if dry else 'Renamed', old, args.name)))
return 0
if sub == 'delete':
if not _confirm('Delete list "%s"' % args.name, yes):
print(render.info('cancelled'))
return 0
tm.remove_list(args.name, dry_run=dry)
print(render.success('%s list "%s"' %
('Would delete' if dry else 'Deleted', args.name)))
return 0
# --- main ---------------------------------------------------------------
def main(argv):
argv = translate_legacy(argv)
parser = build_parser()
args = parser.parse_args(argv)
render.configure(no_color=args.no_color)
tm = TaskManager()
try:
target = resolve_mode(args.target)
except ValueError as e:
parser.error(str(e))
if target:
tm.set_mode(target)
mode = tm.mode
dry = args.dry_run
yes = args.yes
if args.cmd is None:
_show(tm)
return 0
if args.cmd in ('i', 'interactive'):
if dry:
print(render.warn('--dry-run is ignored in interactive mode'))
import tui
if tui.run(tm) is None:
return cmd_interactive(tm) # non-TTY / curses unavailable fallback
return 0
if args.cmd == 'all':
_show(tm, show_all=True)
return 0
if args.cmd == 'lists':
return cmd_lists(tm, args, dry, yes)
if args.cmd == 'add':
return cmd_add(tm, args, mode, dry)
if args.cmd == 'done':
return cmd_done(tm, args, mode, dry, yes)
if args.cmd == 'rm':
return cmd_rm(tm, args, mode, dry, yes)
if args.cmd == 'mv':
return cmd_mv(tm, args, mode, dry)
if args.cmd == 'type':
return cmd_type(tm, args, mode, dry)
if args.cmd == 'edit':
return cmd_edit(tm, args, mode, dry)
if args.cmd == 'status':
return cmd_status(tm, args, mode, dry)
if args.cmd == 'note':
return cmd_note(tm, args, mode, dry)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))