-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_loader.py
More file actions
282 lines (224 loc) · 8.6 KB
/
Copy path_loader.py
File metadata and controls
282 lines (224 loc) · 8.6 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
"""Load taskmark files with file link support."""
from __future__ import annotations
import re
from pathlib import Path
from typing import TYPE_CHECKING
from lark import UnexpectedInput
from taskmark._parser import _detect_malformed_tasks, _extract_frontmatter
from taskmark._resolver import InheritanceResolver
from taskmark._transformer import TaskmarkTransformer
from taskmark._types import (
FileInfo,
Frontmatter,
ParsedHeading,
ParsedTask,
Task,
TaskStore,
Warning,
)
if TYPE_CHECKING:
from lark import Lark
# Pattern for file links: [text](path.md)
# Must be at start of line (after optional whitespace)
_LINK_PATTERN = re.compile(r"^\s*\[([^\]]+)\]\(([^)]+\.md)\)\s*$")
def _get_parser() -> Lark:
"""Get the parser instance (import here to avoid circular imports)."""
from taskmark._parser import _get_parser
return _get_parser()
def parse_links(content: str) -> list[tuple[int, str, str]]:
"""Extract file links from content.
Args:
content: Markdown content to scan
Returns:
List of (line_number, link_text, link_path) tuples
"""
links: list[tuple[int, str, str]] = []
for line_num, line in enumerate(content.split("\n"), start=1):
match = _LINK_PATTERN.match(line)
if match:
links.append((line_num, match.group(1), match.group(2)))
return links
def resolve_link_path(link: str, base: Path) -> Path:
"""Resolve a link path relative to a base file.
Args:
link: The link path (may be relative or absolute)
base: The file containing the link
Returns:
Resolved absolute path
"""
link_path = Path(link)
if link_path.is_absolute():
return link_path
return (base.parent / link_path).resolve()
def load_file_tree(
path: Path,
minutes_per_day: int,
resolver: InheritanceResolver,
loaded: set[Path],
warnings: list[Warning],
linked_from: Path | None = None,
link_line: int | None = None,
is_root: bool = False,
) -> tuple[list[Task], dict[Path, FileInfo], Frontmatter | None]:
"""Recursively load a file and its linked files.
Args:
path: File to load
minutes_per_day: Minutes in a work day for duration conversion
resolver: Shared resolver (maintains heading context)
loaded: Set of already-loaded files (for cycle detection)
warnings: Accumulator for warnings
linked_from: File that linked to this one (for FileInfo)
link_line: Line number of the link (for FileInfo)
is_root: True if this is the root file (extracts frontmatter)
Returns:
Tuple of (tasks, files_dict, frontmatter)
"""
path = path.resolve()
frontmatter: Frontmatter | None = None
# Check for circular link
if path in loaded:
warnings.append(
Warning(
line=link_line or 0,
message=f"Circular link detected: {path.name}",
source_file=str(linked_from) if linked_from else None,
)
)
return [], {}, None
# Check file exists
if not path.exists():
warnings.append(
Warning(
line=link_line or 0,
message=f"Linked file not found: {path}",
source_file=str(linked_from) if linked_from else None,
)
)
return [], {}, None
loaded.add(path)
# Read file content
content = path.read_text(encoding="utf-8")
# Extract front matter if this is the root file
if is_root:
content, frontmatter, fm_warnings = _extract_frontmatter(content, str(path))
warnings.extend(fm_warnings)
lines = content.split("\n")
# Create FileInfo
file_info = FileInfo(
path=path,
content=content,
lines=lines,
linked_from=linked_from,
link_line=link_line,
)
files: dict[Path, FileInfo] = {path: file_info}
# Detect potential malformed tasks (list items without checkboxes)
warnings.extend(_detect_malformed_tasks(content, str(path)))
# Parse the file
parser = _get_parser()
transformer = TaskmarkTransformer(minutes_per_day=minutes_per_day)
# Ensure content ends with newline for grammar
parse_content = content if content.endswith("\n") else content + "\n"
tasks: list[Task] = []
try:
tree = parser.parse(parse_content)
items = transformer.transform(tree)
# Find link positions in the content
link_positions = parse_links(content)
link_map = {line_num: (text, link_path) for line_num, text, link_path in link_positions}
# Process items, inserting linked file contents at link positions
current_line = 0
pending_items: list[ParsedTask | ParsedHeading] = []
for item in items:
item_line = getattr(item, "line", 0)
# Check if any links appear between current_line and item_line
for link_line_num in sorted(link_map.keys()):
if current_line < link_line_num <= item_line:
# Process pending items first
for task, line, task_warnings in resolver.process(pending_items, str(path)):
for msg in task_warnings:
warnings.append(Warning(line=line, message=msg, source_file=str(path)))
tasks.append(task)
pending_items = []
# Load linked file with level offset to preserve parent context
_text, link_path = link_map[link_line_num]
resolved_path = resolve_link_path(link_path, path)
# Save current offset and set new offset based on max level
old_offset = resolver._level_offset
resolver.set_level_offset(resolver.get_max_level())
linked_tasks, linked_files, _ = load_file_tree(
resolved_path,
minutes_per_day,
resolver,
loaded,
warnings,
linked_from=path,
link_line=link_line_num,
)
# Restore offset
resolver.set_level_offset(old_offset)
tasks.extend(linked_tasks)
files.update(linked_files)
# Remove processed link
del link_map[link_line_num]
pending_items.append(item)
current_line = item_line
# Process any remaining items
for task, line, task_warnings in resolver.process(pending_items, str(path)):
for msg in task_warnings:
warnings.append(Warning(line=line, message=msg, source_file=str(path)))
tasks.append(task)
# Process any remaining links after last item
for link_line_num in sorted(link_map.keys()):
_text, link_path = link_map[link_line_num]
resolved_path = resolve_link_path(link_path, path)
# Save current offset and set new offset based on max level
old_offset = resolver._level_offset
resolver.set_level_offset(resolver.get_max_level())
linked_tasks, linked_files, _ = load_file_tree(
resolved_path,
minutes_per_day,
resolver,
loaded,
warnings,
linked_from=path,
link_line=link_line_num,
)
# Restore offset
resolver.set_level_offset(old_offset)
tasks.extend(linked_tasks)
files.update(linked_files)
except UnexpectedInput as e:
warnings.append(
Warning(
line=e.line if hasattr(e, "line") else 0,
message=f"Parse error: {e}",
source_file=str(path),
)
)
return tasks, files, frontmatter
def build_task_store(
path: Path | str,
minutes_per_day: int = 480,
) -> TaskStore:
"""Build a TaskStore from a root file, following all links.
Args:
path: Root file path
minutes_per_day: Minutes in a work day for duration conversion
Returns:
TaskStore with all tasks and file metadata
"""
root = Path(path).resolve()
resolver = InheritanceResolver()
loaded: set[Path] = set()
warnings: list[Warning] = []
tasks, files, frontmatter = load_file_tree(
root, minutes_per_day, resolver, loaded, warnings, is_root=True
)
return TaskStore(
root_file=root,
files=files,
tasks=tasks,
warnings=warnings,
frontmatter=frontmatter,
)