-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_transformer.py
More file actions
227 lines (205 loc) · 8.65 KB
/
Copy path_transformer.py
File metadata and controls
227 lines (205 loc) · 8.65 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
"""Transform Lark parse tree to Task dicts."""
from __future__ import annotations
import re
from typing import Any, ClassVar
from lark import Token, Transformer, Tree, v_args
from taskmark._types import (
CHECKBOX_TO_STATE,
ParsedHeading,
ParsedTask,
TaskState,
)
class TaskmarkTransformer(Transformer[Token, Any]):
"""Transform Lark parse tree into ParsedTask and ParsedHeading objects."""
# Duration pattern: ~2h, ~30m, ~1d
_DURATION_PATTERN: ClassVar[re.Pattern[str]] = re.compile(r"~(\d+)([hmd])")
def __init__(self, minutes_per_day: int = 480) -> None:
"""Initialize transformer with config."""
super().__init__()
self._minutes_per_day = minutes_per_day
def _get_duration_multipliers(self) -> dict[str, int]:
"""Get duration multipliers."""
return {"h": 60, "m": 1, "d": self._minutes_per_day}
@v_args(inline=True)
def checkbox(self, token: Token) -> TaskState:
"""Convert checkbox token to TaskState."""
return CHECKBOX_TO_STATE[token.value]
def content_item(self, items: list[Token]) -> tuple[str, str | int] | tuple[str, str, str]:
"""Process a content item (word or metadata token)."""
token = items[0]
value = token.value
if token.type == "PROJECT":
return ("project", value[1:]) # Strip +
elif token.type == "TAG":
return ("tag", value[1:]) # Strip #
elif token.type == "ASSIGNEE":
return ("assignee", value[1:]) # Strip @
elif token.type == "PRIORITY":
return ("priority", value[1:-1]) # Strip ()
elif token.type == "DURATION":
match = self._DURATION_PATTERN.match(value)
if match:
num = int(match.group(1))
unit = match.group(2)
multipliers = self._get_duration_multipliers()
return ("duration", num * multipliers[unit])
return ("duration", 0)
elif token.type == "KEYVALUE_QUOTED":
# Handle quoted values: key:"value with spaces"
key, _, rest = value.partition(":")
# Strip surrounding quotes from value
val = rest[1:-1] if rest.startswith('"') and rest.endswith('"') else rest
return ("keyvalue", key, val)
elif token.type == "KEYVALUE":
key, _, val = value.partition(":")
# Detect malformed fields (multiple colons that aren't URLs)
if ":" in val and not val.startswith(("http://", "https://", "//")):
return ("malformed_keyvalue", key, val)
return ("keyvalue", key, val)
elif token.type == "DATE_POSITION":
# Date at start of line becomes planned_date (for open) or done_date (for done)
return ("date_position", value)
elif token.type == "ESCAPED":
# Escaped markers: john\@example.com -> john@example.com
# Remove all backslashes before @, #, +
cleaned = re.sub(r"\\([@#+])", r"\1", value)
return ("word", cleaned)
else:
# WORD - regular text
return ("word", value)
@v_args(tree=True)
def task(self, tree: Tree[Token]) -> ParsedTask:
"""Build ParsedTask from parsed components."""
state: TaskState = TaskState.OPEN
title_parts: list[str] = []
projects: list[str] = []
tags: list[str] = []
assignees: list[str] = []
custom_fields: dict[str, str] = {}
priority: str | None = None
estimate_minutes: int | None = None
due_date: str | None = None
created_date: str | None = None
started_date: str | None = None
done_date: str | None = None
planned_date: str | None = None
paused_date: str | None = None
recurrence: str | None = None
warnings: list[str] = []
indent: int = 0
for item in tree.children:
if isinstance(item, TaskState):
state = item
elif isinstance(item, Token) and item.type == "INDENT":
# Calculate indent level (spaces/tabs before task, tabs = 4 spaces)
indent = len(item.value.replace("\t", " "))
elif isinstance(item, tuple):
kind = item[0]
if kind == "word":
title_parts.append(item[1])
elif kind == "project":
projects.append(item[1])
elif kind == "tag":
tags.append(item[1])
elif kind == "assignee":
assignees.append(item[1])
elif kind == "priority":
# First priority wins
if priority is None:
priority = item[1]
elif kind == "duration":
estimate_minutes = item[1]
elif kind == "malformed_keyvalue":
# Skip malformed fields and record warning
warnings.append(f"malformed field '{item[1]}:{item[2]}'")
elif kind == "date_position":
# Date at start of task - use as planned_date for first, done_date for second
if planned_date is None:
planned_date = item[1]
elif done_date is None:
done_date = item[1]
elif kind == "keyvalue":
key, val = item[1], item[2]
if key == "due":
due_date = val
elif key == "created":
created_date = val
elif key == "started":
started_date = val
elif key == "done":
done_date = val
elif key == "planned":
planned_date = val
elif key == "paused":
paused_date = val
elif key in ("recur", "repeat"):
recurrence = val
else:
custom_fields[key] = val
# Extract line number from tree metadata
line = tree.meta.line if tree.meta and hasattr(tree.meta, "line") else 0
return ParsedTask(
state=state.value,
title=" ".join(title_parts),
line=line,
indent=indent,
warnings=warnings,
priority=priority,
estimate_minutes=estimate_minutes,
due_date=due_date,
done_date=done_date,
planned_date=planned_date,
paused_date=paused_date,
created_date=created_date,
started_date=started_date,
recurrence=recurrence,
projects=projects,
tags=tags,
assignees=assignees,
custom_fields=custom_fields,
)
@v_args(tree=True)
def heading(self, tree: Tree[Token]) -> ParsedHeading:
"""Build ParsedHeading from parsed heading."""
level = 0
text_parts: list[str] = []
projects: list[str] = []
tags: list[str] = []
assignees: list[str] = []
custom_fields: dict[str, str] = {}
for item in tree.children:
if isinstance(item, Token) and item.type == "HEADING_MARKER":
level = item.value.count("#")
elif isinstance(item, tuple):
kind = item[0]
if kind == "word":
text_parts.append(item[1])
elif kind == "project":
projects.append(item[1])
elif kind == "tag":
tags.append(item[1])
elif kind == "assignee":
assignees.append(item[1])
elif kind == "keyvalue":
key, val = item[1], item[2]
custom_fields[key] = val
# Extract line number from tree metadata
line = tree.meta.line if tree.meta and hasattr(tree.meta, "line") else 0
return ParsedHeading(
level=level,
text=" ".join(text_parts),
projects=projects,
tags=tags,
assignees=assignees,
custom_fields=custom_fields,
line=line,
)
def line(self, items: list[Any]) -> ParsedTask | ParsedHeading | None:
"""Extract task or heading from line, ignore other lines."""
for item in items:
if isinstance(item, (ParsedHeading, ParsedTask)):
return item
return None
def start(self, items: list[Any]) -> list[ParsedTask | ParsedHeading]:
"""Collect all parsed items, filtering None."""
return [item for item in items if item is not None]