hypermarkdown 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hypermarkdown/__init__.py +31 -0
- hypermarkdown/cli.py +177 -0
- hypermarkdown/config.py +110 -0
- hypermarkdown/diagram.py +169 -0
- hypermarkdown/embed.py +227 -0
- hypermarkdown/frontmatter.py +191 -0
- hypermarkdown/graph.py +74 -0
- hypermarkdown/imports.py +62 -0
- hypermarkdown/lint/__init__.py +6 -0
- hypermarkdown/lint/report.py +44 -0
- hypermarkdown/lint/rules.py +257 -0
- hypermarkdown/mkdocs_plugin.py +337 -0
- hypermarkdown/model.py +155 -0
- hypermarkdown/parse.py +174 -0
- hypermarkdown/render/__init__.py +5 -0
- hypermarkdown/render/flat.py +77 -0
- hypermarkdown/resolve.py +334 -0
- hypermarkdown/scan.py +153 -0
- hypermarkdown/urls.py +60 -0
- hypermarkdown-0.2.0.dist-info/METADATA +303 -0
- hypermarkdown-0.2.0.dist-info/RECORD +25 -0
- hypermarkdown-0.2.0.dist-info/WHEEL +5 -0
- hypermarkdown-0.2.0.dist-info/entry_points.txt +6 -0
- hypermarkdown-0.2.0.dist-info/licenses/LICENSE +21 -0
- hypermarkdown-0.2.0.dist-info/top_level.txt +1 -0
hypermarkdown/embed.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Embed expansion (HMD-0001 §6).
|
|
2
|
+
|
|
3
|
+
Expansion is textual: an embed is replaced by the target's bytes, with no
|
|
4
|
+
heading-level shifting, so the operation stays reversible by inspection. It is
|
|
5
|
+
bounded in two ways — a stack of `(path, fragment)` pairs catches cycles, and
|
|
6
|
+
`MAX_EMBED_DEPTH` bounds work on adversarial input.
|
|
7
|
+
|
|
8
|
+
The expander is total. An embed it cannot expand — unresolved, cyclic, or too
|
|
9
|
+
deep — is left in the output exactly as written, and the reason is returned as a
|
|
10
|
+
diagnostic. A build stays green while lint tracks the work item.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from .frontmatter import split_frontmatter
|
|
20
|
+
from .model import ERROR, Diagnostic, Document, Link
|
|
21
|
+
from .parse import slug_for
|
|
22
|
+
from .resolve import Outcome, Workspace
|
|
23
|
+
|
|
24
|
+
#: Called with each non-embed link and the page it resolved to, or None when it
|
|
25
|
+
#: did not. Returning the replacement text; `link.raw` leaves it untouched.
|
|
26
|
+
Rewrite = Callable[[Link, Path | None], str]
|
|
27
|
+
|
|
28
|
+
#: Called with a resolved embed target; False leaves the embed unexpanded, as if
|
|
29
|
+
#: it were an ordinary link. The expander asks rather than decides — publication
|
|
30
|
+
#: is the caller's policy, and a `hmd render` of a card you named yourself is not
|
|
31
|
+
#: the same situation as a site build (HMD-0002 §2).
|
|
32
|
+
CanEmbed = Callable[[Path], bool]
|
|
33
|
+
|
|
34
|
+
#: Maximum embed expansion depth (HMD-0001 §6). Deep enough for legitimate
|
|
35
|
+
#: composition, shallow enough to bound work on adversarial input. Defined once
|
|
36
|
+
#: here and imported elsewhere, so the template engine reuses it rather than
|
|
37
|
+
#: reimplementing a second limit beside it.
|
|
38
|
+
MAX_EMBED_DEPTH = 16
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Expansion:
|
|
43
|
+
text: str
|
|
44
|
+
diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def expand(
|
|
48
|
+
workspace: Workspace,
|
|
49
|
+
path: Path,
|
|
50
|
+
rewrite: Rewrite | None = None,
|
|
51
|
+
can_embed: CanEmbed | None = None,
|
|
52
|
+
) -> Expansion:
|
|
53
|
+
"""Expand every embed in `path`, recursively, returning its body text.
|
|
54
|
+
|
|
55
|
+
`rewrite` is applied to ordinary links in the same walk. Doing both at once
|
|
56
|
+
is not an optimization: a link inside embedded content must be *resolved*
|
|
57
|
+
from the card it was written in, while the text it becomes belongs to the
|
|
58
|
+
page being rendered. Rewriting the flattened output afterwards would have
|
|
59
|
+
lost which card each link came from.
|
|
60
|
+
|
|
61
|
+
`can_embed` may veto a target. A vetoed embed degrades to `rewrite`, so it
|
|
62
|
+
lands wherever the caller sends an ordinary link to that page.
|
|
63
|
+
"""
|
|
64
|
+
document = workspace.documents[path]
|
|
65
|
+
result = Expansion(text="")
|
|
66
|
+
start, end = body_region(document)
|
|
67
|
+
result.text = _region(
|
|
68
|
+
workspace, document, start, end, [(path, None)], result.diagnostics, rewrite, can_embed
|
|
69
|
+
)
|
|
70
|
+
return result
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# -- regions -------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def body_region(document: Document) -> tuple[int, int]:
|
|
77
|
+
"""The document minus its frontmatter fence."""
|
|
78
|
+
_raw, _body, offset = split_frontmatter(document.text)
|
|
79
|
+
return offset, len(document.text)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def body(document: Document) -> str:
|
|
83
|
+
start, end = body_region(document)
|
|
84
|
+
return document.text[start:end]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def section_region(document: Document, fragment: str) -> tuple[int, int] | None:
|
|
88
|
+
"""A heading and everything up to the next heading of the same or higher level."""
|
|
89
|
+
wanted = slug_for(fragment, set())
|
|
90
|
+
for index, heading in enumerate(document.headings):
|
|
91
|
+
if heading.slug != wanted:
|
|
92
|
+
continue
|
|
93
|
+
end = len(document.text)
|
|
94
|
+
for following in document.headings[index + 1 :]:
|
|
95
|
+
if following.level <= heading.level:
|
|
96
|
+
end = following.span.start
|
|
97
|
+
break
|
|
98
|
+
return heading.span.start, end
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def block_region(document: Document, block_id: str) -> tuple[int, int] | None:
|
|
103
|
+
"""The anchored block, with its trailing ``^id`` marker excluded.
|
|
104
|
+
|
|
105
|
+
A block runs back from the anchored line to the nearest blank line, since
|
|
106
|
+
the anchor marks the end of a block rather than the start of one.
|
|
107
|
+
"""
|
|
108
|
+
text = document.text
|
|
109
|
+
floor, _ = body_region(document)
|
|
110
|
+
for anchor in document.anchors:
|
|
111
|
+
if anchor.block_id != block_id:
|
|
112
|
+
continue
|
|
113
|
+
start = text.rfind("\n", 0, anchor.span.start) + 1
|
|
114
|
+
while start > floor:
|
|
115
|
+
previous_end = start - 1
|
|
116
|
+
previous_start = text.rfind("\n", 0, previous_end) + 1
|
|
117
|
+
if previous_start < floor or not text[previous_start:previous_end].strip():
|
|
118
|
+
break
|
|
119
|
+
start = previous_start
|
|
120
|
+
return start, anchor.span.start
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _target_region(document: Document, link: Link) -> tuple[int, int] | None:
|
|
125
|
+
if link.fragment is None:
|
|
126
|
+
return body_region(document)
|
|
127
|
+
if link.fragment_kind == "block":
|
|
128
|
+
return block_region(document, link.fragment)
|
|
129
|
+
return section_region(document, link.fragment)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# -- expansion -----------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _region(
|
|
136
|
+
workspace: Workspace,
|
|
137
|
+
document: Document,
|
|
138
|
+
start: int,
|
|
139
|
+
end: int,
|
|
140
|
+
stack: list[tuple[Path, str | None]],
|
|
141
|
+
diagnostics: list[Diagnostic],
|
|
142
|
+
rewrite: Rewrite | None,
|
|
143
|
+
can_embed: CanEmbed | None = None,
|
|
144
|
+
) -> str:
|
|
145
|
+
"""Copy `document.text[start:end]`, substituting the links inside it."""
|
|
146
|
+
out: list[str] = []
|
|
147
|
+
cursor = start
|
|
148
|
+
|
|
149
|
+
for link in document.links:
|
|
150
|
+
if not (start <= link.span.start < end):
|
|
151
|
+
continue
|
|
152
|
+
if link.is_embed:
|
|
153
|
+
replacement = _embed(workspace, document, link, stack, diagnostics, rewrite, can_embed)
|
|
154
|
+
elif rewrite is not None:
|
|
155
|
+
result = workspace.resolve(document.path, link.page_ref)
|
|
156
|
+
target = result.path if result.outcome is Outcome.RESOLVED else None
|
|
157
|
+
replacement = rewrite(link, target)
|
|
158
|
+
else:
|
|
159
|
+
continue
|
|
160
|
+
out.append(document.text[cursor : link.span.start])
|
|
161
|
+
out.append(replacement)
|
|
162
|
+
cursor = link.span.end
|
|
163
|
+
|
|
164
|
+
out.append(document.text[cursor:end])
|
|
165
|
+
return "".join(out)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _embed(
|
|
169
|
+
workspace: Workspace,
|
|
170
|
+
document: Document,
|
|
171
|
+
link: Link,
|
|
172
|
+
stack: list[tuple[Path, str | None]],
|
|
173
|
+
diagnostics: list[Diagnostic],
|
|
174
|
+
rewrite: Rewrite | None,
|
|
175
|
+
can_embed: CanEmbed | None = None,
|
|
176
|
+
) -> str:
|
|
177
|
+
"""Expand one embed, or return it verbatim with a diagnostic."""
|
|
178
|
+
result = workspace.resolve(document.path, link.page_ref)
|
|
179
|
+
if result.outcome is not Outcome.RESOLVED or result.path is None:
|
|
180
|
+
return link.raw # HMD001/HMD002/HMD003, already reported by lint
|
|
181
|
+
|
|
182
|
+
# Vetoed: inlining would copy the target's bytes into this page, which is
|
|
183
|
+
# the one outcome a publication gate must not allow. Reported as HMD017.
|
|
184
|
+
if can_embed is not None and not can_embed(result.path):
|
|
185
|
+
return rewrite(link, result.path) if rewrite is not None else link.raw
|
|
186
|
+
|
|
187
|
+
target = workspace.documents.get(result.path)
|
|
188
|
+
if target is None:
|
|
189
|
+
return link.raw
|
|
190
|
+
|
|
191
|
+
region = _target_region(target, link)
|
|
192
|
+
if region is None:
|
|
193
|
+
return link.raw # HMD004/HMD005, already reported by lint
|
|
194
|
+
|
|
195
|
+
key = (result.path, link.fragment)
|
|
196
|
+
if key in stack:
|
|
197
|
+
chain = " -> ".join(workspace.rel(p) for p, _ in stack[stack.index(key) :])
|
|
198
|
+
diagnostics.append(
|
|
199
|
+
_at(workspace, document, link, "HMD007", f"embed cycle: {chain} -> {workspace.rel(result.path)}")
|
|
200
|
+
)
|
|
201
|
+
return link.raw
|
|
202
|
+
|
|
203
|
+
if len(stack) >= MAX_EMBED_DEPTH:
|
|
204
|
+
diagnostics.append(
|
|
205
|
+
_at(workspace, document, link, "HMD008", f"embed depth exceeds the limit of {MAX_EMBED_DEPTH}")
|
|
206
|
+
)
|
|
207
|
+
return link.raw
|
|
208
|
+
|
|
209
|
+
stack.append(key)
|
|
210
|
+
try:
|
|
211
|
+
expanded = _region(
|
|
212
|
+
workspace, target, region[0], region[1], stack, diagnostics, rewrite, can_embed
|
|
213
|
+
)
|
|
214
|
+
finally:
|
|
215
|
+
stack.pop()
|
|
216
|
+
return expanded.strip()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _at(workspace: Workspace, document: Document, link: Link, rule: str, message: str) -> Diagnostic:
|
|
220
|
+
return Diagnostic(
|
|
221
|
+
rule,
|
|
222
|
+
ERROR,
|
|
223
|
+
workspace.rel(document.path),
|
|
224
|
+
link.span.line,
|
|
225
|
+
link.span.column,
|
|
226
|
+
message,
|
|
227
|
+
)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Frontmatter parsing and the reserved keys (HMD-0001 §5.3, HMD-0002 §2).
|
|
2
|
+
|
|
3
|
+
`tags`, `use`, `import`, and `nav` are reserved for the toolchain. The set is
|
|
4
|
+
closed and enumerated here; every other key stays user-owned and unexamined
|
|
5
|
+
(P3). `nav` was added by HMD-0002, which is an amendment to that closed set
|
|
6
|
+
rather than an extension of it — worth noticing, not repeating casually.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
|
|
13
|
+
from .imports import ImportError_, parse_statement
|
|
14
|
+
from .model import VISIBILITIES, CardConfig, ImportStmt, NavConfig
|
|
15
|
+
|
|
16
|
+
RESERVED_KEYS = frozenset({"tags", "use", "import", "nav"})
|
|
17
|
+
|
|
18
|
+
#: Keys recognized inside the `nav` mapping.
|
|
19
|
+
NAV_KEYS = frozenset({"order", "visibility"})
|
|
20
|
+
|
|
21
|
+
#: Features nameable in `use`. Prefixing `no_` disables, as in vim's `set no…`.
|
|
22
|
+
KNOWN_FEATURES = frozenset({"autodiscovery"})
|
|
23
|
+
|
|
24
|
+
_FENCE = "---"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def split_frontmatter(text: str) -> tuple[str | None, str, int]:
|
|
28
|
+
"""Split `text` into (raw_yaml, body, body_offset).
|
|
29
|
+
|
|
30
|
+
The fence must begin at byte 0 and close with a `---` line; anything else is
|
|
31
|
+
a document with no frontmatter at all.
|
|
32
|
+
"""
|
|
33
|
+
if not text.startswith(_FENCE):
|
|
34
|
+
return None, text, 0
|
|
35
|
+
|
|
36
|
+
lines = text.splitlines(keepends=True)
|
|
37
|
+
if not lines or lines[0].rstrip("\r\n") != _FENCE:
|
|
38
|
+
return None, text, 0
|
|
39
|
+
|
|
40
|
+
offset = len(lines[0])
|
|
41
|
+
for line in lines[1:]:
|
|
42
|
+
if line.rstrip("\r\n") == _FENCE:
|
|
43
|
+
raw = text[len(lines[0]) : offset]
|
|
44
|
+
end = offset + len(line)
|
|
45
|
+
return raw, text[end:], end
|
|
46
|
+
offset += len(line)
|
|
47
|
+
|
|
48
|
+
return None, text, 0 # unterminated fence: not frontmatter
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_yaml(raw: str) -> dict:
|
|
52
|
+
"""Parse frontmatter YAML, or raise `ValueError` (HMD009)."""
|
|
53
|
+
try:
|
|
54
|
+
data = yaml.safe_load(raw)
|
|
55
|
+
except yaml.YAMLError as exc:
|
|
56
|
+
raise ValueError(f"invalid YAML: {_one_line(exc)}") from exc
|
|
57
|
+
if data is None:
|
|
58
|
+
return {}
|
|
59
|
+
if not isinstance(data, dict):
|
|
60
|
+
raise ValueError(f"frontmatter must be a mapping, got {type(data).__name__}")
|
|
61
|
+
return data
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def parse_card_config(data: dict) -> tuple[CardConfig, list[tuple[str, str]]]:
|
|
65
|
+
"""Read the reserved keys out of `data`.
|
|
66
|
+
|
|
67
|
+
Returns the config plus a list of (rule_id, message) problems, so the caller
|
|
68
|
+
can attach them to a span. Unrecognized input is reported rather than
|
|
69
|
+
ignored: silently dropping a misspelled `no_autodiscovry` would hand the
|
|
70
|
+
author the default while they believe they configured something else.
|
|
71
|
+
"""
|
|
72
|
+
problems: list[tuple[str, str]] = []
|
|
73
|
+
|
|
74
|
+
tags = _parse_tags(data.get("tags"), problems)
|
|
75
|
+
use = _parse_use(data.get("use"), problems)
|
|
76
|
+
imports = _parse_imports(data.get("import"), problems)
|
|
77
|
+
nav = _parse_nav(data.get("nav"), problems)
|
|
78
|
+
|
|
79
|
+
return CardConfig(tags=tags, use=use, imports=imports, nav=nav), problems
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _parse_nav(value, problems) -> NavConfig:
|
|
83
|
+
"""`nav` places a card in a published site (HMD-0002 §2).
|
|
84
|
+
|
|
85
|
+
A mapping, so the key has room to grow. `nav: 10` was the earlier spelling
|
|
86
|
+
and is now a defect — named as such rather than accepted quietly, since a
|
|
87
|
+
card carrying it means to be ordered and would otherwise sort last.
|
|
88
|
+
"""
|
|
89
|
+
if value is None:
|
|
90
|
+
return NavConfig()
|
|
91
|
+
if not isinstance(value, dict):
|
|
92
|
+
hint = " — write `nav:` with an `order:` under it" if isinstance(value, int) else ""
|
|
93
|
+
problems.append(("HMD013", f"`nav` must be a mapping, got {type(value).__name__}{hint}"))
|
|
94
|
+
return NavConfig()
|
|
95
|
+
|
|
96
|
+
for key in sorted(set(value) - NAV_KEYS):
|
|
97
|
+
known = ", ".join(sorted(NAV_KEYS))
|
|
98
|
+
problems.append(("HMD013", f"unknown key {key!r} in `nav` (known: {known})"))
|
|
99
|
+
|
|
100
|
+
return NavConfig(
|
|
101
|
+
order=_parse_nav_order(value.get("order"), problems),
|
|
102
|
+
visibility=_parse_visibility(value.get("visibility"), problems),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _parse_nav_order(value, problems) -> int | None:
|
|
107
|
+
if value is None:
|
|
108
|
+
return None
|
|
109
|
+
# `True` is an int in Python, and `order: yes` is a mistake worth naming.
|
|
110
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
111
|
+
problems.append(("HMD013", f"`nav.order` must be an integer, got {value!r}"))
|
|
112
|
+
return None
|
|
113
|
+
return value
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _parse_visibility(value, problems) -> str | None:
|
|
117
|
+
"""`nav.visibility` gates publication (HMD-0002 §2).
|
|
118
|
+
|
|
119
|
+
None means inherit, not public. Getting this wrong publishes a card nobody
|
|
120
|
+
meant to publish, so an unrecognized value is rejected rather than coerced.
|
|
121
|
+
"""
|
|
122
|
+
if value is None:
|
|
123
|
+
return None
|
|
124
|
+
# `visibility: no` is YAML for False, and reads as if it meant something.
|
|
125
|
+
if not isinstance(value, str) or value not in VISIBILITIES:
|
|
126
|
+
known = ", ".join(sorted(VISIBILITIES))
|
|
127
|
+
problems.append(("HMD013", f"`nav.visibility` must be one of {known}; got {value!r}"))
|
|
128
|
+
return None
|
|
129
|
+
return value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _parse_tags(value, problems) -> tuple[str, ...]:
|
|
133
|
+
if value is None:
|
|
134
|
+
return ()
|
|
135
|
+
if not isinstance(value, list):
|
|
136
|
+
problems.append(("HMD013", f"`tags` must be a list, got {type(value).__name__}"))
|
|
137
|
+
return ()
|
|
138
|
+
tags = []
|
|
139
|
+
for item in value:
|
|
140
|
+
if not isinstance(item, str) or not item.strip():
|
|
141
|
+
problems.append(("HMD013", f"`tags` entries must be non-empty strings, got {item!r}"))
|
|
142
|
+
continue
|
|
143
|
+
tags.append(item.strip())
|
|
144
|
+
return tuple(tags)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _parse_use(value, problems) -> dict[str, bool]:
|
|
148
|
+
if value is None:
|
|
149
|
+
return {}
|
|
150
|
+
if isinstance(value, str):
|
|
151
|
+
value = [value]
|
|
152
|
+
if not isinstance(value, list):
|
|
153
|
+
problems.append(("HMD013", f"`use` must be a string or list, got {type(value).__name__}"))
|
|
154
|
+
return {}
|
|
155
|
+
|
|
156
|
+
use: dict[str, bool] = {}
|
|
157
|
+
for item in value:
|
|
158
|
+
if not isinstance(item, str):
|
|
159
|
+
problems.append(("HMD013", f"`use` entries must be strings, got {item!r}"))
|
|
160
|
+
continue
|
|
161
|
+
name, enabled = item.strip(), True
|
|
162
|
+
if name.startswith("no_"):
|
|
163
|
+
name, enabled = name[3:], False
|
|
164
|
+
if name not in KNOWN_FEATURES:
|
|
165
|
+
known = ", ".join(sorted(KNOWN_FEATURES))
|
|
166
|
+
problems.append(("HMD013", f"unknown feature {item.strip()!r} in `use` (known: {known})"))
|
|
167
|
+
continue
|
|
168
|
+
use[name] = enabled
|
|
169
|
+
return use
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _parse_imports(value, problems) -> tuple[ImportStmt, ...]:
|
|
173
|
+
if value is None:
|
|
174
|
+
return ()
|
|
175
|
+
if isinstance(value, str):
|
|
176
|
+
value = [value]
|
|
177
|
+
if not isinstance(value, list):
|
|
178
|
+
problems.append(("HMD014", f"`import` must be a string or list, got {type(value).__name__}"))
|
|
179
|
+
return ()
|
|
180
|
+
|
|
181
|
+
stmts: list[ImportStmt] = []
|
|
182
|
+
for item in value:
|
|
183
|
+
try:
|
|
184
|
+
stmts.append(parse_statement(item))
|
|
185
|
+
except ImportError_ as exc:
|
|
186
|
+
problems.append(("HMD014", str(exc)))
|
|
187
|
+
return tuple(stmts)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _one_line(exc: Exception) -> str:
|
|
191
|
+
return " ".join(str(exc).split())
|
hypermarkdown/graph.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Resolved-graph assembly and JSON serialization (HMD-0001 §7)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from .resolve import Outcome, Workspace
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def build(workspace: Workspace) -> dict:
|
|
11
|
+
"""Nodes with frontmatter and headings, edges with kind and source span."""
|
|
12
|
+
nodes = []
|
|
13
|
+
edges = []
|
|
14
|
+
|
|
15
|
+
for path in workspace.pages():
|
|
16
|
+
document = workspace.documents[path]
|
|
17
|
+
rel = workspace.rel(path)
|
|
18
|
+
table = workspace.import_table(path)
|
|
19
|
+
nodes.append(
|
|
20
|
+
{
|
|
21
|
+
"path": rel,
|
|
22
|
+
"namespace": path.parent.relative_to(workspace.root).as_posix() or "/",
|
|
23
|
+
"tags": list(document.card.tags),
|
|
24
|
+
"frontmatter": _plain(document.frontmatter),
|
|
25
|
+
"headings": [
|
|
26
|
+
{"level": h.level, "text": h.text, "slug": h.slug, "line": h.span.line}
|
|
27
|
+
for h in document.headings
|
|
28
|
+
],
|
|
29
|
+
"anchors": [a.block_id for a in document.anchors],
|
|
30
|
+
"autodiscovery": workspace.autodiscovery_enabled(path),
|
|
31
|
+
"imports": {
|
|
32
|
+
"bindings": {k: workspace.rel(v) for k, v in sorted(table.bindings.items())},
|
|
33
|
+
"search_paths": [workspace.rel(p) if p != workspace.root else "/" for p in table.search_paths],
|
|
34
|
+
},
|
|
35
|
+
}
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
for link in document.links:
|
|
39
|
+
result = workspace.resolve(path, link.page_ref)
|
|
40
|
+
edges.append(
|
|
41
|
+
{
|
|
42
|
+
"source": rel,
|
|
43
|
+
"target": workspace.rel(result.path) if result.path else None,
|
|
44
|
+
"kind": "embed" if link.is_embed else "link",
|
|
45
|
+
"raw": link.raw,
|
|
46
|
+
"outcome": result.outcome.value,
|
|
47
|
+
"phase": result.phase,
|
|
48
|
+
"fragment": link.fragment,
|
|
49
|
+
"line": link.span.line,
|
|
50
|
+
"column": link.span.column,
|
|
51
|
+
}
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
nodes.sort(key=lambda n: n["path"])
|
|
55
|
+
edges.sort(key=lambda e: (e["source"], e["line"], e["column"]))
|
|
56
|
+
return {"root": str(workspace.root), "nodes": nodes, "edges": edges}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def to_json(workspace: Workspace) -> str:
|
|
60
|
+
return json.dumps(build(workspace), indent=2, sort_keys=True)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _plain(value):
|
|
64
|
+
"""Coerce YAML scalars to JSON-serializable values."""
|
|
65
|
+
if isinstance(value, dict):
|
|
66
|
+
return {str(k): _plain(v) for k, v in value.items()}
|
|
67
|
+
if isinstance(value, (list, tuple)):
|
|
68
|
+
return [_plain(v) for v in value]
|
|
69
|
+
if isinstance(value, (str, int, float, bool)) or value is None:
|
|
70
|
+
return value
|
|
71
|
+
return str(value)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
__all__ = ["build", "to_json", "Outcome"]
|
hypermarkdown/imports.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""The ``from <ref> import <names>`` mini-grammar (HMD-0001 §5.3).
|
|
2
|
+
|
|
3
|
+
A one-line statement form rather than nested YAML: the grammar is trivial and
|
|
4
|
+
the statement reads at a glance, which nested `from:`/`names:` keys would not.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
from .model import ImportStmt
|
|
12
|
+
|
|
13
|
+
_STMT_RE = re.compile(r"^from\s+(?P<ref>\S+)\s+import\s+(?P<names>.+?)\s*$")
|
|
14
|
+
_NAME_RE = re.compile(r"^(?P<name>[^\s/]+)(?:\s+as\s+(?P<alias>[^\s/]+))?$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ImportError_(ValueError):
|
|
18
|
+
"""A malformed import statement (HMD014)."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def is_qualified(ref: str) -> bool:
|
|
22
|
+
"""True if `ref` is absolute or relative, as an import ref must be.
|
|
23
|
+
|
|
24
|
+
A bare ref would need resolving by the very algorithm the import feeds, and
|
|
25
|
+
that circularity has no good answer.
|
|
26
|
+
"""
|
|
27
|
+
return ref.startswith("/") or ref.startswith("./") or ref.startswith("../")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_statement(raw: str) -> ImportStmt:
|
|
31
|
+
"""Parse one statement, or raise `ImportError_` (HMD014)."""
|
|
32
|
+
if not isinstance(raw, str):
|
|
33
|
+
raise ImportError_(f"import entry must be a string, got {type(raw).__name__}")
|
|
34
|
+
|
|
35
|
+
m = _STMT_RE.match(raw.strip())
|
|
36
|
+
if not m:
|
|
37
|
+
raise ImportError_(f"expected 'from <ref> import <names>', got {raw.strip()!r}")
|
|
38
|
+
|
|
39
|
+
ref = m.group("ref")
|
|
40
|
+
if not is_qualified(ref):
|
|
41
|
+
raise ImportError_(
|
|
42
|
+
f"import ref {ref!r} must be absolute ('/x') or relative ('./x', '../x'), never bare"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
names = m.group("names").strip()
|
|
46
|
+
if names == "*":
|
|
47
|
+
return ImportStmt(ref=ref, wildcard=True, bindings=(), raw=raw.strip())
|
|
48
|
+
|
|
49
|
+
bindings: list[tuple[str, str]] = []
|
|
50
|
+
for part in names.split(","):
|
|
51
|
+
part = part.strip()
|
|
52
|
+
if not part:
|
|
53
|
+
raise ImportError_(f"empty name in import list: {raw.strip()!r}")
|
|
54
|
+
if part == "*":
|
|
55
|
+
raise ImportError_("'*' may not be combined with named imports")
|
|
56
|
+
nm = _NAME_RE.match(part)
|
|
57
|
+
if not nm:
|
|
58
|
+
raise ImportError_(f"expected '<name>' or '<name> as <alias>', got {part!r}")
|
|
59
|
+
name = nm.group("name")
|
|
60
|
+
bindings.append((name, nm.group("alias") or name))
|
|
61
|
+
|
|
62
|
+
return ImportStmt(ref=ref, wildcard=False, bindings=tuple(bindings), raw=raw.strip())
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Text and JSON reporters (HMD-0001 §7).
|
|
2
|
+
|
|
3
|
+
JSON output is identical in content to the text output, so CI and a future
|
|
4
|
+
editor client consume the same data.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from ..model import ERROR, WARNING, Diagnostic
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def summarize(diagnostics: list[Diagnostic], strict: bool = False) -> tuple[int, int]:
|
|
15
|
+
"""Return (errors, warnings). Under `strict` every warning counts as an error."""
|
|
16
|
+
errors = sum(1 for d in diagnostics if d.severity == ERROR)
|
|
17
|
+
warnings = sum(1 for d in diagnostics if d.severity == WARNING)
|
|
18
|
+
if strict:
|
|
19
|
+
return errors + warnings, 0
|
|
20
|
+
return errors, warnings
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def format_text(diagnostics: list[Diagnostic], strict: bool = False) -> str:
|
|
24
|
+
lines = [
|
|
25
|
+
f"{d.path}:{d.line}:{d.column}: {d.severity}[{d.rule}] {d.message}" for d in diagnostics
|
|
26
|
+
]
|
|
27
|
+
errors, warnings = summarize(diagnostics, strict)
|
|
28
|
+
if not diagnostics:
|
|
29
|
+
lines.append("clean: no diagnostics")
|
|
30
|
+
else:
|
|
31
|
+
lines.append("")
|
|
32
|
+
lines.append(f"{errors} error(s), {warnings} warning(s)")
|
|
33
|
+
return "\n".join(lines)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def format_json(diagnostics: list[Diagnostic], strict: bool = False) -> str:
|
|
37
|
+
errors, warnings = summarize(diagnostics, strict)
|
|
38
|
+
payload = {
|
|
39
|
+
"diagnostics": [d.to_dict() for d in diagnostics],
|
|
40
|
+
"errors": errors,
|
|
41
|
+
"warnings": warnings,
|
|
42
|
+
}
|
|
43
|
+
# sort_keys for byte-identical output across runs (P1).
|
|
44
|
+
return json.dumps(payload, indent=2, sort_keys=True)
|