-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_resolver.py
More file actions
291 lines (239 loc) · 12 KB
/
Copy path_resolver.py
File metadata and controls
291 lines (239 loc) · 12 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
"""Resolve task inheritance from heading context."""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass, field
from pathlib import Path
from taskmark._types import ParsedHeading, ParsedTask, Task
@dataclass
class _HeadingContext:
"""Context accumulated from a single heading."""
level: int
project_path: str | None
tags: list[str]
assignees: list[str]
custom_fields: dict[str, str]
def _priority_sort_key(task: Task) -> tuple[int, str, str]:
"""Sort key for tasks by priority.
Priority order: A-Z letters first, then 1-99 numbers, then no priority last.
Within same priority, sort alphabetically by title.
"""
if task.priority is None:
return (2, "", task.title) # No priority - last
if task.priority.isalpha():
return (0, task.priority.upper(), task.title) # Letters first (A=highest)
if task.priority.isdigit():
return (1, task.priority.zfill(2), task.title) # Numbers second
return (0, task.priority, task.title) # Other alphanumeric
@dataclass
class InheritanceResolver:
"""Resolve task inheritance from heading and parent task context.
This class processes a stream of ParsedTask and ParsedHeading items,
applying heading-based and parent-task inheritance to produce resolved Task objects.
Inheritance rules:
- Project path: Hierarchical (heading paths joined with "/" then task's own appended)
- Tags: Appended (inherited + task's own, deduplicated preserving order)
- Assignees: Appended (inherited + task's own, deduplicated preserving order)
- Custom Fields: Overwritten per-key (explicit replaces inherited)
- Subtasks: Tasks with greater indent are nested under parent tasks
- Subtasks inherit project_path from parent task (always)
- Subtasks inherit tags/assignees/custom_fields from parent task
- Subtasks are sorted by priority
"""
# Stack of heading contexts for inheritance
_stack: list[_HeadingContext] = field(default_factory=list)
# Level offset for file links (to preserve parent context)
_level_offset: int = 0
def _join_project_paths(self, *paths: str | None) -> str | None:
"""Join project paths with '/', filtering out empty values.
Example: _join_project_paths("a/b", "c") -> "a/b/c"
"""
parts = [p for p in paths if p]
return "/".join(parts) if parts else None
def _push_heading(self, heading: ParsedHeading) -> None:
"""Push a heading onto the context stack, popping deeper levels."""
# Apply level offset for file links
effective_level = heading.level + self._level_offset
# Pop any headings at same or deeper level
while self._stack and self._stack[-1].level >= effective_level:
self._stack.pop()
# Join all project paths from the heading into a single path
heading_project_path = self._join_project_paths(*heading.projects)
self._stack.append(
_HeadingContext(
level=effective_level,
project_path=heading_project_path,
tags=list(heading.tags),
assignees=list(heading.assignees),
custom_fields=dict(heading.custom_fields),
)
)
def get_max_level(self) -> int:
"""Get the maximum heading level in the current stack."""
return max((ctx.level for ctx in self._stack), default=0)
def set_level_offset(self, offset: int) -> None:
"""Set the level offset for subsequent headings."""
self._level_offset = offset
def _resolve_task(self, parsed: ParsedTask, source_file: Path | None) -> Task:
"""Apply inherited context to a task and build Task."""
# Collect inherited values from heading stack
inherited_project_paths: list[str] = []
inherited_tags: list[str] = []
inherited_assignees: list[str] = []
inherited_custom_fields: dict[str, str] = {}
for ctx in self._stack:
if ctx.project_path:
inherited_project_paths.append(ctx.project_path)
inherited_tags.extend(ctx.tags)
inherited_assignees.extend(ctx.assignees)
# Custom fields: later headings override earlier ones
inherited_custom_fields.update(ctx.custom_fields)
# Build inherited project path from heading stack
inherited_project_path = self._join_project_paths(*inherited_project_paths)
# Task's explicit project path (join multiple +proj annotations)
explicit_project_path = self._join_project_paths(*parsed.projects)
# Explicit values from task line
explicit_tags = list(parsed.tags)
explicit_assignees = list(parsed.assignees)
explicit_custom_fields = dict(parsed.custom_fields)
# Apply inheritance rules:
# Project path: hierarchical (inherited / explicit)
all_project_path = self._join_project_paths(inherited_project_path, explicit_project_path)
# Tags: appended with deduplication (preserving order)
all_tags = list(dict.fromkeys(inherited_tags + explicit_tags))
# Assignees: appended with deduplication (preserving order)
all_assignees = list(dict.fromkeys(inherited_assignees + explicit_assignees))
# Custom fields: explicit overwrites inherited per-key
all_custom_fields = dict(inherited_custom_fields)
all_custom_fields.update(explicit_custom_fields)
return Task(
# Core fields
state=parsed.state,
title=parsed.title,
priority=parsed.priority,
estimate_minutes=parsed.estimate_minutes,
due_date=parsed.due_date,
done_date=parsed.done_date,
planned_date=parsed.planned_date,
paused_date=parsed.paused_date,
created_date=parsed.created_date,
started_date=parsed.started_date,
recurrence=parsed.recurrence,
# Merged fields
assignees=all_assignees,
tags=all_tags,
project_path=all_project_path,
custom_fields=all_custom_fields if all_custom_fields else {},
# Location
file=source_file,
line=parsed.line,
indent=parsed.indent,
# Provenance
inherited_project_path=inherited_project_path,
explicit_project_path=explicit_project_path,
inherited_tags=inherited_tags,
explicit_tags=explicit_tags,
inherited_assignees=inherited_assignees,
explicit_assignees=explicit_assignees,
inherited_custom_fields=inherited_custom_fields,
explicit_custom_fields=explicit_custom_fields,
)
def clear(self) -> None:
"""Reset context for new file."""
self._stack.clear()
def _apply_parent_inheritance(self, subtask: Task, parent: Task) -> None:
"""Apply parent task inheritance to a subtask (mutates subtask in place).
Subtasks inherit from their parent:
- project_path: Always inherited (subtask cannot override)
- tags: Parent tags + subtask's explicit tags (deduplicated)
- assignees: Parent assignees + subtask's explicit assignees (deduplicated)
- custom_fields: Parent fields, subtask explicit fields override
"""
# Project path: always from parent (subtask's explicit project is ignored)
subtask.project_path = parent.project_path
subtask.inherited_project_path = parent.project_path
subtask.explicit_project_path = None
# Tags: parent's tags + subtask's explicit tags
parent_tags = list(parent.tags)
all_tags = list(dict.fromkeys(parent_tags + subtask.explicit_tags))
subtask.tags = all_tags
subtask.inherited_tags = parent_tags
# Assignees: parent's assignees + subtask's explicit assignees
parent_assignees = list(parent.assignees)
all_assignees = list(dict.fromkeys(parent_assignees + subtask.explicit_assignees))
subtask.assignees = all_assignees
subtask.inherited_assignees = parent_assignees
# Custom fields: parent's fields, subtask's explicit override
parent_custom = dict(parent.custom_fields)
all_custom = dict(parent_custom)
all_custom.update(subtask.explicit_custom_fields)
subtask.custom_fields = all_custom
subtask.inherited_custom_fields = parent_custom
def _finalize_subtasks(self, parent: Task) -> None:
"""Apply inheritance and sorting to all subtasks of a parent (recursive)."""
for subtask in parent.subtasks:
self._apply_parent_inheritance(subtask, parent)
# Recursively finalize nested subtasks
self._finalize_subtasks(subtask)
# Sort subtasks by priority
parent.subtasks.sort(key=_priority_sort_key)
def process(
self,
items: Iterable[ParsedTask | ParsedHeading],
source_file: str | None = None,
) -> Iterator[tuple[Task, int, list[str]]]:
"""Process items and yield resolved tasks with line numbers and warnings.
This method handles subtask nesting based on indentation levels.
Tasks with greater indent become subtasks of the previous less-indented task.
Args:
items: Stream of ParsedTask and ParsedHeading items
source_file: Optional source file path for source location
Yields:
Tuples of (resolved_task, line_number, warnings) for root-level tasks only
Subtasks are nested within their parent's "subtasks" field
"""
# Convert source_file to Path if provided
file_path = Path(source_file) if source_file else None
# Stack of (indent, task, line, warnings) for building subtask hierarchy
task_stack: list[tuple[int, Task, int, list[str]]] = []
for item in items:
if isinstance(item, ParsedHeading):
# Flush any pending tasks before processing heading
yield from self._flush_task_stack(task_stack)
task_stack.clear()
self._push_heading(item)
elif isinstance(item, ParsedTask):
task = self._resolve_task(item, file_path)
indent = item.indent
# Pop tasks from stack that are at same or greater indent
while task_stack and task_stack[-1][0] >= indent:
# This task becomes a sibling or uncle, flush the popped one
_parent_indent, parent_task, parent_line, parent_warnings = task_stack.pop()
if task_stack:
# Add as subtask of remaining parent
grandparent_task = task_stack[-1][1]
grandparent_task.subtasks.append(parent_task)
else:
# No parent, yield as root task
# Finalize subtasks (apply inheritance from parent, sort by priority)
self._finalize_subtasks(parent_task)
yield parent_task, parent_line, parent_warnings
# Push this task onto stack (could be root or subtask)
task_stack.append((indent, task, item.line, item.warnings))
# Flush remaining tasks in stack
yield from self._flush_task_stack(task_stack)
def _flush_task_stack(
self,
task_stack: list[tuple[int, Task, int, list[str]]],
) -> Iterator[tuple[Task, int, list[str]]]:
"""Flush task stack, nesting subtasks into parents."""
while task_stack:
_indent, task, line, warnings = task_stack.pop()
if task_stack:
# Add as subtask of remaining parent
parent_task = task_stack[-1][1]
parent_task.subtasks.append(task)
else:
# No parent, yield as root task
# Finalize subtasks (apply inheritance from parent, sort by priority)
self._finalize_subtasks(task)
yield task, line, warnings