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/query.py ADDED
@@ -0,0 +1,250 @@
1
+ """Filter, criterion, and sort value objects for querying items."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ from datetime import timedelta
8
+ from typing import TYPE_CHECKING
9
+
10
+ from ..exceptions import InvalidConfigValueError
11
+ from . import registry
12
+ from .attributes import Operator
13
+ from .dates import midnight, parse_agenda_window, parse_due_date, today
14
+
15
+ if TYPE_CHECKING:
16
+ from _typeshed import SupportsRichComparison
17
+
18
+ from .tasks import TaskliItem
19
+
20
+ __all__ = [
21
+ "Criterion",
22
+ "Filter",
23
+ "Sort",
24
+ "agenda_criteria",
25
+ "due_to_criteria",
26
+ ]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Criterion:
31
+ attr_key: str
32
+ operator: Operator
33
+ operand: object
34
+
35
+ def matches(self, item: TaskliItem) -> bool:
36
+ """Whether ``item`` satisfies this criterion.
37
+
38
+ Parameters
39
+ ----------
40
+ item : TaskliItem
41
+ The item to test.
42
+
43
+ Returns
44
+ -------
45
+ bool
46
+ Whether the item's ``attr_key`` value satisfies the operand.
47
+ """
48
+
49
+ value = getattr(item, self.attr_key)
50
+
51
+ return self.operator.compare(value, self.operand)
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class Filter:
56
+ criteria: tuple[Criterion, ...] = ()
57
+ any_of: tuple[tuple[Criterion, ...], ...] = ()
58
+
59
+ @property
60
+ def active(self) -> bool:
61
+ """Whether this filter carries any criteria or OR-groups."""
62
+
63
+ return bool(self.criteria or self.any_of)
64
+
65
+ def matches(self, item: TaskliItem) -> bool:
66
+ """Whether ``item`` satisfies every criterion and any OR-group.
67
+
68
+ ``criteria`` are AND-combined. When ``any_of`` is non-empty, the
69
+ item must also fully match at least one of its groups, each group
70
+ being an AND-combined tuple of criteria. An empty filter matches
71
+ every item.
72
+
73
+ Parameters
74
+ ----------
75
+ item : TaskliItem
76
+ The item to test.
77
+
78
+ Returns
79
+ -------
80
+ bool
81
+ True when all criteria match and either ``any_of`` is empty or
82
+ some group fully matches.
83
+ """
84
+
85
+ if not all(c.matches(item) for c in self.criteria):
86
+ return False
87
+
88
+ return not self.any_of or any(
89
+ all(c.matches(item) for c in group) for group in self.any_of
90
+ )
91
+
92
+ def apply(self, items: Iterable[TaskliItem]) -> list[TaskliItem]:
93
+ """Return the items that satisfy this filter, order preserved.
94
+
95
+ Flat: each item is tested on its own, with no descent into
96
+ ``children``. ``TaskliList.filtered_items`` is the tree-aware
97
+ entry point that keeps an item whose descendant matches.
98
+
99
+ Parameters
100
+ ----------
101
+ items : Iterable[TaskliItem]
102
+ The items to filter.
103
+
104
+ Returns
105
+ -------
106
+ list[TaskliItem]
107
+ The matching items.
108
+ """
109
+
110
+ return [i for i in items if self.matches(i)]
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Sort:
115
+ attr_key: str
116
+ descending: bool = False
117
+
118
+ def __post_init__(self) -> None:
119
+ """Reject an ``attr_key`` that names no known sort mode."""
120
+
121
+ if self.attr_key not in registry.sortable():
122
+ raise InvalidConfigValueError(
123
+ f"'{self.attr_key}' is not a valid sort key."
124
+ )
125
+
126
+ def key(self, item: TaskliItem) -> SupportsRichComparison:
127
+ """Return ``item``'s sort key under this sort mode.
128
+
129
+ Parameters
130
+ ----------
131
+ item : TaskliItem
132
+ The item to derive a sort key for.
133
+
134
+ Returns
135
+ -------
136
+ SupportsRichComparison
137
+ The value to sort the item by.
138
+ """
139
+
140
+ sort_key = registry.ATTRIBUTES[self.attr_key].sort_key
141
+ assert sort_key is not None # guaranteed by __post_init__.
142
+
143
+ return sort_key(item)
144
+
145
+ @classmethod
146
+ def from_default_sort(cls, value: str) -> Sort:
147
+ """Build a ``Sort`` from a config ``default_sort`` value.
148
+
149
+ Parameters
150
+ ----------
151
+ value : str
152
+ The configured default sort mode.
153
+
154
+ Returns
155
+ -------
156
+ Sort
157
+ The matching sort, using the attribute's registered default
158
+ direction.
159
+ """
160
+
161
+ attr = registry.sortable().get(value)
162
+ if attr is None:
163
+ raise InvalidConfigValueError(
164
+ f"'{value}' is not a valid sort key."
165
+ )
166
+
167
+ return cls(value, descending=attr.sort_descending)
168
+
169
+
170
+ def due_to_criteria(raw: str) -> tuple[Criterion, ...]:
171
+ """Build the due-date view criteria for a ``--due`` token.
172
+
173
+ ``overdue`` matches not-done items due before today; ``none``
174
+ matches not-done items with no due date; any other token is parsed
175
+ as a single day and matched exactly.
176
+
177
+ Parameters
178
+ ----------
179
+ raw : str
180
+ The user-supplied ``--due`` value.
181
+
182
+ Returns
183
+ -------
184
+ tuple[Criterion, ...]
185
+ The criteria a due-date filter should AND together.
186
+ """
187
+
188
+ if raw.strip().casefold() == "overdue":
189
+ return (
190
+ Criterion("due_date", Operator.LT, midnight(today())),
191
+ Criterion("done", Operator.EQ, False),
192
+ )
193
+
194
+ if raw.strip().casefold() == "none":
195
+ return (
196
+ Criterion("due_date", Operator.EQ, None),
197
+ Criterion("done", Operator.EQ, False),
198
+ )
199
+
200
+ # parse_due_date midnight-normalizes its result, so this exact-datetime
201
+ # match agrees with _due_render_style's calendar-day comparison.
202
+ return (Criterion("due_date", Operator.EQ, parse_due_date(raw)),)
203
+
204
+
205
+ def agenda_criteria(
206
+ window: str, *, include_overdue: bool
207
+ ) -> tuple[Criterion, ...]:
208
+ """Build the criteria for a ``--agenda`` window.
209
+
210
+ ``overdue`` matches not-done items due before today. Any other
211
+ token bounds a forward-looking, inclusive window of not-done items
212
+ due from today through ``today + N`` days (``today`` is ``N=0``,
213
+ ``week`` is ``N=7``). When ``include_overdue`` is true, that window
214
+ also takes in not-done items due before today, so the window's
215
+ lower bound is dropped and only its upper bound is applied.
216
+
217
+ Parameters
218
+ ----------
219
+ window : str
220
+ The user-supplied ``--agenda`` value.
221
+ include_overdue : bool
222
+ Whether a non-``overdue`` window also includes items already
223
+ past due (``Config.agenda_include_overdue``).
224
+
225
+ Returns
226
+ -------
227
+ tuple[Criterion, ...]
228
+ The criteria an agenda filter should AND together.
229
+ """
230
+
231
+ keyword = parse_agenda_window(window)
232
+ if keyword == "overdue":
233
+ return due_to_criteria("overdue")
234
+
235
+ days = (
236
+ 0 if keyword == "today" else 7 if keyword == "week" else int(keyword)
237
+ )
238
+ start = midnight(today())
239
+ end = start + timedelta(days=days + 1)
240
+
241
+ lower = (
242
+ ()
243
+ if include_overdue
244
+ else (Criterion("due_date", Operator.GTE, start),)
245
+ )
246
+ return (
247
+ *lower,
248
+ Criterion("due_date", Operator.LT, end),
249
+ Criterion("done", Operator.EQ, False),
250
+ )
@@ -0,0 +1,215 @@
1
+ """Per-attribute domain and render metadata, collected into one table."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+ from functools import cache
9
+ from typing import TYPE_CHECKING, Literal
10
+
11
+ from .attributes import Operator, Priority
12
+ from .dates import parse_due_date, today
13
+
14
+ if TYPE_CHECKING:
15
+ from _typeshed import SupportsRichComparison
16
+
17
+ from .tasks import TaskliItem
18
+
19
+ _Justify = Literal["default", "left", "center", "right", "full"]
20
+
21
+ __all__ = [
22
+ "ATTRIBUTES",
23
+ "Attribute",
24
+ "RenderColumn",
25
+ "filterable",
26
+ "modifiable",
27
+ "renderable",
28
+ "sortable",
29
+ ]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Attribute:
34
+ name: str
35
+ filter_operators: tuple[Operator, ...] = ()
36
+ filter_default_operator: Operator | None = None
37
+ sort_key: Callable[[TaskliItem], SupportsRichComparison] | None = None
38
+ sort_descending: bool = False
39
+ column_header: str | None = None
40
+ column_justify: _Justify = "left"
41
+ render_format: Callable[[TaskliItem], str] | None = None
42
+ render_style: Callable[[TaskliItem], str | None] | None = None
43
+ parse: Callable[[str], object] | None = None
44
+ modifier_ops: frozenset[str] = frozenset()
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class RenderColumn:
49
+ header: str
50
+ justify: _Justify
51
+ format: Callable[[TaskliItem], str]
52
+ style: Callable[[TaskliItem], str | None] | None
53
+
54
+
55
+ def _due_render_style(item: TaskliItem) -> str | None:
56
+ """Return the rich style for an item's due-date cell."""
57
+
58
+ if item.due_date is None or item.done:
59
+ return None
60
+ due, now = item.due_date.date(), today()
61
+ if due < now:
62
+ return "red"
63
+ if due == now:
64
+ return "yellow"
65
+
66
+ return None
67
+
68
+
69
+ # insertion order is the render column order.
70
+ ATTRIBUTES: dict[str, Attribute] = {
71
+ "id": Attribute(name="id"),
72
+ "status": Attribute(name="status"),
73
+ "text": Attribute(
74
+ name="text",
75
+ modifier_ops=frozenset({"edit"}),
76
+ ),
77
+ "description": Attribute(
78
+ name="description",
79
+ parse=lambda s: s or None,
80
+ modifier_ops=frozenset({"add", "edit"}),
81
+ ),
82
+ "priority": Attribute(
83
+ name="priority",
84
+ column_header="Priority",
85
+ column_justify="left",
86
+ render_format=lambda item: item.priority.label,
87
+ render_style=lambda item: item.priority.color,
88
+ filter_operators=(Operator.EQ,),
89
+ filter_default_operator=Operator.EQ,
90
+ sort_key=lambda item: item.priority.index,
91
+ sort_descending=True,
92
+ parse=lambda s: Priority[s.upper()],
93
+ modifier_ops=frozenset({"add", "edit"}),
94
+ ),
95
+ "tags": Attribute(
96
+ name="tags",
97
+ column_header="Tags",
98
+ column_justify="left",
99
+ render_format=lambda item: ", ".join(item.tags),
100
+ filter_operators=(Operator.CONTAINS,),
101
+ filter_default_operator=Operator.CONTAINS,
102
+ sort_key=lambda item: (
103
+ "".join(item.tags) == "",
104
+ ",".join(sorted(item.tags)),
105
+ ),
106
+ modifier_ops=frozenset({"add", "edit"}),
107
+ ),
108
+ "due_date": Attribute(
109
+ name="due_date",
110
+ column_header="Due",
111
+ column_justify="left",
112
+ render_format=lambda item: (
113
+ item.due_date.date().isoformat() if item.due_date else ""
114
+ ),
115
+ render_style=_due_render_style,
116
+ # the operators due_to_criteria emits. The view path routes --due
117
+ # through the due_date spec's per-token to_criteria, not the generic
118
+ # single-operator filter.
119
+ filter_operators=(Operator.EQ, Operator.LT),
120
+ filter_default_operator=Operator.EQ,
121
+ sort_key=lambda item: (
122
+ item.due_date is None,
123
+ item.due_date or datetime.max,
124
+ ),
125
+ sort_descending=False,
126
+ parse=parse_due_date,
127
+ modifier_ops=frozenset({"add", "edit"}),
128
+ ),
129
+ "created_at": Attribute(
130
+ name="created_at",
131
+ sort_key=lambda item: item.created_at,
132
+ ),
133
+ "color": Attribute(name="color"),
134
+ }
135
+
136
+
137
+ @cache
138
+ def sortable() -> dict[str, Attribute]:
139
+ """Return the attributes that define a sort key, keyed by name.
140
+
141
+ Returns
142
+ -------
143
+ dict[str, Attribute]
144
+ Every entry whose ``sort_key`` is set, in ``ATTRIBUTES`` order.
145
+ """
146
+
147
+ return {name: attr for name, attr in ATTRIBUTES.items() if attr.sort_key}
148
+
149
+
150
+ @cache
151
+ def renderable() -> list[RenderColumn]:
152
+ """Return the resolved table columns, in column order.
153
+
154
+ Returns
155
+ -------
156
+ list[RenderColumn]
157
+ One column per attribute carrying both a ``column_header`` and a
158
+ ``render_format``, in ``ATTRIBUTES`` order.
159
+ """
160
+
161
+ columns: list[RenderColumn] = []
162
+ for attr in ATTRIBUTES.values():
163
+ if attr.column_header is None or attr.render_format is None:
164
+ continue
165
+ columns.append(
166
+ RenderColumn(
167
+ attr.column_header,
168
+ attr.column_justify,
169
+ attr.render_format,
170
+ attr.render_style,
171
+ )
172
+ )
173
+
174
+ return columns
175
+
176
+
177
+ @cache
178
+ def filterable() -> dict[str, Attribute]:
179
+ """Return the attributes that can be filtered, keyed by name.
180
+
181
+ Returns
182
+ -------
183
+ dict[str, Attribute]
184
+ Every entry whose ``filter_operators`` is non-empty, in
185
+ ``ATTRIBUTES`` order.
186
+ """
187
+
188
+ return {
189
+ name: attr
190
+ for name, attr in ATTRIBUTES.items()
191
+ if attr.filter_operators
192
+ }
193
+
194
+
195
+ @cache
196
+ def modifiable(op: str) -> dict[str, Attribute]:
197
+ """Return the attributes settable as an item modifier on ``op``.
198
+
199
+ Parameters
200
+ ----------
201
+ op : str
202
+ The item-action op name, e.g. ``"add"`` or ``"edit"``.
203
+
204
+ Returns
205
+ -------
206
+ dict[str, Attribute]
207
+ Every entry whose ``modifier_ops`` contains ``op``, in
208
+ ``ATTRIBUTES`` order.
209
+ """
210
+
211
+ return {
212
+ name: attr
213
+ for name, attr in ATTRIBUTES.items()
214
+ if op in attr.modifier_ops
215
+ }