taskli-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
taskli/cli.py ADDED
@@ -0,0 +1,1073 @@
1
+ # PYTHON_ARGCOMPLETE_OK
2
+ """Command-line interface and argument routing."""
3
+
4
+ import argparse
5
+ import functools
6
+ import sys
7
+ from collections.abc import Callable
8
+ from enum import StrEnum
9
+ from typing import TYPE_CHECKING, Any, NamedTuple
10
+
11
+ import argcomplete
12
+
13
+ from .__version__ import __version__
14
+ from .env import resolve_storage_dir, scan_list_names
15
+ from .exceptions import TaskliError
16
+ from .models import registry
17
+ from .models.attributes import Color, Priority
18
+ from .models.paths import path_key
19
+ from .models.query import Criterion, Filter, due_to_criteria
20
+
21
+ if TYPE_CHECKING:
22
+ from .logic import CommandResult
23
+ from .models.config import Config
24
+ from .models.tasks import TaskliList
25
+
26
+
27
+ def _handle_errors(func: Callable[..., int]) -> Callable[..., int]:
28
+ @functools.wraps(func)
29
+ def wrapper(*args: object, **kwargs: object) -> int:
30
+ from . import render
31
+
32
+ try:
33
+ return func(*args, **kwargs)
34
+ except TaskliError as e:
35
+ render.render_error(str(e))
36
+
37
+ return 1
38
+
39
+ return wrapper
40
+
41
+
42
+ def _confirm(prompt: str) -> bool:
43
+ answer = input(f"{prompt} [y/N]: ")
44
+
45
+ return answer.strip().lower() in {"y", "yes"}
46
+
47
+
48
+ def _print_list(task_list: "TaskliList", config: "Config") -> None:
49
+ from . import render
50
+
51
+ render.render_items(
52
+ task_list.display_name(config.sublist_delimiter),
53
+ task_list.items,
54
+ task_list.color,
55
+ )
56
+
57
+ return None
58
+
59
+
60
+ def _render_notices(result: "CommandResult") -> None:
61
+ """Render a result's messages, then its warnings."""
62
+
63
+ from . import render
64
+
65
+ for message in result.messages:
66
+ render.render_message(message)
67
+ for warning in result.warnings:
68
+ render.render_warning(warning)
69
+
70
+ return None
71
+
72
+
73
+ def _emit(result: "CommandResult", config: "Config") -> int:
74
+ """Render a command result: messages, warnings, then any list view."""
75
+
76
+ from . import render
77
+
78
+ _render_notices(result)
79
+
80
+ if result.item_view is not None:
81
+ _print_list(result.item_view, config)
82
+ if result.tree_view is not None:
83
+ render.render_list_tree(result.tree_view, config.sublist_delimiter)
84
+
85
+ return result.exit_code
86
+
87
+
88
+ class ListCommands(StrEnum):
89
+ VIEW = "view"
90
+ NEW = "new"
91
+ DELETE = "delete"
92
+ COLOR = "color"
93
+ LISTS = "lists"
94
+ PRUNE = "prune"
95
+ RENAME = "rename"
96
+ MIGRATE = "migrate"
97
+ AGENDA = "agenda"
98
+
99
+
100
+ class ConfigCommands(StrEnum):
101
+ CONFIG = "config"
102
+
103
+
104
+ class ItemActionCommands(StrEnum):
105
+ ADD = "add"
106
+ STATUS = "status"
107
+ EDIT = "edit"
108
+ MOVE = "move"
109
+ COPY = "copy"
110
+ DETAILS = "details"
111
+
112
+
113
+ type CommandOptions = ListCommands | ItemActionCommands | ConfigCommands
114
+
115
+
116
+ class ModifierArg(NamedTuple):
117
+ flags: tuple[str, ...]
118
+ dest: str
119
+ kwargs: dict[str, Any]
120
+ completer: Callable[..., list[str]] | None = None
121
+ filter_word: str | None = None
122
+
123
+
124
+ class ModifierSpec(NamedTuple):
125
+ args: tuple[ModifierArg, ...]
126
+ filter_dest: str | None = None
127
+ multi: bool = False
128
+ to_criteria: Callable[[str], tuple[Criterion, ...]] | None = None
129
+
130
+
131
+ def _complete_due_keywords(
132
+ prefix: str, parsed_args: argparse.Namespace, **kwargs: object
133
+ ) -> list[str]:
134
+ """argcomplete callback: keyword tokens accepted by --due."""
135
+
136
+ from .models.dates import DUE_DATE_KEYWORDS, WEEKDAY_INDEX
137
+
138
+ keywords = [*DUE_DATE_KEYWORDS, *WEEKDAY_INDEX]
139
+ if not (
140
+ getattr(parsed_args, "add", None) or getattr(parsed_args, "edit", None)
141
+ ):
142
+ keywords.extend(["overdue", "none"])
143
+
144
+ return keywords
145
+
146
+
147
+ MODIFIER_FLAGS: dict[str, ModifierSpec] = {
148
+ "priority": ModifierSpec(
149
+ args=(
150
+ ModifierArg(
151
+ flags=("-p", "--priority"),
152
+ dest="priority",
153
+ kwargs={
154
+ "choices": [p.name.lower() for p in Priority],
155
+ "nargs": "?",
156
+ "default": None,
157
+ "help": (
158
+ "Set or filter item's priority. Used to set"
159
+ " priority for -a/-e. Used to filter for viewing"
160
+ " items."
161
+ ),
162
+ },
163
+ ),
164
+ ),
165
+ filter_dest="priority",
166
+ ),
167
+ "tags": ModifierSpec(
168
+ args=(
169
+ ModifierArg(
170
+ flags=("--tag",),
171
+ dest="tag",
172
+ kwargs={
173
+ "action": "append",
174
+ "default": [],
175
+ "metavar": "TAG",
176
+ "help": (
177
+ "Set of filter item's tag. Used to add/replace"
178
+ " tags for -a/-e. Use to filter for viewing"
179
+ " items. NOTE: If you want to add a tag and not"
180
+ " REPLACE a tag, use --add-tag instead."
181
+ ),
182
+ },
183
+ ),
184
+ ModifierArg(
185
+ flags=("--add-tag",),
186
+ dest="add_tag",
187
+ kwargs={
188
+ "action": "append",
189
+ "default": [],
190
+ "metavar": "TAG",
191
+ "help": (
192
+ "Used to add a tag to an existing set of tags"
193
+ " for an item. Can only be used for -e"
194
+ " statements."
195
+ ),
196
+ },
197
+ ),
198
+ ),
199
+ filter_dest="tag",
200
+ ),
201
+ "due_date": ModifierSpec(
202
+ args=(
203
+ ModifierArg(
204
+ flags=("--due",),
205
+ dest="due",
206
+ kwargs={
207
+ "action": "append",
208
+ "default": [],
209
+ "metavar": "WHEN",
210
+ "help": (
211
+ "Set (with -a/-e) or filter (default view) an"
212
+ " item's due date. Accepts: today, tomorrow,"
213
+ " 'N days', 'next-week', 'N weeks', MM-DD-YYYY."
214
+ " Filtering also accepts 'overdue' and 'none'"
215
+ " (items with no due date), and may repeat"
216
+ " (values OR together)."
217
+ ),
218
+ },
219
+ completer=_complete_due_keywords,
220
+ ),
221
+ ModifierArg(
222
+ flags=("--today",),
223
+ dest="today",
224
+ kwargs={
225
+ "action": "store_true",
226
+ "help": (
227
+ "On the default view, show only items due today"
228
+ " (--due today)."
229
+ ),
230
+ },
231
+ filter_word="today",
232
+ ),
233
+ ModifierArg(
234
+ flags=("--undated",),
235
+ dest="undated",
236
+ kwargs={
237
+ "action": "store_true",
238
+ "help": (
239
+ "On the default view, show only not-done items"
240
+ " with no due date (--due none)."
241
+ ),
242
+ },
243
+ filter_word="none",
244
+ ),
245
+ ),
246
+ filter_dest="due",
247
+ multi=True,
248
+ to_criteria=due_to_criteria,
249
+ ),
250
+ "text": ModifierSpec(
251
+ args=(
252
+ ModifierArg(
253
+ flags=("-t", "--text"),
254
+ dest="text",
255
+ kwargs={
256
+ "type": str,
257
+ "default": None,
258
+ "help": (
259
+ "Replace an item's text. Can use for -e"
260
+ " statements only."
261
+ ),
262
+ },
263
+ ),
264
+ ),
265
+ ),
266
+ "description": ModifierSpec(
267
+ args=(
268
+ ModifierArg(
269
+ flags=("--desc",),
270
+ dest="desc",
271
+ kwargs={
272
+ "type": str,
273
+ "default": None,
274
+ "metavar": "TEXT",
275
+ "help": (
276
+ "Set (with -a/-e) an item's description; pass an"
277
+ " empty string to clear it. -a/-e only."
278
+ ),
279
+ },
280
+ ),
281
+ ),
282
+ ),
283
+ "color": ModifierSpec(
284
+ args=(
285
+ ModifierArg(
286
+ flags=("--color",),
287
+ dest="color",
288
+ kwargs={
289
+ "choices": [c.name.lower() for c in Color],
290
+ "nargs": "?",
291
+ "default": None,
292
+ "help": "Add/Change color of LIST.",
293
+ },
294
+ ),
295
+ ),
296
+ ),
297
+ }
298
+
299
+
300
+ def _register_list_args(parser: argparse.ArgumentParser) -> None:
301
+ list_group = parser.add_argument_group(
302
+ "List management",
303
+ "Add, remove, view, prune, or change the color for the given LIST.",
304
+ )
305
+
306
+ ops = list_group.add_mutually_exclusive_group()
307
+ ops.add_argument(
308
+ "-n",
309
+ "--new",
310
+ dest="new",
311
+ action="store_true",
312
+ help="Create LIST as a new, empty list.",
313
+ )
314
+ ops.add_argument(
315
+ "--delete",
316
+ dest="delete",
317
+ action="store_true",
318
+ help="Delete LIST and all its items.",
319
+ )
320
+ ops.add_argument(
321
+ "-l",
322
+ "--lists",
323
+ dest="lists",
324
+ action="store_true",
325
+ help="Show every list name, nested as a tree.",
326
+ )
327
+ ops.add_argument(
328
+ "--prune",
329
+ dest="prune",
330
+ action="store_true",
331
+ help=(
332
+ "Remove all done items from LIST. Combine with --all to prune"
333
+ " all lists."
334
+ ),
335
+ )
336
+ ops.add_argument(
337
+ "--rename",
338
+ dest="rename",
339
+ default=None,
340
+ metavar="NEW_NAME",
341
+ help="Rename LIST (and its sublists) to NEW_NAME.",
342
+ )
343
+ ops.add_argument(
344
+ "--migrate",
345
+ dest="migrate",
346
+ action="store_true",
347
+ help=(
348
+ "Bring every list and config file up to the current on-disk"
349
+ " schema."
350
+ ),
351
+ )
352
+ ops.add_argument(
353
+ "--agenda",
354
+ dest="agenda",
355
+ nargs="?",
356
+ const="",
357
+ default=None,
358
+ metavar="WINDOW",
359
+ help=(
360
+ "Show items due across every list, chronologically. WINDOW:"
361
+ " today, week, overdue, or N (days from today, inclusive);"
362
+ " defaults to the configured agenda_window."
363
+ ),
364
+ )
365
+
366
+ return None
367
+
368
+
369
+ def _register_config_args(parser: argparse.ArgumentParser) -> None:
370
+ config_group = parser.add_argument_group(
371
+ "Configuration management", "View or edit Taskli configs."
372
+ )
373
+
374
+ ops = config_group.add_mutually_exclusive_group()
375
+ ops.add_argument(
376
+ "--config",
377
+ dest="config",
378
+ nargs="*",
379
+ default=None,
380
+ metavar=("KEY", "VALUE"),
381
+ help="View or edit config settings. Omit KEY/VALUE to view all.",
382
+ )
383
+
384
+ return None
385
+
386
+
387
+ def _register_item_action_args(parser: argparse.ArgumentParser) -> None:
388
+ actions_group = parser.add_argument_group(
389
+ "Item actions",
390
+ "Add, remove, edit, or mark item(s) done/in-progress/undone for the"
391
+ " current LIST.",
392
+ )
393
+
394
+ ops = actions_group.add_mutually_exclusive_group()
395
+ ops.add_argument(
396
+ "-a",
397
+ "--add",
398
+ dest="add",
399
+ nargs="+",
400
+ action="append",
401
+ metavar="TEXT",
402
+ help="Add an item to LIST. Repeatable for multiple items.",
403
+ )
404
+ # -d/-i/-u/-rm sit on the plain group, not `ops`: they combine with
405
+ # each other in one invocation (resolved as ItemActionCommands.STATUS),
406
+ # and `_validate` rejects pairing them with -a/-e/-D/-mv/--copy.
407
+ actions_group.add_argument(
408
+ "-rm",
409
+ "--remove",
410
+ dest="remove",
411
+ nargs="+",
412
+ metavar="ID",
413
+ help="Remove an item, or items, from LIST.",
414
+ )
415
+ actions_group.add_argument(
416
+ "-d",
417
+ "--done",
418
+ dest="done",
419
+ nargs="+",
420
+ metavar="ID",
421
+ help="Mark an item, or items, as done.",
422
+ )
423
+ actions_group.add_argument(
424
+ "-u",
425
+ "--undone",
426
+ dest="undone",
427
+ nargs="+",
428
+ metavar="ID",
429
+ help="Mark an item, or items, as not done.",
430
+ )
431
+ actions_group.add_argument(
432
+ "-i",
433
+ "--in-progress",
434
+ dest="in_progress",
435
+ nargs="+",
436
+ metavar="ID",
437
+ help="Mark an item, or items, as in progress.",
438
+ )
439
+ ops.add_argument(
440
+ "-e",
441
+ "--edit",
442
+ dest="edit",
443
+ nargs=1,
444
+ metavar="ID",
445
+ help="Edit an item's text, priority, or tags.",
446
+ )
447
+ ops.add_argument(
448
+ "-D",
449
+ "--details",
450
+ dest="details",
451
+ nargs=1,
452
+ metavar="ID",
453
+ help="Show a task's full detail: description, timestamps, subtasks.",
454
+ )
455
+ ops.add_argument(
456
+ "-mv",
457
+ "--move",
458
+ dest="move",
459
+ nargs="+",
460
+ metavar=("TARGET_LIST", "ID"),
461
+ help=(
462
+ "Move item(s) from LIST to TARGET_LIST. Omit ID to move"
463
+ " every item in LIST."
464
+ ),
465
+ )
466
+ ops.add_argument(
467
+ "--copy",
468
+ dest="copy",
469
+ nargs="+",
470
+ metavar=("TARGET_LIST", "ID"),
471
+ help=(
472
+ "Copy item(s) from LIST to TARGET_LIST. Omit ID to copy"
473
+ " every item in LIST."
474
+ ),
475
+ )
476
+
477
+ return None
478
+
479
+
480
+ def _register_modifier_args(parser: argparse.ArgumentParser) -> None:
481
+ modifiers = parser.add_argument_group(
482
+ "Modifiers", "Add to list or item action args to change behavior."
483
+ )
484
+
485
+ for spec in MODIFIER_FLAGS.values():
486
+ for arg in spec.args:
487
+ action = modifiers.add_argument(
488
+ *arg.flags, dest=arg.dest, **arg.kwargs
489
+ )
490
+ if arg.completer is not None:
491
+ action.completer = arg.completer # type: ignore[attr-defined]
492
+ modifiers.add_argument(
493
+ "--all",
494
+ dest="all",
495
+ action="store_true",
496
+ help=(
497
+ "Used to prune or view across multiple lists. See documentation"
498
+ " for examples."
499
+ ),
500
+ )
501
+ modifiers.add_argument(
502
+ "--under",
503
+ dest="under",
504
+ default=None,
505
+ metavar="PATH",
506
+ help=(
507
+ "With -a, add the new item under item PATH. With -e, re-nest"
508
+ ' the existing item (and its subtree) under PATH; pass "" to'
509
+ " un-nest to the top level."
510
+ ),
511
+ )
512
+
513
+
514
+ def _complete_list_names(
515
+ prefix: str, parsed_args: argparse.Namespace, **kwargs: object
516
+ ) -> list[str]:
517
+ """argcomplete callback: existing list names for the LIST positional."""
518
+
519
+ return scan_list_names(resolve_storage_dir())
520
+
521
+
522
+ def _compose_parser() -> argparse.ArgumentParser:
523
+ parser = argparse.ArgumentParser(
524
+ prog="taskli[tk]",
525
+ description=(
526
+ "Manage Taskli lists/items. LIST defaults to 'inbox' when omitted."
527
+ ),
528
+ epilog="Example: tk groceries --new --color teal",
529
+ )
530
+ list_action = parser.add_argument(
531
+ "list",
532
+ nargs="?",
533
+ default=None,
534
+ metavar="LIST",
535
+ help="Name of the list to act on (default: configured default_list).",
536
+ )
537
+ list_action.completer = _complete_list_names # type: ignore[attr-defined]
538
+ parser.add_argument(
539
+ "--version",
540
+ action="version",
541
+ version=f"taskli {__version__}",
542
+ )
543
+ parser.add_argument(
544
+ "--path",
545
+ action="store_true",
546
+ help="Print the storage directory currently in use and exit.",
547
+ )
548
+
549
+ # register commands/arg groups.
550
+ _register_list_args(parser)
551
+ _register_item_action_args(parser)
552
+ _register_modifier_args(parser)
553
+ _register_config_args(parser)
554
+
555
+ return parser
556
+
557
+
558
+ def _resolve_list_op(namespace: argparse.Namespace) -> ListCommands | None:
559
+ if namespace.new:
560
+ return ListCommands.NEW
561
+ if namespace.delete:
562
+ return ListCommands.DELETE
563
+ if namespace.lists:
564
+ return ListCommands.LISTS
565
+ if namespace.prune:
566
+ return ListCommands.PRUNE
567
+ if namespace.rename:
568
+ return ListCommands.RENAME
569
+ if namespace.migrate:
570
+ return ListCommands.MIGRATE
571
+ if namespace.agenda is not None:
572
+ return ListCommands.AGENDA
573
+ # bare --color with no other list flag means "recolor this list."
574
+ if namespace.color:
575
+ return ListCommands.COLOR
576
+
577
+ return None
578
+
579
+
580
+ def _resolve_item_action_op(
581
+ namespace: argparse.Namespace,
582
+ ) -> ItemActionCommands | None:
583
+ # STATUS first: a -a/-e/... paired with -d/-i/-u/-rm must land in the
584
+ # STATUS validation case so `_validate` can name the real conflict.
585
+ if (
586
+ namespace.done
587
+ or namespace.undone
588
+ or namespace.in_progress
589
+ or namespace.remove
590
+ ):
591
+ return ItemActionCommands.STATUS
592
+ if namespace.add:
593
+ return ItemActionCommands.ADD
594
+ if namespace.edit:
595
+ return ItemActionCommands.EDIT
596
+ if namespace.details:
597
+ return ItemActionCommands.DETAILS
598
+ if namespace.move:
599
+ return ItemActionCommands.MOVE
600
+ if namespace.copy:
601
+ return ItemActionCommands.COPY
602
+
603
+ return None
604
+
605
+
606
+ def _resolve_config_op(
607
+ namespace: argparse.Namespace,
608
+ ) -> ConfigCommands | None:
609
+ if namespace.config is not None:
610
+ return ConfigCommands.CONFIG
611
+
612
+ return None
613
+
614
+
615
+ def _resolve_op(namespace: argparse.Namespace) -> CommandOptions:
616
+ from . import render
617
+
618
+ defined = [
619
+ (label, op)
620
+ for label, op in (
621
+ ("list management", _resolve_list_op(namespace)),
622
+ ("item action", _resolve_item_action_op(namespace)),
623
+ ("config", _resolve_config_op(namespace)),
624
+ )
625
+ if op is not None
626
+ ]
627
+
628
+ # only allow one option. take first & warn.
629
+ if len(defined) > 1:
630
+ winner_label, winner_op = defined[0]
631
+ ignored = ", ".join(label for label, _ in defined[1:])
632
+ render.render_warning(
633
+ f"multiple option groups given; using {winner_label} "
634
+ f"('{winner_op.value}'), ignoring {ignored}."
635
+ )
636
+
637
+ if defined:
638
+ return defined[0][1]
639
+
640
+ # if no option (w/ exception of modifiers), default is view.
641
+ return ListCommands.VIEW
642
+
643
+
644
+ def _reject_modifiers(
645
+ namespace: argparse.Namespace,
646
+ parser: argparse.ArgumentParser,
647
+ context: str,
648
+ allowed: set[str],
649
+ ) -> None:
650
+ # every modifier dest, plus the hand-wired --all/--under scope flags,
651
+ # each mapped to its long option string for the error message.
652
+ flags = {"all": "--all", "under": "--under"} | {
653
+ arg.dest: arg.flags[-1]
654
+ for spec in MODIFIER_FLAGS.values()
655
+ for arg in spec.args
656
+ }
657
+ for dest in sorted(flags.keys() - allowed):
658
+ if getattr(namespace, dest):
659
+ parser.error(f"{flags[dest]} is not valid with {context}.")
660
+
661
+ return None
662
+
663
+
664
+ def _reject_multi_values(
665
+ namespace: argparse.Namespace,
666
+ parser: argparse.ArgumentParser,
667
+ op: ItemActionCommands,
668
+ context: str,
669
+ ) -> None:
670
+ for name, spec in MODIFIER_FLAGS.items():
671
+ if not spec.multi:
672
+ continue
673
+ if op not in registry.ATTRIBUTES[name].modifier_ops:
674
+ continue
675
+ dest = spec.filter_dest
676
+
677
+ assert dest is not None # multi specs set it.
678
+
679
+ if len(getattr(namespace, dest)) > 1:
680
+ parser.error(f"{context} takes one {spec.args[0].flags[0]} value.")
681
+
682
+ return None
683
+
684
+
685
+ def _validate(
686
+ op: ListCommands | ItemActionCommands | ConfigCommands,
687
+ namespace: argparse.Namespace,
688
+ parser: argparse.ArgumentParser,
689
+ ) -> None:
690
+ match op:
691
+ case (
692
+ ListCommands.DELETE
693
+ | ListCommands.LISTS
694
+ | ListCommands.RENAME
695
+ | ListCommands.MIGRATE
696
+ | ListCommands.AGENDA
697
+ ):
698
+ _reject_modifiers(namespace, parser, f"--{op.value}", set())
699
+ case ListCommands.NEW | ListCommands.COLOR:
700
+ # --color is the only modifier that means anything for either:
701
+ # the initial color on creation, or the new color on recolor.
702
+ _reject_modifiers(namespace, parser, "--new/--color", {"color"})
703
+ case ListCommands.PRUNE:
704
+ _reject_modifiers(namespace, parser, "--prune", {"all"})
705
+ case ItemActionCommands.ADD:
706
+ _reject_modifiers(
707
+ namespace,
708
+ parser,
709
+ "-a/--add",
710
+ {"priority", "tag", "due", "desc", "under"},
711
+ )
712
+ _reject_multi_values(
713
+ namespace, parser, ItemActionCommands.ADD, "-a/--add"
714
+ )
715
+ case ItemActionCommands.EDIT:
716
+ if namespace.tag and namespace.add_tag:
717
+ parser.error(
718
+ "--tag and --add-tag cannot both be given; --tag"
719
+ " replaces, --add-tag appends."
720
+ )
721
+ _reject_multi_values(
722
+ namespace, parser, ItemActionCommands.EDIT, "-e/--edit"
723
+ )
724
+ _reject_modifiers(
725
+ namespace,
726
+ parser,
727
+ "-e/--edit",
728
+ {"priority", "tag", "add_tag", "text", "due", "desc", "under"},
729
+ )
730
+ case ItemActionCommands.DETAILS:
731
+ _reject_modifiers(namespace, parser, "-D/--details", set())
732
+ case ItemActionCommands.STATUS:
733
+ # -d/-i/-u/-rm are the one item action off the exclusive
734
+ # `ops` group, so argparse no longer guards them against a
735
+ # second item action -- re-resolve with the status flags
736
+ # blanked to catch any other one, without hardcoding the
737
+ # list. conflict first: for `-e 1 --text x -d 2` the real
738
+ # problem is -e + -d, not the modifier.
739
+ others = argparse.Namespace(**vars(namespace))
740
+ others.done = others.undone = None
741
+ others.in_progress = others.remove = None
742
+ if _resolve_item_action_op(others) is not None:
743
+ parser.error(
744
+ "-d/-i/-u/-rm cannot be combined with"
745
+ " -a/-e/-D/-mv/--copy."
746
+ )
747
+ _reject_modifiers(namespace, parser, "-d/-i/-u/-rm", set())
748
+ seen: dict[str, str] = {}
749
+ groups = {
750
+ "-d": namespace.done or [],
751
+ "-i": namespace.in_progress or [],
752
+ "-u": namespace.undone or [],
753
+ "-rm": namespace.remove or [],
754
+ }
755
+ for flag, ids in groups.items():
756
+ for item_id in ids:
757
+ if seen.get(item_id, flag) != flag:
758
+ parser.error(
759
+ f"id {item_id} given to more than one action"
760
+ " flag."
761
+ )
762
+ seen.setdefault(item_id, flag)
763
+ case ItemActionCommands.MOVE | ItemActionCommands.COPY:
764
+ ids = (
765
+ namespace.move
766
+ if op == ItemActionCommands.MOVE
767
+ else namespace.copy
768
+ )[1:]
769
+ try:
770
+ [path_key(i) for i in ids]
771
+ except ValueError:
772
+ parser.error("ID must be an item path like 1 or 1.2.")
773
+ _reject_modifiers(
774
+ namespace,
775
+ parser,
776
+ "-mv/--move" if op == ItemActionCommands.MOVE else "--copy",
777
+ set(),
778
+ )
779
+ case ConfigCommands.CONFIG:
780
+ if namespace.config and len(namespace.config) > 2:
781
+ parser.error("--config takes at most KEY and VALUE.")
782
+ _reject_modifiers(namespace, parser, "--config", set())
783
+ case ListCommands.VIEW:
784
+ _reject_modifiers(
785
+ namespace,
786
+ parser,
787
+ "the default view",
788
+ {"priority", "tag", "all", "due", "today", "undated"},
789
+ )
790
+
791
+ return None
792
+
793
+
794
+ def _modifier_values(
795
+ op: ItemActionCommands, namespace: argparse.Namespace
796
+ ) -> dict[str, object]:
797
+ values: dict[str, object] = {}
798
+ for name, spec in MODIFIER_FLAGS.items():
799
+ if op not in registry.ATTRIBUTES[name].modifier_ops:
800
+ continue
801
+ if name == "tags":
802
+ if namespace.tag:
803
+ values["tags"] = namespace.tag
804
+ if op is ItemActionCommands.EDIT and namespace.add_tag:
805
+ values["add_tag"] = namespace.add_tag
806
+ continue
807
+ if spec.multi:
808
+ dest = spec.filter_dest
809
+
810
+ assert dest is not None # multi specs set it.
811
+
812
+ values_list = getattr(namespace, dest)
813
+ value = values_list[0] if values_list else None
814
+ else:
815
+ value = getattr(namespace, spec.args[0].dest)
816
+ if value is not None:
817
+ values[name] = value
818
+
819
+ return values
820
+
821
+
822
+ def _run_item_action(
823
+ action: ItemActionCommands,
824
+ list_name: str,
825
+ namespace: argparse.Namespace,
826
+ config: "Config",
827
+ ) -> "CommandResult":
828
+ from . import logic
829
+
830
+ match action:
831
+ case ItemActionCommands.ADD:
832
+ texts = [" ".join(words) for words in namespace.add]
833
+
834
+ return logic.add(
835
+ list_name,
836
+ texts,
837
+ _modifier_values(action, namespace),
838
+ config,
839
+ parent_path=namespace.under,
840
+ )
841
+ case ItemActionCommands.STATUS:
842
+ return logic.batch_actions(
843
+ list_name,
844
+ config,
845
+ done=namespace.done,
846
+ undone=namespace.undone,
847
+ in_progress=namespace.in_progress,
848
+ remove=namespace.remove,
849
+ )
850
+ case ItemActionCommands.MOVE:
851
+ target, *ids = namespace.move
852
+ target_name = target.replace(config.sublist_delimiter, ".")
853
+
854
+ return logic.move(list_name, target_name, ids, config)
855
+ case ItemActionCommands.COPY:
856
+ target, *ids = namespace.copy
857
+ target_name = target.replace(config.sublist_delimiter, ".")
858
+
859
+ return logic.copy(list_name, target_name, ids, config)
860
+
861
+ # only EDIT reaches here: DETAILS is handled in _dispatch, and the
862
+ # match above returns for every other action.
863
+ return logic.edit(
864
+ list_name,
865
+ namespace.edit[0],
866
+ _modifier_values(ItemActionCommands.EDIT, namespace),
867
+ config,
868
+ parent_path=namespace.under,
869
+ )
870
+
871
+
872
+ @_handle_errors
873
+ def _dispatch(
874
+ namespace: argparse.Namespace,
875
+ op: ListCommands | ItemActionCommands | ConfigCommands,
876
+ ) -> int:
877
+ from . import logic, render
878
+ from .storage import load_config
879
+
880
+ if op is ListCommands.MIGRATE:
881
+ result = logic.migrate()
882
+ _render_notices(result)
883
+
884
+ return result.exit_code
885
+
886
+ config = load_config(resolve_storage_dir())
887
+
888
+ if config.show_reminders and op is not ListCommands.AGENDA:
889
+ overdue, due_today = logic.check_reminders()
890
+ if overdue or due_today:
891
+ render.render_reminder(overdue, due_today)
892
+
893
+ if namespace.list:
894
+ list_name = namespace.list.replace(config.sublist_delimiter, ".")
895
+ else:
896
+ list_name = config.default_list.replace(config.sublist_delimiter, ".")
897
+
898
+ match op:
899
+ case ListCommands.LISTS:
900
+ default_name = config.default_list.replace(
901
+ config.sublist_delimiter, "."
902
+ )
903
+ render.render_list_names(logic.list_entries(), default_name)
904
+
905
+ return 0
906
+ case ListCommands.AGENDA:
907
+ render.render_agenda(
908
+ logic.agenda(namespace.agenda or None, config),
909
+ config.sublist_delimiter,
910
+ )
911
+
912
+ return 0
913
+ case ConfigCommands.CONFIG:
914
+ key = namespace.config[0] if namespace.config else None
915
+ value = namespace.config[1] if len(namespace.config) > 1 else None
916
+
917
+ if key is None:
918
+ render.render_config(config)
919
+
920
+ return 0
921
+ if value is None:
922
+ render.render_value(str(config.get_value(key)))
923
+
924
+ return 0
925
+
926
+ return _emit(logic.set_config(key, value), config)
927
+ case ListCommands.NEW:
928
+ return _emit(
929
+ logic.new_list(list_name, namespace.color, config), config
930
+ )
931
+ case ListCommands.DELETE:
932
+ prompt = logic.delete_prompt(list_name, config)
933
+ if not _confirm(prompt):
934
+ render.render_message("aborted.")
935
+
936
+ return 1
937
+
938
+ return _emit(logic.delete_confirmed(list_name, config), config)
939
+ case ListCommands.COLOR:
940
+ return _emit(
941
+ logic.set_list_color(list_name, namespace.color, config),
942
+ config,
943
+ )
944
+ case ListCommands.PRUNE:
945
+ return _emit(
946
+ logic.prune(
947
+ list_name,
948
+ namespace.all,
949
+ bool(namespace.list),
950
+ config,
951
+ ),
952
+ config,
953
+ )
954
+ case ListCommands.RENAME:
955
+ new_name = namespace.rename.replace(config.sublist_delimiter, ".")
956
+
957
+ return _emit(logic.rename(list_name, new_name, config), config)
958
+ case ItemActionCommands.DETAILS:
959
+ task_list, item = logic.item_details(
960
+ list_name, namespace.details[0]
961
+ )
962
+ render.render_item_details(
963
+ task_list, item, config.sublist_delimiter
964
+ )
965
+
966
+ return 0
967
+ case ItemActionCommands():
968
+ return _emit(
969
+ _run_item_action(op, list_name, namespace, config), config
970
+ )
971
+ case _:
972
+ # only ListCommands.VIEW reaches here; it's the fallback when
973
+ # nothing else matched, so it's never named explicitly.
974
+ criteria: list[Criterion] = []
975
+ any_of: tuple[tuple[Criterion, ...], ...] = ()
976
+ for name, attr in registry.filterable().items():
977
+ spec = MODIFIER_FLAGS[name]
978
+ dest = spec.filter_dest
979
+
980
+ assert dest is not None # filterable entries set it.
981
+
982
+ raw = getattr(namespace, dest)
983
+ if spec.multi:
984
+ # each token is one OR-alternative from to_criteria.
985
+ tokens: list[str] = list(raw)
986
+ for arg in spec.args:
987
+ if arg.filter_word and getattr(namespace, arg.dest):
988
+ tokens.append(arg.filter_word)
989
+ assert spec.to_criteria is not None # multi sets it.
990
+ assert not any_of # one repeatable view filter
991
+ any_of = tuple(spec.to_criteria(t) for t in tokens)
992
+ continue
993
+ if not raw:
994
+ continue
995
+
996
+ value = raw[0] if isinstance(raw, list) else raw
997
+
998
+ parse = attr.parse
999
+ operand = parse(value) if parse is not None else value
1000
+ operator = attr.filter_default_operator
1001
+
1002
+ assert operator is not None # filterable() entries set it.
1003
+
1004
+ criteria.append(Criterion(name, operator, operand))
1005
+
1006
+ item_filter = Filter(tuple(criteria), any_of=any_of)
1007
+
1008
+ if not namespace.list and namespace.all:
1009
+ groups = logic.all_views(item_filter)
1010
+ if not groups:
1011
+ # all_views returns [] either for a filter that
1012
+ # matched nothing or for genuinely-empty storage;
1013
+ # has_any_lists tells the two apart.
1014
+ if logic.has_any_lists():
1015
+ render.render_message(
1016
+ "no items match the given filter."
1017
+ )
1018
+ else:
1019
+ render.render_list_names([])
1020
+
1021
+ return 0
1022
+ for group in groups:
1023
+ render.render_list_tree(group, config.sublist_delimiter)
1024
+
1025
+ return 0
1026
+
1027
+ views = logic.list_view(
1028
+ list_name,
1029
+ item_filter,
1030
+ namespace.all,
1031
+ )
1032
+ if not views:
1033
+ # no empty-storage case to disambiguate here (unlike the
1034
+ # --all branch): a missing target raises before list_view
1035
+ # can return [], so [] always means the filter pruned
1036
+ # every list from a --all view.
1037
+ render.render_message("no items match the given filter.")
1038
+
1039
+ return 0
1040
+
1041
+ render.render_list_tree(views, config.sublist_delimiter)
1042
+
1043
+ return 0
1044
+
1045
+
1046
+ def main(argv: list[str] | None = None) -> int:
1047
+ raw_argv = list(sys.argv[1:] if argv is None else argv)
1048
+
1049
+ parser = _compose_parser()
1050
+ try:
1051
+ argcomplete.autocomplete(parser)
1052
+ namespace = parser.parse_args(raw_argv)
1053
+
1054
+ if namespace.path:
1055
+ from . import logic, render
1056
+
1057
+ render.render_value(str(logic.storage_path()))
1058
+
1059
+ return 0
1060
+
1061
+ op = _resolve_op(namespace)
1062
+ _validate(op, namespace, parser)
1063
+
1064
+ # argparse calls sys.exit for --help and its own parse errors; convert
1065
+ # that into a return code instead of letting it propagate.
1066
+ except SystemExit as e:
1067
+ return e.code if isinstance(e.code, int) else 1
1068
+
1069
+ return _dispatch(namespace, op)
1070
+
1071
+
1072
+ if __name__ == "__main__":
1073
+ sys.exit(main())