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/logic.py ADDED
@@ -0,0 +1,1099 @@
1
+ """Per-command orchestration between the CLI and storage/models."""
2
+
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import cast
7
+
8
+ from .env import resolve_storage_dir
9
+ from .exceptions import (
10
+ InvalidModifierValueError,
11
+ ItemNotFoundError,
12
+ TaskliError,
13
+ )
14
+ from .hierarchy import ancestor_chain, descendant_list_names
15
+ from .models import registry
16
+ from .models.attributes import Color, Operator
17
+ from .models.config import Config
18
+ from .models.query import (
19
+ Criterion,
20
+ Filter,
21
+ Sort,
22
+ agenda_criteria,
23
+ due_to_criteria,
24
+ )
25
+ from .models.tasks import TaskliItem, TaskliList, walk_items
26
+ from .storage import (
27
+ create_list,
28
+ delete_list,
29
+ list_all_lists,
30
+ load_config,
31
+ load_list,
32
+ load_or_create_list,
33
+ migrate_all,
34
+ rename_list,
35
+ resort_all_lists,
36
+ save_config,
37
+ save_list,
38
+ )
39
+
40
+
41
+ @dataclass
42
+ class CommandResult:
43
+ messages: list[str] = field(default_factory=list)
44
+ warnings: list[str] = field(default_factory=list)
45
+ exit_code: int = 0
46
+ item_view: TaskliList | None = None
47
+ tree_view: list[TaskliList] | None = None
48
+
49
+
50
+ def storage_path() -> Path:
51
+ """Return the storage directory currently in use.
52
+
53
+ Returns
54
+ -------
55
+ Path
56
+ The resolved storage directory.
57
+ """
58
+
59
+ return resolve_storage_dir()
60
+
61
+
62
+ def _mutate(
63
+ list_name: str, mutate_fn: Callable[[TaskliList], str]
64
+ ) -> CommandResult:
65
+ """Load a list, apply ``mutate_fn``, save, and echo the list back."""
66
+
67
+ storage_dir = resolve_storage_dir()
68
+ task_list = load_list(storage_dir, list_name)
69
+ message = mutate_fn(task_list)
70
+
71
+ save_list(storage_dir, task_list)
72
+
73
+ return CommandResult(messages=[message], item_view=task_list)
74
+
75
+
76
+ def _resolve_modifiers(raw: dict[str, object]) -> dict[str, object]:
77
+ """Turn raw string modifier values into typed field values."""
78
+
79
+ typed: dict[str, object] = {}
80
+ for name, value in raw.items():
81
+ attr = registry.ATTRIBUTES.get(name)
82
+ if attr is None:
83
+ raise InvalidModifierValueError(f"unknown modifier '{name}'.")
84
+ parse = attr.parse
85
+ if parse is None:
86
+ typed[name] = value
87
+ continue
88
+ try:
89
+ # the cli only ever supplies str modifier values.
90
+ typed[name] = parse(cast(str, value))
91
+ except InvalidModifierValueError:
92
+ raise
93
+ except (KeyError, ValueError, TaskliError) as error:
94
+ raise InvalidModifierValueError(
95
+ f"invalid value for '{name}': {value!r}."
96
+ ) from error
97
+
98
+ return typed
99
+
100
+
101
+ def _per_item(typed: dict[str, object]) -> dict[str, object]:
102
+ """Copy a typed modifier mapping, duplicating its list values."""
103
+
104
+ return {
105
+ key: list(value) if isinstance(value, list) else value
106
+ for key, value in typed.items()
107
+ }
108
+
109
+
110
+ def add(
111
+ list_name: str,
112
+ texts: list[str],
113
+ modifiers: dict[str, object],
114
+ config: Config,
115
+ parent_path: str | None = None,
116
+ ) -> CommandResult:
117
+ """Add one or more items to a list, creating the list if missing.
118
+
119
+ Parameters
120
+ ----------
121
+ list_name : str
122
+ The target list.
123
+ texts : list[str]
124
+ One entry per item to add.
125
+ modifiers : dict[str, object]
126
+ Raw modifier values keyed by field name, applied to every item
127
+ added in this call. A missing ``priority`` falls back to the
128
+ config default.
129
+ config : Config
130
+ The active config, for the display name and default sort.
131
+ parent_path : str | None, optional
132
+ The dotted path of an existing item to nest the new items under,
133
+ or ``None`` to add them at the top level.
134
+
135
+ Returns
136
+ -------
137
+ CommandResult
138
+ One message per added item plus the list as the item view.
139
+ """
140
+
141
+ storage_dir = resolve_storage_dir()
142
+
143
+ # resolve before load_or_create_list so a bad value doesn't leave an
144
+ # empty list file behind.
145
+ raw = dict(modifiers)
146
+ raw.setdefault("priority", config.default_priority.label)
147
+ typed = _resolve_modifiers(raw)
148
+
149
+ task_list = load_or_create_list(storage_dir, list_name, config=config)
150
+ display_name = task_list.display_name(config.sublist_delimiter)
151
+
152
+ added = [
153
+ task_list.add_item(text, _per_item(typed), parent_path=parent_path)
154
+ for text in texts
155
+ ]
156
+
157
+ # resort before reading ids back: reindex can renumber the new items.
158
+ task_list.resort(Sort.from_default_sort(config.default_sort))
159
+
160
+ result = CommandResult(item_view=task_list)
161
+ for item in added:
162
+ result.messages.append(f"added #{item.id} to '{display_name}'.")
163
+
164
+ save_list(storage_dir, task_list)
165
+
166
+ return result
167
+
168
+
169
+ def set_list_color(name: str, color: str, config: Config) -> CommandResult:
170
+ """Recolor an existing list.
171
+
172
+ Parameters
173
+ ----------
174
+ name : str
175
+ The list to recolor.
176
+ color : str
177
+ Color name (lower-cased).
178
+ config : Config
179
+ The active config, for the display name.
180
+
181
+ Returns
182
+ -------
183
+ CommandResult
184
+ The status message plus the list as the item view.
185
+ """
186
+
187
+ def mutate_fn(task_list: TaskliList) -> str:
188
+ task_list.set_color(Color[color.upper()])
189
+ display_name = task_list.display_name(config.sublist_delimiter)
190
+
191
+ return f"updated color of '{display_name}' to '{color}'."
192
+
193
+ return _mutate(name, mutate_fn)
194
+
195
+
196
+ def edit(
197
+ list_name: str,
198
+ item_id: str,
199
+ modifiers: dict[str, object],
200
+ config: Config,
201
+ parent_path: str | None = None,
202
+ ) -> CommandResult:
203
+ """Edit an item's text, priority, tags, or other modifiers.
204
+
205
+ Parameters
206
+ ----------
207
+ list_name : str
208
+ The list holding the item.
209
+ item_id : str
210
+ The item to edit.
211
+ modifiers : dict[str, object]
212
+ Raw modifier values keyed by field name. The reserved
213
+ ``add_tag`` key appends to the item's existing tags instead of
214
+ replacing them.
215
+ config : Config
216
+ The active config, for the display name.
217
+ parent_path : str | None, optional
218
+ The dotted path of an existing item to re-nest this item under,
219
+ or ``None`` to leave its position alone. An empty string
220
+ un-nests the item back to the top level.
221
+
222
+ Returns
223
+ -------
224
+ CommandResult
225
+ The status message plus the list as the item view.
226
+ """
227
+
228
+ def mutate_fn(task_list: TaskliList) -> str:
229
+ mods = dict(modifiers)
230
+ add_tag = cast(list[str] | None, mods.pop("add_tag", None))
231
+ task_list.edit_item(item_id, _resolve_modifiers(mods))
232
+ if add_tag:
233
+ task_list.add_tags(item_id, add_tag)
234
+
235
+ new_id = item_id
236
+ if parent_path is not None:
237
+ moved = task_list.reparent_item(item_id, parent_path or None)
238
+ # reparent_item already reindexed, so moved.id is valid; the
239
+ # resort places the item in default_sort order within its new
240
+ # sibling group (renumbering again as a consequence), matching
241
+ # add/move/copy. A plain -e deliberately does not resort.
242
+ task_list.resort(Sort.from_default_sort(config.default_sort))
243
+ new_id = moved.id
244
+
245
+ display_name = task_list.display_name(config.sublist_delimiter)
246
+
247
+ return f"updated #{new_id} in '{display_name}'."
248
+
249
+ return _mutate(list_name, mutate_fn)
250
+
251
+
252
+ def mark_done(
253
+ list_name: str, item_ids: list[str], config: Config
254
+ ) -> CommandResult:
255
+ """Mark one or more items done, tolerating missing ids.
256
+
257
+ Parameters
258
+ ----------
259
+ list_name : str
260
+ The list holding the items.
261
+ item_ids : list[str]
262
+ Ids to mark done.
263
+ config : Config
264
+ The active config, for the display name.
265
+
266
+ Returns
267
+ -------
268
+ CommandResult
269
+ One message per marked id, one warning per missing id.
270
+ """
271
+
272
+ return batch_actions(list_name, config, done=item_ids)
273
+
274
+
275
+ def mark_undone(
276
+ list_name: str, item_ids: list[str], config: Config
277
+ ) -> CommandResult:
278
+ """Mark one or more items not done, tolerating missing ids.
279
+
280
+ Parameters
281
+ ----------
282
+ list_name : str
283
+ The list holding the items.
284
+ item_ids : list[str]
285
+ Ids to mark not done.
286
+ config : Config
287
+ The active config, for the display name.
288
+
289
+ Returns
290
+ -------
291
+ CommandResult
292
+ One message per marked id, one warning per missing id.
293
+ """
294
+
295
+ return batch_actions(list_name, config, undone=item_ids)
296
+
297
+
298
+ def mark_in_progress(
299
+ list_name: str, item_ids: list[str], config: Config
300
+ ) -> CommandResult:
301
+ """Mark one or more items in progress, tolerating missing ids.
302
+
303
+ Parameters
304
+ ----------
305
+ list_name : str
306
+ The list holding the items.
307
+ item_ids : list[str]
308
+ Ids to mark in progress.
309
+ config : Config
310
+ The active config, for the display name.
311
+
312
+ Returns
313
+ -------
314
+ CommandResult
315
+ One message per marked id, one warning per missing id.
316
+ """
317
+
318
+ return batch_actions(list_name, config, in_progress=item_ids)
319
+
320
+
321
+ def _resolve_items(
322
+ task_list: TaskliList,
323
+ item_ids: list[str],
324
+ *,
325
+ drop_covered: bool = False,
326
+ ) -> tuple[list[tuple[str, TaskliItem]], list[str]]:
327
+ """Resolve ids to items, deduped by identity, with per-id warnings.
328
+
329
+ With ``drop_covered``, also drop any resolved item that lives inside
330
+ another resolved item's subtree -- for the whole-subtree ops
331
+ (remove / move / copy) the ancestor already carries it. The mark ops
332
+ leave it off, since marking does not cascade.
333
+ """
334
+
335
+ resolved: list[tuple[str, TaskliItem]] = []
336
+ seen: set[int] = set()
337
+ warnings: list[str] = []
338
+ for item_id in item_ids:
339
+ try:
340
+ item = task_list.get_item(item_id)
341
+ except ItemNotFoundError as e:
342
+ warnings.append(str(e))
343
+ continue
344
+ if id(item) in seen:
345
+ continue
346
+ seen.add(id(item))
347
+ resolved.append((item_id, item))
348
+
349
+ if drop_covered:
350
+ # the ancestor carries the descendant, same as duplicate ids
351
+ # collapsing to one action.
352
+ covered = {item.id for _, item in resolved}
353
+ resolved = [
354
+ (item_id, item)
355
+ for item_id, item in resolved
356
+ if not any(
357
+ item.id.startswith(f"{ancestor}.") for ancestor in covered
358
+ )
359
+ ]
360
+
361
+ return resolved, warnings
362
+
363
+
364
+ def batch_actions(
365
+ list_name: str,
366
+ config: Config,
367
+ *,
368
+ done: list[str] | None = None,
369
+ undone: list[str] | None = None,
370
+ in_progress: list[str] | None = None,
371
+ remove: list[str] | None = None,
372
+ ) -> CommandResult:
373
+ """Apply status marks and removals to one list in a single pass.
374
+
375
+ Parameters
376
+ ----------
377
+ list_name : str
378
+ The list holding the items.
379
+ config : Config
380
+ The active config, for the display name.
381
+ done, undone, in_progress : list[str] | None
382
+ Ids to mark done / not done / in progress, respectively.
383
+ remove : list[str] | None
384
+ Ids to remove, each with its whole subtree.
385
+
386
+ Returns
387
+ -------
388
+ CommandResult
389
+ One message per acted-on id, one warning per missing id; the
390
+ exit code is 1 when any id was missing.
391
+
392
+ Notes
393
+ -----
394
+ Marks are applied before removals so a removed subtree's cascade and
395
+ reindex cannot strand a just-marked reference. An id under both a
396
+ mark flag and ``remove`` (only possible via distinct raw strings, as
397
+ ``-d 1.1 -rm 1``) is honoured for both -- the CLI rejects the same
398
+ raw string under two flags before this is called.
399
+ """
400
+
401
+ marks = [
402
+ (TaskliList.mark_done_ref, "done", done or []),
403
+ (TaskliList.mark_in_progress_ref, "in progress", in_progress or []),
404
+ (TaskliList.mark_undone_ref, "not done", undone or []),
405
+ ]
406
+
407
+ storage_dir = resolve_storage_dir()
408
+ task_list = load_list(storage_dir, list_name)
409
+ display_name = task_list.display_name(config.sublist_delimiter)
410
+
411
+ result = CommandResult()
412
+ for mark, label, ids in marks:
413
+ resolved, warnings = _resolve_items(task_list, ids)
414
+ result.warnings.extend(warnings)
415
+ for item_id, item in resolved:
416
+ mark(task_list, item)
417
+ result.messages.append(
418
+ f"marked #{item_id} {label} in '{display_name}'."
419
+ )
420
+
421
+ resolved, warnings = _resolve_items(
422
+ task_list, remove or [], drop_covered=True
423
+ )
424
+ result.warnings.extend(warnings)
425
+ for item_id, item in resolved:
426
+ task_list.remove_item_ref(item)
427
+ result.messages.append(f"removed #{item_id} from '{display_name}'.")
428
+
429
+ save_list(storage_dir, task_list)
430
+ result.item_view = task_list
431
+ result.exit_code = 1 if result.warnings else 0
432
+
433
+ return result
434
+
435
+
436
+ def remove_items(
437
+ list_name: str, item_ids: list[str], config: Config
438
+ ) -> CommandResult:
439
+ """Remove one or more items, tolerating missing ids.
440
+
441
+ Parameters
442
+ ----------
443
+ list_name : str
444
+ The list holding the items.
445
+ item_ids : list[str]
446
+ Ids to remove.
447
+ config : Config
448
+ The active config, for the display name.
449
+
450
+ Returns
451
+ -------
452
+ CommandResult
453
+ One message per removed id, one warning per missing id.
454
+ """
455
+
456
+ return batch_actions(list_name, config, remove=item_ids)
457
+
458
+
459
+ def move(
460
+ list_name: str,
461
+ target_name: str,
462
+ item_ids: list[str],
463
+ config: Config,
464
+ ) -> CommandResult:
465
+ """Move items from one list to another, tolerating missing ids.
466
+
467
+ Parameters
468
+ ----------
469
+ list_name : str
470
+ The source list.
471
+ target_name : str
472
+ The destination list, created if missing.
473
+ item_ids : list[str]
474
+ Ids to move; empty moves every item in the source.
475
+ config : Config
476
+ The active config, for display names and default sort.
477
+
478
+ Returns
479
+ -------
480
+ CommandResult
481
+ One message per moved id, one warning per missing id, plus the
482
+ target list as the item view.
483
+ """
484
+
485
+ storage_dir = resolve_storage_dir()
486
+ task_list = load_list(storage_dir, list_name)
487
+ target_list = load_or_create_list(storage_dir, target_name, config=config)
488
+ display_name = task_list.display_name(config.sublist_delimiter)
489
+ target_display_name = target_list.display_name(config.sublist_delimiter)
490
+
491
+ # top-level ids only; each child subtree travels with its root.
492
+ ids = item_ids or [item.id for item in task_list.items]
493
+
494
+ result = CommandResult()
495
+ resolved, result.warnings = _resolve_items(
496
+ task_list, ids, drop_covered=True
497
+ )
498
+ for item_id, item in resolved:
499
+ task_list.move_item_ref(item, target_list)
500
+ result.messages.append(
501
+ f"moved #{item_id} from '{display_name}' to "
502
+ f"'{target_display_name}'."
503
+ )
504
+
505
+ target_list.resort(Sort.from_default_sort(config.default_sort))
506
+
507
+ save_list(storage_dir, task_list)
508
+ save_list(storage_dir, target_list)
509
+ result.item_view = target_list
510
+ result.exit_code = 1 if result.warnings else 0
511
+
512
+ return result
513
+
514
+
515
+ def copy(
516
+ list_name: str,
517
+ target_name: str,
518
+ item_ids: list[str],
519
+ config: Config,
520
+ ) -> CommandResult:
521
+ """Copy items from one list to another, tolerating missing ids.
522
+
523
+ Parameters
524
+ ----------
525
+ list_name : str
526
+ The source list.
527
+ target_name : str
528
+ The destination list, created if missing.
529
+ item_ids : list[str]
530
+ Ids to copy; empty copies every item in the source.
531
+ config : Config
532
+ The active config, for display names and default sort.
533
+
534
+ Returns
535
+ -------
536
+ CommandResult
537
+ One message per copied id, one warning per missing id, plus the
538
+ target list as the item view.
539
+ """
540
+
541
+ storage_dir = resolve_storage_dir()
542
+ task_list = load_list(storage_dir, list_name)
543
+ target_list = load_or_create_list(storage_dir, target_name, config=config)
544
+ display_name = task_list.display_name(config.sublist_delimiter)
545
+ target_display_name = target_list.display_name(config.sublist_delimiter)
546
+
547
+ # top-level ids only; each child subtree travels with its root.
548
+ ids = item_ids or [item.id for item in task_list.items]
549
+
550
+ result = CommandResult()
551
+ resolved, result.warnings = _resolve_items(
552
+ task_list, ids, drop_covered=True
553
+ )
554
+ for item_id, item in resolved:
555
+ task_list.copy_item_ref(item, target_list)
556
+ result.messages.append(
557
+ f"copied #{item_id} from '{display_name}' to "
558
+ f"'{target_display_name}'."
559
+ )
560
+
561
+ target_list.resort(Sort.from_default_sort(config.default_sort))
562
+
563
+ save_list(storage_dir, target_list)
564
+ result.item_view = target_list
565
+ result.exit_code = 1 if result.warnings else 0
566
+
567
+ return result
568
+
569
+
570
+ def prune(
571
+ list_name: str,
572
+ prune_all: bool,
573
+ target_given: bool,
574
+ config: Config,
575
+ ) -> CommandResult:
576
+ """Remove done items from one or more lists.
577
+
578
+ Parameters
579
+ ----------
580
+ list_name : str
581
+ The primary list to prune.
582
+ prune_all : bool
583
+ When true, also prune descendants (with a target) or every list
584
+ on disk (without one).
585
+ target_given : bool
586
+ Whether an explicit list name was passed on the command line.
587
+ config : Config
588
+ The active config, for display names and ``silent_prune``.
589
+
590
+ Returns
591
+ -------
592
+ CommandResult
593
+ One message per pruned list, plus every pruned list as the tree
594
+ view unless ``config.silent_prune`` is set.
595
+ """
596
+
597
+ storage_dir = resolve_storage_dir()
598
+
599
+ lists: list[TaskliList] = [load_list(storage_dir, list_name)]
600
+ if prune_all:
601
+ all_lists = list_all_lists(storage_dir)
602
+ if target_given:
603
+ names = descendant_list_names(list_name, all_lists)
604
+ else:
605
+ names = all_lists
606
+ lists.extend(load_list(storage_dir, name) for name in names)
607
+
608
+ result = CommandResult()
609
+ if not config.silent_prune:
610
+ result.tree_view = lists
611
+
612
+ for task_list in lists:
613
+ removed = task_list.prune()
614
+ save_list(storage_dir, task_list)
615
+
616
+ display_name = task_list.display_name(config.sublist_delimiter)
617
+ result.messages.append(
618
+ f"pruned {len(removed)} item(s) from '{display_name}'."
619
+ )
620
+
621
+ return result
622
+
623
+
624
+ def new_list(name: str, color: str | None, config: Config) -> CommandResult:
625
+ """Create and persist a new, empty list.
626
+
627
+ Parameters
628
+ ----------
629
+ name : str
630
+ The new list's name.
631
+ color : str | None
632
+ Color name (lower-cased), or None to inherit the nearest ancestor
633
+ list's color, falling back to the config default.
634
+ config : Config
635
+ The active config, for the default color and display name.
636
+
637
+ Returns
638
+ -------
639
+ CommandResult
640
+ The status message plus the new list as the item view.
641
+ """
642
+
643
+ storage_dir = resolve_storage_dir()
644
+ explicit = Color[color.upper()] if color else None
645
+
646
+ task_list = create_list(storage_dir, name, color=explicit, config=config)
647
+ display_name = task_list.display_name(config.sublist_delimiter)
648
+
649
+ return CommandResult(
650
+ messages=[f"created list '{display_name}'."], item_view=task_list
651
+ )
652
+
653
+
654
+ def rename(old_name: str, new_name: str, config: Config) -> CommandResult:
655
+ """Rename a list and its descendants, following the default list.
656
+
657
+ Parameters
658
+ ----------
659
+ old_name : str
660
+ The list's current name.
661
+ new_name : str
662
+ The list's new name.
663
+ config : Config
664
+ The active config; its ``default_list`` is updated and saved if it
665
+ pointed at a renamed list.
666
+
667
+ Returns
668
+ -------
669
+ CommandResult
670
+ A single status message.
671
+ """
672
+
673
+ storage_dir = resolve_storage_dir()
674
+ old_display = TaskliList(name=old_name).display_name(
675
+ config.sublist_delimiter
676
+ )
677
+ new_display = TaskliList(name=new_name).display_name(
678
+ config.sublist_delimiter
679
+ )
680
+
681
+ renamed = rename_list(storage_dir, old_name, new_name)
682
+
683
+ if not renamed:
684
+ return CommandResult(
685
+ messages=[f"'{old_display}' is already named '{old_display}'."]
686
+ )
687
+
688
+ if len(renamed) > 1:
689
+ message = (
690
+ f"renamed '{old_display}' to '{new_display}' and "
691
+ f"{len(renamed) - 1} sublist(s)."
692
+ )
693
+ else:
694
+ message = f"renamed '{old_display}' to '{new_display}'."
695
+
696
+ canonical_default = config.default_list.replace(
697
+ config.sublist_delimiter, "."
698
+ )
699
+ for old, new in renamed:
700
+ if canonical_default == old:
701
+ config.default_list = new.replace(".", config.sublist_delimiter)
702
+ save_config(storage_dir, config)
703
+ break
704
+
705
+ return CommandResult(messages=[message])
706
+
707
+
708
+ def delete_prompt(name: str, config: Config) -> str:
709
+ """Build the confirmation prompt for deleting a list.
710
+
711
+ Parameters
712
+ ----------
713
+ name : str
714
+ The list to be deleted.
715
+ config : Config
716
+ The active config, for display names.
717
+
718
+ Returns
719
+ -------
720
+ str
721
+ The prompt text, naming any descendant lists that would also go.
722
+ """
723
+
724
+ storage_dir = resolve_storage_dir()
725
+ descendants = descendant_list_names(name, list_all_lists(storage_dir))
726
+ display_name = TaskliList(name=name).display_name(config.sublist_delimiter)
727
+
728
+ if not descendants:
729
+ return f"delete list '{display_name}' and all its items?"
730
+
731
+ display_descendants = [
732
+ TaskliList(name=d).display_name(config.sublist_delimiter)
733
+ for d in descendants
734
+ ]
735
+
736
+ return (
737
+ f"delete list '{display_name}' and its {len(descendants)} "
738
+ f"sublist(s) ({', '.join(display_descendants)}) and all "
739
+ "their items?"
740
+ )
741
+
742
+
743
+ def delete_confirmed(name: str, config: Config) -> CommandResult:
744
+ """Delete a list and its descendants after confirmation.
745
+
746
+ Parameters
747
+ ----------
748
+ name : str
749
+ The list to delete.
750
+ config : Config
751
+ The active config, for the display name.
752
+
753
+ Returns
754
+ -------
755
+ CommandResult
756
+ A single status message; no list view (the list is gone).
757
+ """
758
+
759
+ storage_dir = resolve_storage_dir()
760
+ display_name = TaskliList(name=name).display_name(config.sublist_delimiter)
761
+
762
+ deleted_descendants = delete_list(storage_dir, name)
763
+
764
+ if deleted_descendants:
765
+ message = (
766
+ f"deleted list '{display_name}' and "
767
+ f"{len(deleted_descendants)} sublist(s)."
768
+ )
769
+ else:
770
+ message = f"deleted list '{display_name}'."
771
+
772
+ return CommandResult(messages=[message])
773
+
774
+
775
+ def set_config(key: str, value: str) -> CommandResult:
776
+ """Set a config value, resorting every list if the sort changed.
777
+
778
+ Parameters
779
+ ----------
780
+ key : str
781
+ The config key to set.
782
+ value : str
783
+ The new value.
784
+
785
+ Returns
786
+ -------
787
+ CommandResult
788
+ A single status message.
789
+ """
790
+
791
+ storage_dir = resolve_storage_dir()
792
+ config = load_config(storage_dir)
793
+
794
+ config.set_value(key, value)
795
+ save_config(storage_dir, config)
796
+
797
+ if key == "default_sort":
798
+ resort_all_lists(
799
+ storage_dir, Sort.from_default_sort(config.default_sort)
800
+ )
801
+
802
+ return CommandResult(messages=[f"set '{key}' to '{value}'."])
803
+
804
+
805
+ def migrate() -> CommandResult:
806
+ """Bring every on-disk list and config file up to the current schema.
807
+
808
+ Returns
809
+ -------
810
+ CommandResult
811
+ One message per migrated or already-current file, one warning per
812
+ file whose JSON could not be read; ``exit_code`` is 1 when any
813
+ file was unreadable.
814
+ """
815
+
816
+ result = CommandResult()
817
+ for name, outcome in migrate_all(resolve_storage_dir()):
818
+ if outcome == "migrated":
819
+ result.messages.append(f"migrated '{name}'.")
820
+ elif outcome == "current":
821
+ result.messages.append(f"'{name}' already current.")
822
+ else:
823
+ result.warnings.append(f"could not read '{name}'; skipped.")
824
+
825
+ result.exit_code = 1 if result.warnings else 0
826
+
827
+ return result
828
+
829
+
830
+ def list_entries() -> list[tuple[str, Color | None]]:
831
+ """Return every list name paired with its color.
832
+
833
+ Returns
834
+ -------
835
+ list[tuple[str, Color | None]]
836
+ (name, color) for every list on disk, color None if the file
837
+ fails to load.
838
+ """
839
+
840
+ storage_dir = resolve_storage_dir()
841
+
842
+ entries: list[tuple[str, Color | None]] = []
843
+ for name in list_all_lists(storage_dir):
844
+ try:
845
+ entries.append((name, load_list(storage_dir, name).color))
846
+ except TaskliError:
847
+ entries.append((name, None))
848
+
849
+ return entries
850
+
851
+
852
+ def has_any_lists() -> bool:
853
+ """Return whether any list exists on disk.
854
+
855
+ Returns
856
+ -------
857
+ bool
858
+ True if at least one list file is present.
859
+ """
860
+
861
+ return bool(list_all_lists(resolve_storage_dir()))
862
+
863
+
864
+ def _all_items(storage_dir: Path) -> list[tuple[str, TaskliItem]]:
865
+ """Return every item on disk, paired with its list name."""
866
+
867
+ items: list[tuple[str, TaskliItem]] = []
868
+ for name in list_all_lists(storage_dir):
869
+ try:
870
+ task_list = load_list(storage_dir, name)
871
+ except TaskliError:
872
+ continue
873
+ items.extend((name, item) for item in walk_items(task_list.items))
874
+
875
+ return items
876
+
877
+
878
+ def check_reminders() -> tuple[int, int]:
879
+ """Count overdue and due-today items across every list on disk.
880
+
881
+ Returns
882
+ -------
883
+ tuple[int, int]
884
+ (overdue, due_today) item counts, including nested subtasks.
885
+ A list that fails to load is skipped rather than raising.
886
+ """
887
+
888
+ storage_dir = resolve_storage_dir()
889
+ overdue_filter = Filter(due_to_criteria("overdue"))
890
+ today_filter = Filter(
891
+ due_to_criteria("today") + (Criterion("done", Operator.EQ, False),)
892
+ )
893
+
894
+ overdue = due_today = 0
895
+ for _, item in _all_items(storage_dir):
896
+ if overdue_filter.matches(item):
897
+ overdue += 1
898
+ elif today_filter.matches(item):
899
+ due_today += 1
900
+
901
+ return overdue, due_today
902
+
903
+
904
+ def agenda(window: str | None, config: Config) -> list[tuple[str, TaskliItem]]:
905
+ """Return items due within a window, chronologically, across every list.
906
+
907
+ Parameters
908
+ ----------
909
+ window : str | None
910
+ An explicit window token (``today``/``week``/``overdue``/``N``),
911
+ or None to fall back to ``config.agenda_window``.
912
+ config : Config
913
+ The active config, for the default window.
914
+
915
+ Returns
916
+ -------
917
+ list[tuple[str, TaskliItem]]
918
+ (list name, item) rows sorted chronologically by due date across
919
+ every list on disk, including nested subtasks. A list that fails
920
+ to load is skipped rather than raising.
921
+ """
922
+
923
+ storage_dir = resolve_storage_dir()
924
+ token = window or config.agenda_window
925
+ item_filter = Filter(
926
+ agenda_criteria(token, include_overdue=config.agenda_include_overdue)
927
+ )
928
+
929
+ rows = [
930
+ (name, item)
931
+ for name, item in _all_items(storage_dir)
932
+ if item_filter.matches(item)
933
+ ]
934
+ sort_key = registry.ATTRIBUTES["due_date"].sort_key
935
+ assert sort_key is not None
936
+ rows.sort(key=lambda pair: sort_key(pair[1]))
937
+
938
+ return rows
939
+
940
+
941
+ def item_details(
942
+ list_name: str, item_id: str
943
+ ) -> tuple[TaskliList, TaskliItem]:
944
+ """Return a list and one of its items for the read-only detail view.
945
+
946
+ Parameters
947
+ ----------
948
+ list_name : str
949
+ The list holding the item.
950
+ item_id : str
951
+ The dotted path of the item to show.
952
+
953
+ Returns
954
+ -------
955
+ tuple[TaskliList, TaskliItem]
956
+ The loaded list and the resolved item.
957
+ """
958
+
959
+ storage_dir = resolve_storage_dir()
960
+ task_list = load_list(storage_dir, list_name)
961
+ item = task_list.get_item(item_id)
962
+
963
+ return task_list, item
964
+
965
+
966
+ def _grouped_lists(
967
+ storage_dir: Path,
968
+ list_name: str,
969
+ all_names: list[str],
970
+ item_filter: Filter,
971
+ config: Config,
972
+ ) -> list[TaskliList]:
973
+ """Build filtered views of a list and (optionally) its descendants."""
974
+
975
+ task_list = load_list(storage_dir, list_name)
976
+ if config.auto_prune and task_list.prune():
977
+ save_list(storage_dir, task_list)
978
+
979
+ lists = [
980
+ TaskliList(
981
+ name=list_name,
982
+ color=task_list.color,
983
+ items=task_list.filtered_items(item_filter),
984
+ view_only=True,
985
+ )
986
+ ]
987
+
988
+ # filter each descendant list by the same criteria given to the parent.
989
+ for descendant_name in descendant_list_names(list_name, all_names):
990
+ descendant_list = load_list(storage_dir, descendant_name)
991
+ if config.auto_prune and descendant_list.prune():
992
+ save_list(storage_dir, descendant_list)
993
+
994
+ lists.append(
995
+ TaskliList(
996
+ name=descendant_name,
997
+ color=descendant_list.color,
998
+ items=descendant_list.filtered_items(item_filter),
999
+ view_only=True,
1000
+ )
1001
+ )
1002
+
1003
+ return lists
1004
+
1005
+
1006
+ def _drop_unmatched_lists(lists: list[TaskliList]) -> list[TaskliList]:
1007
+ """Drop empty lists, keeping in-group ancestors of any non-empty one.
1008
+
1009
+ Ancestor retention only sees names present in ``lists``, so callers
1010
+ must pass a full group (as ``_grouped_lists`` builds it).
1011
+ """
1012
+
1013
+ present = {tl.name for tl in lists}
1014
+ keep: set[str] = set()
1015
+ for tl in lists:
1016
+ if tl.items:
1017
+ keep.add(tl.name)
1018
+ # keep the empty ancestors too, so render_list_tree can still
1019
+ # parent this list under its chain.
1020
+ keep.update(a for a in ancestor_chain(tl.name) if a in present)
1021
+
1022
+ return [tl for tl in lists if tl.name in keep]
1023
+
1024
+
1025
+ def list_view(
1026
+ list_name: str,
1027
+ item_filter: Filter,
1028
+ include_descendants: bool,
1029
+ ) -> list[TaskliList]:
1030
+ """Return the filtered tree view for a single list.
1031
+
1032
+ Parameters
1033
+ ----------
1034
+ list_name : str
1035
+ The list to view.
1036
+ item_filter : Filter
1037
+ The criteria to filter items by; empty matches everything.
1038
+ include_descendants : bool
1039
+ Whether to include descendant lists in the view.
1040
+
1041
+ Returns
1042
+ -------
1043
+ list[TaskliList]
1044
+ The list, then any descendants, each filtered. When descendants
1045
+ are included and a filter is active, lists left empty by the
1046
+ filter are dropped (ancestors of a kept list are retained for
1047
+ tree connectivity); an all-empty result is ``[]``.
1048
+ """
1049
+
1050
+ storage_dir = resolve_storage_dir()
1051
+ config = load_config(storage_dir)
1052
+ all_names = list_all_lists(storage_dir) if include_descendants else []
1053
+
1054
+ groups = _grouped_lists(
1055
+ storage_dir, list_name, all_names, item_filter, config
1056
+ )
1057
+ if include_descendants and item_filter.active:
1058
+ return _drop_unmatched_lists(groups)
1059
+
1060
+ return groups
1061
+
1062
+
1063
+ def all_views(item_filter: Filter) -> list[list[TaskliList]]:
1064
+ """Return one filtered tree view per root list on disk.
1065
+
1066
+ Parameters
1067
+ ----------
1068
+ item_filter : Filter
1069
+ The criteria to filter items by; empty matches everything.
1070
+
1071
+ Returns
1072
+ -------
1073
+ list[list[TaskliList]]
1074
+ One group per root list. With a filter active, groups left with
1075
+ no surviving lists are omitted, so the result may be shorter
1076
+ than the number of roots (or empty); empty too when no lists
1077
+ exist.
1078
+ """
1079
+
1080
+ storage_dir = resolve_storage_dir()
1081
+ config = load_config(storage_dir)
1082
+ all_names = list_all_lists(storage_dir)
1083
+
1084
+ roots = [name for name in all_names if "." not in name]
1085
+
1086
+ groups = [
1087
+ _grouped_lists(storage_dir, root, all_names, item_filter, config)
1088
+ for root in roots
1089
+ ]
1090
+ if item_filter.active:
1091
+ kept: list[list[TaskliList]] = []
1092
+ for group in groups:
1093
+ pruned = _drop_unmatched_lists(group)
1094
+ if pruned:
1095
+ kept.append(pruned)
1096
+
1097
+ return kept
1098
+
1099
+ return groups