-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_types.py
More file actions
713 lines (550 loc) · 23.8 KB
/
Copy path_types.py
File metadata and controls
713 lines (550 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
"""Type definitions for taskmark."""
from __future__ import annotations
import dataclasses
from collections.abc import Iterator
from dataclasses import dataclass, field
from enum import StrEnum
from pathlib import Path
from typing import Any, ClassVar, overload
class TaskState(StrEnum):
"""Task completion states."""
OPEN = "open"
DONE = "done"
CANCELLED = "cancelled"
BLOCKED = "blocked"
class ParseError(Exception):
"""Raised when parsing fails or warnings exist in strict mode."""
@dataclass
class Task:
"""Task representation with dict-like access to content fields.
Content fields are accessible via dict interface: task["title"], dict(task)
Location and provenance fields are accessible via attributes only.
"""
# Required fields
state: str
title: str
# Optional metadata
priority: str | None = None
estimate_minutes: int | None = None
due_date: str | None = None
done_date: str | None = None
planned_date: str | None = None
paused_date: str | None = None
created_date: str | None = None
started_date: str | None = None
recurrence: str | None = None
# List fields
assignees: list[str] = field(default_factory=list)
tags: list[str] = field(default_factory=list)
custom_fields: dict[str, str] = field(default_factory=dict)
# Project hierarchy as path string: "company/dept/team"
project_path: str | None = None
# Nested subtasks
subtasks: list[Task] = field(default_factory=list)
# Location info (attribute access only)
file: Path | None = None
line: int | None = None
indent: int = 0
# Provenance fields (attribute access only)
inherited_project_path: str | None = None
explicit_project_path: str | None = None
inherited_tags: list[str] = field(default_factory=list)
explicit_tags: list[str] = field(default_factory=list)
inherited_assignees: list[str] = field(default_factory=list)
explicit_assignees: list[str] = field(default_factory=list)
inherited_custom_fields: dict[str, str] = field(default_factory=dict)
explicit_custom_fields: dict[str, str] = field(default_factory=dict)
# ─────────────────────────────────────────────────────────────
# Field Categories
# ─────────────────────────────────────────────────────────────
_CONTENT_FIELDS: ClassVar[tuple[str, ...]] = (
"state",
"title",
"priority",
"due_date",
"planned_date",
"estimate_minutes",
"recurrence",
"created_date",
"started_date",
"done_date",
"paused_date",
"assignees",
"project_path",
"tags",
"custom_fields",
"subtasks",
)
_LOCATION_FIELDS: ClassVar[tuple[str, ...]] = ("file", "line", "indent")
_PROVENANCE_FIELDS: ClassVar[tuple[str, ...]] = (
"inherited_project_path",
"explicit_project_path",
"inherited_tags",
"explicit_tags",
"inherited_assignees",
"explicit_assignees",
"inherited_custom_fields",
"explicit_custom_fields",
)
# ─────────────────────────────────────────────────────────────
# Dict-like Interface (content fields only)
# ─────────────────────────────────────────────────────────────
def __getitem__(self, key: str) -> Any:
"""Get content field by key."""
if key not in self._CONTENT_FIELDS:
raise KeyError(key)
return getattr(self, key)
def __iter__(self) -> Iterator[str]:
"""Iterate over content field names."""
return iter(self._CONTENT_FIELDS)
def __len__(self) -> int:
"""Number of content fields."""
return len(self._CONTENT_FIELDS)
def __contains__(self, key: object) -> bool:
"""Check if key is a content field."""
return key in self._CONTENT_FIELDS
def keys(self) -> tuple[str, ...]:
"""Content field names."""
return self._CONTENT_FIELDS
def values(self) -> tuple[Any, ...]:
"""Content field values."""
return tuple(getattr(self, f) for f in self._CONTENT_FIELDS)
def items(self) -> tuple[tuple[str, Any], ...]:
"""Content field (name, value) pairs."""
return tuple((f, getattr(self, f)) for f in self._CONTENT_FIELDS)
@overload
def get(self, key: str) -> Any: ...
@overload
def get(self, key: str, default: Any) -> Any: ...
def get(self, key: str, default: Any = None) -> Any:
"""Get content field by key with default."""
if key not in self._CONTENT_FIELDS:
return default
return getattr(self, key)
# ─────────────────────────────────────────────────────────────
# Equality Methods
# ─────────────────────────────────────────────────────────────
def content_eq(self, other: Task) -> bool:
"""Compare by semantic content only (ignores provenance & location)."""
if not isinstance(other, Task):
return False
for fname in self._CONTENT_FIELDS:
if fname == "subtasks":
self_subs = getattr(self, fname)
other_subs = getattr(other, fname)
if len(self_subs) != len(other_subs):
return False
if not all(s.content_eq(o) for s, o in zip(self_subs, other_subs, strict=True)):
return False
elif getattr(self, fname) != getattr(other, fname):
return False
return True
def content_hash(self) -> int:
"""Hash based on content only - for deduplication."""
def _hashable(v: Any) -> Any:
if isinstance(v, list):
return tuple(v)
if isinstance(v, dict):
return tuple(sorted(v.items()))
return v
return hash(
tuple(_hashable(getattr(self, f)) for f in self._CONTENT_FIELDS if f != "subtasks")
)
def identical_to(self, other: Task) -> bool:
"""Strict equality including provenance and location."""
if not isinstance(other, Task):
return False
return dataclasses.asdict(self) == dataclasses.asdict(other)
# ─────────────────────────────────────────────────────────────
# Serialization
# ─────────────────────────────────────────────────────────────
def to_dict(
self,
include_location: bool = False,
include_provenance: bool = False,
exclude_empty: bool = True,
) -> dict[str, Any]:
"""Serialize to dict.
Args:
include_location: Include file, line, indent fields
include_provenance: Include inherited_*/explicit_* fields
exclude_empty: Omit None values and empty lists/dicts
"""
fields: list[str] = list(self._CONTENT_FIELDS)
if include_location:
fields.extend(self._LOCATION_FIELDS)
if include_provenance:
fields.extend(self._PROVENANCE_FIELDS)
result: dict[str, Any] = {}
for fname in fields:
value = getattr(self, fname)
if exclude_empty:
if value is None:
continue
if isinstance(value, (list, dict)) and not value:
continue
if fname == "subtasks" and value:
value = [
t.to_dict(include_location, include_provenance, exclude_empty) for t in value
]
if isinstance(value, Path):
value = str(value)
result[fname] = value
return result
# ─────────────────────────────────────────────────────────────
# Markdown Serialization
# ─────────────────────────────────────────────────────────────
def to_markdown(self, use_explicit_only: bool = True) -> str:
"""Serialize task to markdown (without indent/bullet)."""
parts: list[str] = []
checkbox = STATE_TO_CHECKBOX.get(self.state, "[ ]")
parts.append(checkbox)
# For done tasks, dates come right after checkbox (positional format)
if self.state == "done":
if self.created_date:
parts.append(self.created_date)
if self.done_date:
parts.append(self.done_date)
if self.priority:
parts.append(f"({self.priority})")
parts.append(self.title)
if self.estimate_minutes:
parts.append(self._format_duration(self.estimate_minutes))
assignees = self.explicit_assignees if use_explicit_only else self.assignees
for assignee in assignees:
parts.append(f"@{assignee}")
proj_path = self.explicit_project_path if use_explicit_only else self.project_path
if proj_path:
parts.append(f"+{proj_path}")
tags = self.explicit_tags if use_explicit_only else self.tags
for tag in tags:
parts.append(f"#{tag}")
if self.due_date:
parts.append(f"due:{self.due_date}")
if self.planned_date:
parts.append(f"planned:{self.planned_date}")
if self.recurrence:
if " " in self.recurrence:
parts.append(f'repeat:"{self.recurrence}"')
else:
parts.append(f"repeat:{self.recurrence}")
if self.started_date:
parts.append(f"started:{self.started_date}")
if self.paused_date:
parts.append(f"paused:{self.paused_date}")
custom = self.explicit_custom_fields if use_explicit_only else self.custom_fields
for key, value in custom.items():
if " " in value:
parts.append(f'{key}:"{value}"')
else:
parts.append(f"{key}:{value}")
return " ".join(parts)
def to_markdown_line(self, use_explicit_only: bool = True) -> str:
"""Serialize task to full markdown line with indent and bullet."""
indent = " " * self.indent
return f"{indent}- {self.to_markdown(use_explicit_only)}"
def to_markdown_block(self, use_explicit_only: bool = True) -> str:
"""Serialize task and all subtasks to markdown lines."""
lines = [self.to_markdown_line(use_explicit_only)]
for subtask in self.subtasks:
lines.append(subtask.to_markdown_block(use_explicit_only))
return "\n".join(lines)
@staticmethod
def _format_duration(minutes: int) -> str:
"""Format minutes as ~Xh or ~Xm."""
if minutes >= 60:
hours = minutes // 60
mins = minutes % 60
if mins == 0:
return f"~{hours}h"
return f"~{hours}h{mins}m"
return f"~{minutes}m"
@dataclass
class Warning:
"""Parse warning with location."""
line: int
message: str
source_file: str | None = None
@dataclass
class FileInfo:
"""Metadata about a parsed file."""
path: Path
content: str
lines: list[str]
linked_from: Path | None = None
link_line: int | None = None
@dataclass
class Frontmatter:
"""YAML front matter metadata."""
timezone: str | None = None
locale: str | None = None
@dataclass
class TaskStore:
"""Parse result containing tasks, warnings, and file metadata.
Iterable over tasks: `for task in store`
"""
tasks: list[Task] = field(default_factory=list)
warnings: list[Warning] = field(default_factory=list)
files: dict[Path, FileInfo] = field(default_factory=dict)
root_file: Path | None = None
frontmatter: Frontmatter | None = None
# Pending changes for write_updates() - keyed by (file_path, line_number)
_pending: dict[tuple[Path, int], PendingChange] = field(default_factory=dict, repr=False)
# ─────────────────────────────────────────────────────────────
# Iterable Interface
# ─────────────────────────────────────────────────────────────
def __iter__(self) -> Iterator[Task]:
"""Iterate over tasks."""
return iter(self.tasks)
def __len__(self) -> int:
"""Number of tasks."""
return len(self.tasks)
@overload
def __getitem__(self, idx: int) -> Task: ...
@overload
def __getitem__(self, idx: slice) -> list[Task]: ...
def __getitem__(self, idx: int | slice) -> Task | list[Task]:
"""Get task by index."""
return self.tasks[idx]
# ─────────────────────────────────────────────────────────────
# Warnings
# ─────────────────────────────────────────────────────────────
@property
def is_clean(self) -> bool:
"""True if no warnings."""
return len(self.warnings) == 0
def check(self) -> None:
"""Raise ParseError if there are warnings."""
if self.warnings:
messages = [w.message for w in self.warnings]
raise ParseError(f"Parse warnings: {messages}")
# ─────────────────────────────────────────────────────────────
# Internal Types (not exported)
# ─────────────────────────────────────────────────────────────
@dataclass
class ParsedTask:
"""Intermediate task representation during parsing."""
state: str
title: str
line: int
indent: int = 0
warnings: list[str] = field(default_factory=list)
priority: str | None = None
estimate_minutes: int | None = None
due_date: str | None = None
done_date: str | None = None
planned_date: str | None = None
paused_date: str | None = None
created_date: str | None = None
started_date: str | None = None
recurrence: str | None = None
projects: list[str] = field(default_factory=list)
tags: list[str] = field(default_factory=list)
assignees: list[str] = field(default_factory=list)
custom_fields: dict[str, str] = field(default_factory=dict)
@dataclass
class ParsedHeading:
"""A parsed heading with metadata."""
level: int
text: str
line: int
projects: list[str] = field(default_factory=list)
tags: list[str] = field(default_factory=list)
assignees: list[str] = field(default_factory=list)
custom_fields: dict[str, str] = field(default_factory=dict)
# ─────────────────────────────────────────────────────────────
# Constants
# ─────────────────────────────────────────────────────────────
CHECKBOX_TO_STATE: dict[str, TaskState] = {
"[ ]": TaskState.OPEN,
"[x]": TaskState.DONE,
"[X]": TaskState.DONE,
"[-]": TaskState.CANCELLED,
"[!]": TaskState.BLOCKED,
}
STATE_TO_CHECKBOX: dict[str, str] = {
"open": "[ ]",
"done": "[x]",
"cancelled": "[-]",
"blocked": "[!]",
}
# ─────────────────────────────────────────────────────────────
# Mutation Types
# ─────────────────────────────────────────────────────────────
class _Remove:
"""Sentinel indicating a field should be removed."""
__slots__ = ()
def __repr__(self) -> str:
return "REMOVE"
REMOVE = _Remove()
"""Sentinel value to remove a field. Use `is REMOVE` for comparison."""
@dataclass
class TaskChanges:
"""Change instructions for a task.
All fields default to None (no change).
Set a field to REMOVE to clear it.
Set a field to a value to update it.
For list fields (tags, assignees): set the complete new list.
"""
state: str | None | _Remove = None
title: str | None = None # Cannot be removed
priority: str | None | _Remove = None
estimate_minutes: int | None | _Remove = None
due_date: str | None | _Remove = None
done_date: str | None | _Remove = None
planned_date: str | None | _Remove = None
paused_date: str | None | _Remove = None
created_date: str | None | _Remove = None
started_date: str | None | _Remove = None
recurrence: str | None | _Remove = None
# List fields: set to new complete list (None = no change, [] = clear)
tags: list[str] | None = None
assignees: list[str] | None = None
custom_fields: dict[str, str] | None = None
# Subtasks: set to new complete list (None = no change)
subtasks: list[Task] | None = None
@dataclass
class TaskUpdateSpec:
"""Specification for a single update in a batch."""
title: str
project: str | None
changes: TaskChanges
class UpdateStatus(StrEnum):
"""Status of an update operation."""
SUCCESS = "success"
PARTIAL = "partial"
FAIL = "fail"
@dataclass
class RejectedChange:
"""A change that was rejected."""
field: str
reason: str
attempted_value: Any
@dataclass
class UpdateResult:
"""Result of a single update operation."""
status: UpdateStatus
task: Task | None = None
error: str | None = None
rejected: list[RejectedChange] = field(default_factory=list)
@dataclass
class BatchUpdateResult:
"""Result of a batch update operation."""
total: int
succeeded: int
partial: int
failed: int
results: list[UpdateResult] = field(default_factory=list)
@dataclass
class WriteResult:
"""Result of writing updates to files."""
files_modified: list[Path] = field(default_factory=list)
files_unchanged: list[Path] = field(default_factory=list)
tasks_updated: int = 0
lines_changed: int = 0
@dataclass
class PendingChange:
"""A pending change to be written.
Tracks a modified task and optional new recurring task to insert.
"""
task: Task
new_recurring_task: Task | None = None
# ─────────────────────────────────────────────────────────────
# State Machine
# ─────────────────────────────────────────────────────────────
@dataclass
class StateTransition:
"""A state transition with its side effects.
Attributes:
from_state: Source state (or "*" for any state)
to_state: Target state
on_enter: Action to run when entering the target state.
Receives (task, today) and returns optional new Task.
on_exit: Action to run when leaving the source state.
Receives (task, today) and returns None.
"""
from_state: str
to_state: str
on_enter: TransitionAction | None = None
on_exit: TransitionAction | None = None
# Type alias for transition actions
TransitionAction = Any # Callable[[Task, str], Task | None] - using Any to avoid forward ref issues
@dataclass
class StateMachine:
"""Explicit state machine for task state transitions.
Defines valid transitions and their associated side effects.
Transitions can be from a specific state or from any state ("*").
Example:
machine = StateMachine(transitions=[
StateTransition("*", "done", on_enter=set_done_date),
StateTransition("done", "open", on_exit=clear_done_date),
])
new_task = machine.transition(task, "open", "done", today)
"""
transitions: list[StateTransition] = field(default_factory=list)
def __post_init__(self) -> None:
"""Build lookup table for O(1) transition lookup."""
self._lookup: dict[tuple[str, str], StateTransition] = {}
self._wildcard_lookup: dict[str, StateTransition] = {}
for t in self.transitions:
if t.from_state == "*":
self._wildcard_lookup[t.to_state] = t
else:
self._lookup[(t.from_state, t.to_state)] = t
def get_transition(self, from_state: str, to_state: str) -> StateTransition | None:
"""Get the transition definition for a state change.
Returns:
StateTransition if valid, None if transition not allowed.
"""
# Try exact match first
if (from_state, to_state) in self._lookup:
return self._lookup[(from_state, to_state)]
# Fall back to wildcard
if to_state in self._wildcard_lookup:
return self._wildcard_lookup[to_state]
return None
def is_valid(self, from_state: str, to_state: str) -> bool:
"""Check if a transition is valid."""
return self.get_transition(from_state, to_state) is not None
def apply(
self,
task: Task,
from_state: str,
to_state: str,
today: str,
) -> Task | None:
"""Apply a state transition with side effects.
Args:
task: The task being transitioned (will be mutated)
from_state: Previous state
to_state: New state
today: Today's date string for date fields
Returns:
New recurring task if created by the transition, else None.
Note:
The task.state should already be set to to_state before calling.
This method handles the side effects only.
"""
transition = self.get_transition(from_state, to_state)
if transition is None:
return None
new_task: Task | None = None
# Run exit action for leaving the old state
if transition.on_exit is not None:
transition.on_exit(task, today)
# Run enter action for entering the new state
if transition.on_enter is not None:
result = transition.on_enter(task, today)
if result is not None:
new_task = result
return new_task
def valid_transitions_from(self, state: str) -> list[str]:
"""Get all valid target states from a given state."""
targets: list[str] = []
# Add explicit transitions
for from_s, to_s in self._lookup:
if from_s == state:
targets.append(to_s)
# Add wildcard transitions
targets.extend(self._wildcard_lookup.keys())
return list(dict.fromkeys(targets)) # Dedupe preserving order