-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
191 lines (145 loc) · 6.76 KB
/
utils.py
File metadata and controls
191 lines (145 loc) · 6.76 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
"""Shared utilities for the doc-parser toolchain."""
from __future__ import annotations
import re
import sys
from pathlib import Path
from typing import Any
import yaml
# ========================================
# Regex patterns shared across modules
# ========================================
DOC_ID_RE = re.compile(r"<!--\s*doc-id:\s*(?P<id>[A-Za-z0-9_.-]+)\s*-->")
# ========================================
# YAML utilities
# ========================================
def load_yaml_file(path: Path) -> dict[str, Any]:
"""Load a YAML file and return its contents as a dict."""
with path.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
if not isinstance(data, dict):
raise ValueError(f"YAML root is not a mapping: {path}")
return data
class LiteralStr(str):
"""Marker type for YAML literal block scalars."""
pass
class LiteralDumper(yaml.SafeDumper):
"""YAML dumper that renders multiline strings as literal block scalars."""
pass
def _literal_str_representer(dumper: yaml.Dumper, data: str) -> Any:
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
def _str_representer(dumper: yaml.Dumper, data: str) -> Any:
"""Use literal block style for any multiline string, not just LiteralStr."""
if "\n" in data:
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
return dumper.represent_scalar("tag:yaml.org,2002:str", data)
LiteralDumper.add_representer(LiteralStr, _literal_str_representer)
LiteralDumper.add_representer(str, _str_representer)
def as_yaml_str(s: str) -> str:
"""Use literal block scalar for multiline strings to keep YAML readable."""
return LiteralStr(s) if "\n" in s else s
# ========================================
# Doc link conversion
# ========================================
_LINK_RE = re.compile(r"\{@link\s+(?P<target>[^}|]+?)(?:\s*\|\s*(?P<display>[^}]*?))?\s*\}")
_DOC_ID_LINE_RE = re.compile(r"^\s*<!--\s*doc-id:\s*[^>]+-->\s*$", re.MULTILINE)
_GITHUB_WIKI_RE = re.compile(r"\(github:wiki/([^)]+)\)")
_GITHUB_WIKI_BASE = "https://github.com/transistorsoft/native-background-geolocation/wiki"
# Kotlin fully-qualified name map — KDoc needs FQN for cross-package links.
# Keys are the simple class name; values are the full package path.
_KOTLIN_PKG = "com.transistorsoft.locationmanager.kotlin"
_KOTLIN_FQN: dict[str, str] = {
# config/
"Config": f"{_KOTLIN_PKG}.config.Config",
"ConfigEditor": f"{_KOTLIN_PKG}.config.ConfigEditor",
"AppConfig": f"{_KOTLIN_PKG}.config.AppConfig",
"GeolocationConfig": f"{_KOTLIN_PKG}.config.GeolocationConfig",
"HttpConfig": f"{_KOTLIN_PKG}.config.HttpConfig",
"PersistenceConfig": f"{_KOTLIN_PKG}.config.PersistenceConfig",
"ActivityConfig": f"{_KOTLIN_PKG}.config.ActivityConfig",
"AuthorizationConfig": f"{_KOTLIN_PKG}.config.AuthorizationConfig",
"LoggerConfig": f"{_KOTLIN_PKG}.config.LoggerConfig",
"LocationFilterConfig": f"{_KOTLIN_PKG}.config.LocationFilterConfig",
# events/
"LocationEvent": f"{_KOTLIN_PKG}.events.LocationEvent",
"HttpEvent": f"{_KOTLIN_PKG}.events.HttpEvent",
"ActivityChangeEvent": f"{_KOTLIN_PKG}.events.ActivityChangeEvent",
"ProviderChangeEvent": f"{_KOTLIN_PKG}.events.ProviderChangeEvent",
"HeartbeatEvent": f"{_KOTLIN_PKG}.events.HeartbeatEvent",
"AuthorizationEvent": f"{_KOTLIN_PKG}.events.AuthorizationEvent",
"GeofenceEvent": f"{_KOTLIN_PKG}.events.GeofenceEvent",
"GeofencesChangeEvent": f"{_KOTLIN_PKG}.events.GeofencesChangeEvent",
"ConnectivityChangeEvent": f"{_KOTLIN_PKG}.events.ConnectivityChangeEvent",
# top-level classes
"Geofence": f"{_KOTLIN_PKG}.Geofence",
"GeofenceManager": f"{_KOTLIN_PKG}.GeofenceManager",
"EventSubscription": f"{_KOTLIN_PKG}.EventSubscription",
"Logger": f"{_KOTLIN_PKG}.Logger",
"DataStore": f"{_KOTLIN_PKG}.DataStore",
"Authorization": f"{_KOTLIN_PKG}.Authorization",
"Sensors": f"{_KOTLIN_PKG}.Sensors",
"App": f"{_KOTLIN_PKG}.App",
"TransistorAuthorizationService": f"{_KOTLIN_PKG}.TransistorAuthorizationService",
}
def _kotlin_resolve_fqn(target: str) -> str:
"""Resolve a simple class reference to its Kotlin FQN.
Examples:
'AppConfig.schedule' → 'com.transistorsoft...config.AppConfig.schedule'
'BGGeo' → 'BGGeo' (same package, no mapping needed)
'stop' → 'stop' (bare method, no class prefix)
"""
# Split into class part and optional member part
parts = target.split(".", 1)
cls = parts[0]
if cls in _KOTLIN_FQN:
fqn = _KOTLIN_FQN[cls]
if len(parts) > 1:
return f"{fqn}.{parts[1]}"
return fqn
# No mapping found — return as-is (same package or unknown)
return target
def convert_doc_links(text: str, fmt: str) -> str:
"""Convert {@link ClassName.member} and other doc markup to platform format.
Args:
text: Raw description text from YAML (may contain {@link ...}, <!-- doc-id -->, etc.)
fmt: Target format — "kotlin", "swift", or "typedoc" (passthrough)
Returns:
Text with links converted to the target platform's doc comment syntax.
"""
if fmt == "typedoc":
return text
# Remove <!-- doc-id: ... --> lines
text = _DOC_ID_LINE_RE.sub("", text)
# Convert github:wiki links to full URLs
text = _GITHUB_WIKI_RE.sub(rf"({_GITHUB_WIKI_BASE}/\1)", text)
# Convert {@link ...} to platform format
text = _LINK_RE.sub(lambda m: _format_link(m, fmt), text)
# Clean up excessive blank lines (max 2 consecutive)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def _format_link(m: re.Match, fmt: str) -> str:
"""Format a single {@link target | display} match for the target platform."""
target = m.group("target").strip()
display = (m.group("display") or "").strip()
if fmt == "kotlin":
# KDoc: [display text][FQN] for cross-package links
# Resolve to FQN for cross-package links
fqn_target = _kotlin_resolve_fqn(target)
if display:
return f"[{display}][{fqn_target}]"
# If FQN differs from original, use short name as display text
if fqn_target != target:
return f"[{target}][{fqn_target}]"
return f"[{fqn_target}]"
elif fmt == "swift":
# DocC: ``ClassName/member`` (dots become slashes)
swift_target = target.replace(".", "/")
if display:
return f"[{display}](doc:{swift_target})"
return f"``{swift_target}``"
return m.group(0) # passthrough
# ========================================
# File utilities
# ========================================
def read_text(path: Path) -> str:
"""Read a text file with UTF-8 encoding, replacing invalid characters."""
return path.read_text(encoding="utf-8", errors="replace")