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/models/tasks.py ADDED
@@ -0,0 +1,764 @@
1
+ """Tasks & task list models."""
2
+
3
+ from datetime import datetime
4
+ from typing import Any
5
+
6
+ from pydantic import BaseModel, Field, field_serializer, field_validator
7
+
8
+ from ..exceptions import InvalidReparentError, ItemNotFoundError
9
+ from . import registry
10
+ from .attributes import Color, Priority, Status
11
+ from .paths import path_key
12
+ from .query import Filter, Sort
13
+
14
+ __all__ = ["TaskliItem", "TaskliList", "walk_items"]
15
+
16
+
17
+ class TaskliItem(BaseModel):
18
+ id: str
19
+ text: str
20
+ status: Status = Status.TODO
21
+ priority: Priority = Priority.MEDIUM
22
+ tags: list[str] = Field(default_factory=list)
23
+ created_at: datetime
24
+ modified_at: datetime | None = None
25
+ completed_at: datetime | None = None
26
+ due_date: datetime | None = None
27
+ description: str | None = None
28
+ children: list["TaskliItem"] = Field(default_factory=list)
29
+
30
+ @field_validator("id")
31
+ @classmethod
32
+ def _validate_id(cls, value: str) -> str:
33
+ path_key(value) # rejects a non-numeric or empty segment.
34
+
35
+ return value
36
+
37
+ @field_serializer("status")
38
+ def _serialize_status(self, value: Status) -> str:
39
+ return value.label
40
+
41
+ @field_serializer("priority")
42
+ def _serialize_priority(self, value: Priority) -> str:
43
+ return value.label
44
+
45
+ @property
46
+ def done(self) -> bool:
47
+ """Whether the item's status is ``Status.DONE``.
48
+
49
+ Returns
50
+ -------
51
+ bool
52
+ True if the item is done.
53
+ """
54
+
55
+ return self.status == Status.DONE
56
+
57
+
58
+ TaskliItem.model_rebuild()
59
+
60
+
61
+ def walk_items(items: list[TaskliItem]) -> list[TaskliItem]:
62
+ """Flatten an item forest to pre-order DFS.
63
+
64
+ Parameters
65
+ ----------
66
+ items : list[TaskliItem]
67
+ The top-level items to walk.
68
+
69
+ Returns
70
+ -------
71
+ list[TaskliItem]
72
+ Every item in the forest, each parent before its own children
73
+ and siblings in list order.
74
+ """
75
+
76
+ flat: list[TaskliItem] = []
77
+ for item in items:
78
+ flat.append(item)
79
+ flat.extend(walk_items(item.children))
80
+
81
+ return flat
82
+
83
+
84
+ def _reindex(items: list[TaskliItem], prefix: str = "") -> None:
85
+ """Renumber a sibling group and its descendants positionally."""
86
+
87
+ for position, item in enumerate(items, start=1):
88
+ item.id = f"{prefix}{position}"
89
+ _reindex(item.children, f"{item.id}.")
90
+
91
+
92
+ def _sort_tree(items: list[TaskliItem], sort: Sort) -> list[TaskliItem]:
93
+ """Sort a sibling group by ``sort``, then recurse into children."""
94
+
95
+ ordered = sorted(items, key=sort.key, reverse=sort.descending)
96
+ for item in ordered:
97
+ item.children = _sort_tree(item.children, sort)
98
+
99
+ return ordered
100
+
101
+
102
+ def _sort_tree_by_path(items: list[TaskliItem]) -> list[TaskliItem]:
103
+ """Reorder a sibling group ascending by path key, recursively."""
104
+
105
+ ordered = sorted(items, key=lambda item: path_key(item.id))
106
+ for item in ordered:
107
+ item.children = _sort_tree_by_path(item.children)
108
+
109
+ return ordered
110
+
111
+
112
+ def _find_container(
113
+ items: list[TaskliItem], target: TaskliItem
114
+ ) -> list[TaskliItem] | None:
115
+ """Return the sibling list holding ``target`` by identity, or None."""
116
+
117
+ if any(item is target for item in items):
118
+ return items
119
+ for item in items:
120
+ found = _find_container(item.children, target)
121
+ if found is not None:
122
+ return found
123
+
124
+ return None
125
+
126
+
127
+ def _prune_tree(
128
+ items: list[TaskliItem],
129
+ ) -> tuple[list[TaskliItem], list[TaskliItem]]:
130
+ """Drop fully-done subtrees bottom-up; return (survivors, removed)."""
131
+
132
+ survivors: list[TaskliItem] = []
133
+ removed: list[TaskliItem] = []
134
+ for item in items:
135
+ kept_children, child_removed = _prune_tree(item.children)
136
+ item.children = kept_children
137
+ removed.extend(child_removed)
138
+ if item.done and not item.children:
139
+ removed.append(item)
140
+ else:
141
+ survivors.append(item)
142
+
143
+ return survivors, removed
144
+
145
+
146
+ def _filter_tree(
147
+ items: list[TaskliItem], item_filter: Filter
148
+ ) -> list[TaskliItem]:
149
+ """Copy items that match ``item_filter`` or have a kept child.
150
+
151
+ Each kept item is a fresh copy with its mutable state (``tags``,
152
+ ``children``) replaced, so the returned forest never aliases the
153
+ originals.
154
+ """
155
+
156
+ kept: list[TaskliItem] = []
157
+ for item in items:
158
+ kept_children = _filter_tree(item.children, item_filter)
159
+ if item_filter.matches(item) or kept_children:
160
+ narrowed = item.model_copy(
161
+ update={"children": kept_children, "tags": list(item.tags)}
162
+ )
163
+ kept.append(narrowed)
164
+
165
+ return kept
166
+
167
+
168
+ def _copy_subtree(src: TaskliItem, dest_item: TaskliItem) -> None:
169
+ """Recursively copy ``src``'s children into ``dest_item``'s subtree."""
170
+
171
+ now = datetime.now()
172
+ for child in src.children:
173
+ attrs: dict[str, Any] = {
174
+ name: getattr(child, name) for name in registry.modifiable("add")
175
+ }
176
+ attrs["tags"] = list(child.tags) # own list object per copy.
177
+ new_child = TaskliItem(
178
+ id=f"{dest_item.id}.{len(dest_item.children) + 1}",
179
+ text=child.text,
180
+ created_at=child.created_at,
181
+ modified_at=now,
182
+ **attrs,
183
+ )
184
+ dest_item.children.append(new_child)
185
+ _copy_subtree(child, new_child)
186
+
187
+
188
+ class TaskliList(BaseModel):
189
+ name: str
190
+ color: Color | None = Color.WHITE
191
+ items: list[TaskliItem] = Field(default_factory=list)
192
+ # a filtered (deep-copied) view storage.save_list must refuse to write.
193
+ view_only: bool = Field(default=False, exclude=True)
194
+
195
+ def display_name(self, delimiter: str = ".") -> str:
196
+ """Render the name with sublist segments joined by ``delimiter``.
197
+
198
+ Parameters
199
+ ----------
200
+ delimiter : str, optional
201
+ Delimiter to substitute for the storage-form ".", by default
202
+ ".".
203
+
204
+ Returns
205
+ -------
206
+ str
207
+ The name in display form.
208
+ """
209
+
210
+ return self.name.replace(".", delimiter)
211
+
212
+ def sort_by(self, sort: Sort) -> None:
213
+ """Sort ``items`` in place under ``sort``.
214
+
215
+ Every item's ``children`` are sorted the same way, recursively.
216
+
217
+ Parameters
218
+ ----------
219
+ sort : Sort
220
+ The sort mode to apply.
221
+ """
222
+
223
+ self.items = _sort_tree(self.items, sort)
224
+
225
+ return None
226
+
227
+ def set_color(self, color: Color) -> None:
228
+ """Set the list's display color.
229
+
230
+ Parameters
231
+ ----------
232
+ color : Color
233
+ The new color.
234
+ """
235
+
236
+ self.color = color
237
+
238
+ return None
239
+
240
+ def reindex(self) -> None:
241
+ """Renumber items to their positional dotted paths.
242
+
243
+ Top-level items become ``"1"``, ``"2"``, ...; a child of
244
+ ``"1"`` becomes ``"1.1"``, ``"1.2"``, ...; recursively. Ids are
245
+ mutated in place so held references survive.
246
+ """
247
+
248
+ _reindex(self.items)
249
+
250
+ return None
251
+
252
+ def sort_by_index(self) -> None:
253
+ """Reorder each sibling group ascending by its current path."""
254
+
255
+ self.items = _sort_tree_by_path(self.items)
256
+
257
+ return None
258
+
259
+ def resort(self, sort: Sort) -> None:
260
+ """Sort ``items`` by ``sort``, then reindex to match the new order.
261
+
262
+ Parameters
263
+ ----------
264
+ sort : Sort
265
+ The sort mode to apply.
266
+ """
267
+
268
+ self.sort_by(sort)
269
+ self.reindex()
270
+
271
+ return None
272
+
273
+ def add_item(
274
+ self,
275
+ text: str,
276
+ attrs: dict[str, Any] | None = None,
277
+ *,
278
+ created_at: datetime | None = None,
279
+ modified_at: datetime | None = None,
280
+ parent_path: str | None = None,
281
+ ) -> TaskliItem:
282
+ """Create and append a new item, returning it.
283
+
284
+ Parameters
285
+ ----------
286
+ text : str
287
+ The item's description.
288
+ attrs : dict[str, Any] | None, optional
289
+ Typed field values keyed by pydantic field name (e.g.
290
+ ``{"priority": Priority.HIGH, "tags": ["x"]}``). Present
291
+ keys are validated and absent ones defaulted by the
292
+ ``TaskliItem`` constructor. By default none.
293
+ created_at : datetime | None, optional
294
+ Creation timestamp, by default ``datetime.now()``. Set by
295
+ ``copy_item`` to preserve the source item's timestamp.
296
+ modified_at : datetime | None, optional
297
+ Last-modified timestamp, by default the resolved
298
+ ``created_at``. Set by ``copy_item`` to the time of copy.
299
+ parent_path : str | None, optional
300
+ The dotted path of an existing item to nest the new item
301
+ under. By default none, appending at the top level. The
302
+ provisional child id is finalised by a later
303
+ ``resort``/``reindex``.
304
+
305
+ Returns
306
+ -------
307
+ TaskliItem
308
+ The newly created item.
309
+ """
310
+
311
+ resolved_created_at = created_at or datetime.now()
312
+ if parent_path is None:
313
+ new_id = str(len(self.items) + 1)
314
+ container = self.items
315
+ else:
316
+ parent = self.get_item(parent_path)
317
+ new_id = f"{parent.id}.{len(parent.children) + 1}"
318
+ container = parent.children
319
+ item = TaskliItem(
320
+ id=new_id,
321
+ text=text,
322
+ created_at=resolved_created_at,
323
+ modified_at=modified_at or resolved_created_at,
324
+ **(attrs or {}),
325
+ )
326
+ container.append(item)
327
+
328
+ return item
329
+
330
+ def get_item(self, item_id: str | int) -> TaskliItem:
331
+ """Return the item anywhere in the tree with the given id.
332
+
333
+ Parameters
334
+ ----------
335
+ item_id : str | int
336
+ The item's dotted path; an ``int`` is normalised to its
337
+ string form for legacy call sites.
338
+
339
+ Returns
340
+ -------
341
+ TaskliItem
342
+ The matching item.
343
+ """
344
+
345
+ path = str(item_id)
346
+ try:
347
+ return next(
348
+ item for item in walk_items(self.items) if item.id == path
349
+ )
350
+ except StopIteration as e:
351
+ raise ItemNotFoundError(
352
+ f"no item with id {item_id} in list '{self.name}'."
353
+ ) from e
354
+
355
+ def mark_done_ref(self, item: TaskliItem) -> TaskliItem:
356
+ """Mark a resolved item done and set its completion timestamp.
357
+
358
+ Parameters
359
+ ----------
360
+ item : TaskliItem
361
+ The item to mark done.
362
+
363
+ Returns
364
+ -------
365
+ TaskliItem
366
+ The updated item.
367
+ """
368
+
369
+ now = datetime.now()
370
+ item.status = Status.DONE
371
+ item.completed_at = now
372
+ item.modified_at = now
373
+
374
+ return item
375
+
376
+ def mark_done(self, item_id: str | int) -> TaskliItem:
377
+ """Mark an item done and set its completion timestamp.
378
+
379
+ Parameters
380
+ ----------
381
+ item_id : str | int
382
+ The item's id.
383
+
384
+ Returns
385
+ -------
386
+ TaskliItem
387
+ The updated item.
388
+ """
389
+
390
+ return self.mark_done_ref(self.get_item(item_id))
391
+
392
+ def mark_undone_ref(self, item: TaskliItem) -> TaskliItem:
393
+ """Reset a resolved item to todo and clear its completion timestamp.
394
+
395
+ Resets from either ``Status.DONE`` or ``Status.IN_PROGRESS``.
396
+
397
+ Parameters
398
+ ----------
399
+ item : TaskliItem
400
+ The item to reset.
401
+
402
+ Returns
403
+ -------
404
+ TaskliItem
405
+ The updated item.
406
+ """
407
+
408
+ item.status = Status.TODO
409
+ item.completed_at = None
410
+ item.modified_at = datetime.now()
411
+
412
+ return item
413
+
414
+ def mark_undone(self, item_id: str | int) -> TaskliItem:
415
+ """Reset an item to todo and clear its completion timestamp.
416
+
417
+ Resets from either ``Status.DONE`` or ``Status.IN_PROGRESS``.
418
+
419
+ Parameters
420
+ ----------
421
+ item_id : str | int
422
+ The item's id.
423
+
424
+ Returns
425
+ -------
426
+ TaskliItem
427
+ The updated item.
428
+ """
429
+
430
+ return self.mark_undone_ref(self.get_item(item_id))
431
+
432
+ def mark_in_progress_ref(self, item: TaskliItem) -> TaskliItem:
433
+ """Mark a resolved item in progress; clear its completion timestamp.
434
+
435
+ Parameters
436
+ ----------
437
+ item : TaskliItem
438
+ The item to mark in progress.
439
+
440
+ Returns
441
+ -------
442
+ TaskliItem
443
+ The updated item.
444
+ """
445
+
446
+ item.status = Status.IN_PROGRESS
447
+ item.completed_at = None
448
+ item.modified_at = datetime.now()
449
+
450
+ return item
451
+
452
+ def mark_in_progress(self, item_id: str | int) -> TaskliItem:
453
+ """Mark an item in progress and clear its completion timestamp.
454
+
455
+ Parameters
456
+ ----------
457
+ item_id : str | int
458
+ The item's id.
459
+
460
+ Returns
461
+ -------
462
+ TaskliItem
463
+ The updated item.
464
+ """
465
+
466
+ return self.mark_in_progress_ref(self.get_item(item_id))
467
+
468
+ def remove_item_ref(self, item: TaskliItem) -> None:
469
+ """Remove a resolved item and its subtree, then reindex.
470
+
471
+ Parameters
472
+ ----------
473
+ item : TaskliItem
474
+ The item to remove; its children travel with it.
475
+ """
476
+
477
+ container = _find_container(self.items, item)
478
+ if container is None:
479
+ raise ValueError("item is not in the list.")
480
+ container[:] = [
481
+ existing for existing in container if existing is not item
482
+ ]
483
+ self.reindex()
484
+
485
+ def remove_item(self, item_id: str | int) -> None:
486
+ """Remove an item and its subtree from the list.
487
+
488
+ Parameters
489
+ ----------
490
+ item_id : str | int
491
+ The item's id.
492
+ """
493
+
494
+ self.remove_item_ref(self.get_item(item_id))
495
+
496
+ def prune(self) -> list[TaskliItem]:
497
+ """Remove every item whose entire subtree is done.
498
+
499
+ A done item is kept when it still has a surviving un-done
500
+ descendant; done leaves are always removed.
501
+
502
+ Returns
503
+ -------
504
+ list[TaskliItem]
505
+ Every removed item, as one flat list.
506
+ """
507
+
508
+ survivors, removed = _prune_tree(self.items)
509
+ self.items = survivors
510
+ self.reindex()
511
+
512
+ return removed
513
+
514
+ def edit_item(
515
+ self, item_id: str | int, attrs: dict[str, object]
516
+ ) -> TaskliItem:
517
+ """Apply a mapping of typed field values to an existing item.
518
+
519
+ Assignment is a bare ``setattr`` with no pydantic validation
520
+ (``TaskliItem`` has no ``validate_assignment``); callers are
521
+ responsible for passing already-valid typed values.
522
+
523
+ Parameters
524
+ ----------
525
+ item_id : str | int
526
+ The item's id.
527
+ attrs : dict[str, object]
528
+ Field values keyed by pydantic field name. An empty
529
+ mapping is a no-op and leaves ``modified_at`` untouched.
530
+
531
+ Returns
532
+ -------
533
+ TaskliItem
534
+ The updated item.
535
+ """
536
+
537
+ item = self.get_item(item_id)
538
+ for name, value in attrs.items():
539
+ setattr(item, name, value)
540
+ if attrs:
541
+ item.modified_at = datetime.now()
542
+
543
+ return item
544
+
545
+ def filtered_items(self, item_filter: Filter) -> list[TaskliItem]:
546
+ """Return a forest of fresh copies narrowed to matching subtrees.
547
+
548
+ An item is kept when it matches ``item_filter`` or any of its
549
+ descendants does. Each kept item is a copy with its mutable state
550
+ replaced, so the originals are left untouched -- these views are
551
+ for rendering only and must never be persisted.
552
+
553
+ Parameters
554
+ ----------
555
+ item_filter : Filter
556
+ The filter to apply; an empty filter keeps every item.
557
+
558
+ Returns
559
+ -------
560
+ list[TaskliItem]
561
+ The matching items as independent copies.
562
+ """
563
+
564
+ return _filter_tree(self.items, item_filter)
565
+
566
+ def add_tags(self, item_id: str | int, tags: list[str]) -> TaskliItem:
567
+ """Append new tags to an item's existing tags, deduplicated.
568
+
569
+ Parameters
570
+ ----------
571
+ item_id : str | int
572
+ The item's id.
573
+ tags : list[str]
574
+ Tags to add, in addition to any the item already has.
575
+
576
+ Returns
577
+ -------
578
+ TaskliItem
579
+ The updated item.
580
+ """
581
+
582
+ item = self.get_item(item_id)
583
+ item.tags = item.tags + [t for t in tags if t not in item.tags]
584
+ item.modified_at = datetime.now()
585
+
586
+ return item
587
+
588
+ def copy_item_ref(
589
+ self, item: TaskliItem, target: "TaskliList"
590
+ ) -> TaskliItem:
591
+ """Copy a resolved item and its subtree into another list.
592
+
593
+ The copied root keeps the source item's ``created_at``; only
594
+ ``modified_at`` is stamped with the time of copy. Descendants
595
+ are recreated as fresh items with their status reset to the
596
+ ``TaskliItem`` default.
597
+
598
+ Parameters
599
+ ----------
600
+ item : TaskliItem
601
+ The item to copy.
602
+ target : TaskliList
603
+ The list to copy the item into.
604
+
605
+ Returns
606
+ -------
607
+ TaskliItem
608
+ The newly created root item in ``target``.
609
+ """
610
+
611
+ # the add-settable attributes are exactly the ones a copy should
612
+ # carry today; test_add_modifiers_in_column_order pins the set.
613
+ attrs: dict[str, Any] = {
614
+ name: getattr(item, name) for name in registry.modifiable("add")
615
+ }
616
+ attrs["tags"] = list(item.tags) # own list object per copy.
617
+
618
+ new_item = target.add_item(
619
+ item.text,
620
+ attrs,
621
+ created_at=item.created_at,
622
+ modified_at=datetime.now(),
623
+ )
624
+ _copy_subtree(item, new_item)
625
+
626
+ return new_item
627
+
628
+ def copy_item(
629
+ self, item_id: str | int, target: "TaskliList"
630
+ ) -> TaskliItem:
631
+ """Copy an item and its subtree into another list.
632
+
633
+ The copied root keeps the source item's ``created_at``; only
634
+ ``modified_at`` is stamped with the time of copy.
635
+
636
+ Parameters
637
+ ----------
638
+ item_id : str | int
639
+ The item's id in ``self``.
640
+ target : TaskliList
641
+ The list to copy the item into.
642
+
643
+ Returns
644
+ -------
645
+ TaskliItem
646
+ The newly created root item in ``target``.
647
+ """
648
+
649
+ return self.copy_item_ref(self.get_item(item_id), target)
650
+
651
+ def move_item_ref(
652
+ self, item: TaskliItem, target: "TaskliList"
653
+ ) -> TaskliItem:
654
+ """Move a resolved item into another list, removing it from ``self``.
655
+
656
+ Parameters
657
+ ----------
658
+ item : TaskliItem
659
+ The item to move; its subtree travels with it.
660
+ target : TaskliList
661
+ The list to move the item into.
662
+
663
+ Returns
664
+ -------
665
+ TaskliItem
666
+ The newly created root item in ``target``.
667
+ """
668
+
669
+ moved = self.copy_item_ref(item, target)
670
+ self.remove_item_ref(item)
671
+
672
+ return moved
673
+
674
+ def move_item(
675
+ self, item_id: str | int, target: "TaskliList"
676
+ ) -> TaskliItem:
677
+ """Move an item into another list, removing it from ``self``.
678
+
679
+ Parameters
680
+ ----------
681
+ item_id : str | int
682
+ The item's id in ``self``.
683
+ target : TaskliList
684
+ The list to move the item into.
685
+
686
+ Returns
687
+ -------
688
+ TaskliItem
689
+ The newly created root item in ``target``.
690
+ """
691
+
692
+ return self.move_item_ref(self.get_item(item_id), target)
693
+
694
+ def reparent_item_ref(
695
+ self, item: TaskliItem, parent: TaskliItem | None
696
+ ) -> TaskliItem:
697
+ """Re-nest a resolved item under ``parent``, then reindex.
698
+
699
+ This is an identity splice: the same ``TaskliItem`` object (and
700
+ its whole subtree) is detached and re-appended, so ``status``,
701
+ ``completed_at``, ``modified_at``, and ``created_at`` are all
702
+ left untouched; only ``item.id`` is renumbered by ``reindex``.
703
+
704
+ Parameters
705
+ ----------
706
+ item : TaskliItem
707
+ The item to move; its children travel with it.
708
+ parent : TaskliItem | None
709
+ The item to nest ``item`` under, or ``None`` for the top
710
+ level.
711
+
712
+ Returns
713
+ -------
714
+ TaskliItem
715
+ The re-nested item.
716
+ """
717
+
718
+ if parent is not None and (
719
+ parent is item
720
+ or any(node is parent for node in walk_items(item.children))
721
+ ):
722
+ message = (
723
+ f"cannot nest #{item.id} under #{parent.id}: "
724
+ "a task cannot be its own ancestor."
725
+ )
726
+ raise InvalidReparentError(message)
727
+ container = _find_container(self.items, item)
728
+ if container is None:
729
+ raise ValueError("item is not in the list.")
730
+ container[:] = [
731
+ existing for existing in container if existing is not item
732
+ ]
733
+ destination = self.items if parent is None else parent.children
734
+ destination.append(item)
735
+ self.reindex()
736
+
737
+ return item
738
+
739
+ def reparent_item(
740
+ self, item_id: str | int, parent_path: str | None
741
+ ) -> TaskliItem:
742
+ """Re-nest an item under another item in the same list.
743
+
744
+ Parameters
745
+ ----------
746
+ item_id : str | int
747
+ The item's id.
748
+ parent_path : str | None
749
+ The dotted path of the item to nest under, or ``None`` to
750
+ un-nest to the top level.
751
+
752
+ Returns
753
+ -------
754
+ TaskliItem
755
+ The re-nested item.
756
+ """
757
+
758
+ item = self.get_item(item_id)
759
+ if parent_path is None:
760
+ parent = None
761
+ else:
762
+ parent = self.get_item(parent_path)
763
+
764
+ return self.reparent_item_ref(item, parent)