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.
@@ -0,0 +1,31 @@
1
+ """HyperMarkDown — a strict, machine-checkable markdown dialect.
2
+
3
+ The **canonical** implementation of the format: where this and any other
4
+ implementation disagree about a case the conformance corpus covers, this one
5
+ defines the correct answer. Every consumer here (CLI, MkDocs plugin, the language
6
+ server to come) is a thin client over the same semantics.
7
+
8
+ Canonical is not sole. The old principle that semantics live in one
9
+ implementation is retired — a second implementation exists in TypeScript, and the
10
+ corpus at `examples/conformance/cases/` plus a ledger of expected failures is
11
+ what keeps the two from drifting into dialects.
12
+ """
13
+
14
+ from .config import Config, ConfigError
15
+ from .model import Diagnostic, Document, Link, Span
16
+ from .resolve import Outcome, Resolution, Workspace
17
+
18
+ __version__ = "0.2.0"
19
+
20
+ __all__ = [
21
+ "Config",
22
+ "ConfigError",
23
+ "Diagnostic",
24
+ "Document",
25
+ "Link",
26
+ "Outcome",
27
+ "Resolution",
28
+ "Span",
29
+ "Workspace",
30
+ "__version__",
31
+ ]
hypermarkdown/cli.py ADDED
@@ -0,0 +1,177 @@
1
+ """The `hmd` command-line interface (HMD-0001 §7).
2
+
3
+ All semantics live in the library; this layer is argument parsing and
4
+ formatting only, so a future `hmd lsp` answers from the same code rather than
5
+ from a second reading of the specification.
6
+
7
+ Exit codes are pinned: 0 clean, 1 diagnostics, 2 usage or internal failure.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+ from typing import Optional
14
+
15
+ import typer
16
+
17
+ from . import __version__
18
+ from . import config as config_mod
19
+ from . import graph as graph_mod
20
+ from .lint import check, format_json, format_text, summarize
21
+ from .model import Diagnostic
22
+ from .render import flat
23
+ from .resolve import SUFFIX, Workspace
24
+
25
+ app = typer.Typer(
26
+ add_completion=False,
27
+ help="Lint, query, and inspect a HyperMarkDown knowledge base.",
28
+ no_args_is_help=True,
29
+ )
30
+
31
+ EXIT_OK = 0
32
+ EXIT_DIAGNOSTICS = 1
33
+ EXIT_USAGE = 2
34
+
35
+ RootOption = typer.Option(None, "--root", help="Namespace root (default: the `wiki` setting, or doc/wiki).")
36
+ FormatOption = typer.Option("text", "--format", help="Output format: text or json.")
37
+
38
+
39
+ def _show_version(value: bool) -> None:
40
+ """Report the module's version, not the installed distribution's.
41
+
42
+ `importlib.metadata` would answer for the wheel on the path, which is the
43
+ wrong answer in a checkout — the number a contributor is about to tag lives
44
+ in `__init__.py`, and `hmd --version` should show that one.
45
+ """
46
+ if value:
47
+ typer.echo(f"hmd {__version__}")
48
+ raise typer.Exit(EXIT_OK)
49
+
50
+
51
+ @app.callback()
52
+ def cli(
53
+ version: bool = typer.Option(
54
+ False,
55
+ "--version",
56
+ callback=_show_version,
57
+ is_eager=True,
58
+ help="Show the version and exit.",
59
+ ),
60
+ ) -> None:
61
+ """Lint, query, and inspect a HyperMarkDown knowledge base."""
62
+
63
+
64
+ def _workspace(root: Optional[Path], start: Path | None = None) -> Workspace:
65
+ try:
66
+ cfg = config_mod.load(root_override=root, start=start)
67
+ except config_mod.ConfigError as exc:
68
+ typer.echo(f"hmd: {exc}", err=True)
69
+ raise typer.Exit(EXIT_USAGE)
70
+ return Workspace(cfg)
71
+
72
+
73
+ def _selected(workspace: Workspace, paths: list[Path] | None) -> list[Path] | None:
74
+ """Map CLI paths onto pages in the workspace, or None for the whole tree."""
75
+ if not paths:
76
+ return None
77
+ selected: list[Path] = []
78
+ for raw in paths:
79
+ candidate = raw.resolve()
80
+ if candidate.is_dir():
81
+ selected.extend(p for p in workspace.pages() if candidate in p.parents or candidate == p.parent)
82
+ elif candidate.suffix == SUFFIX:
83
+ if candidate not in workspace.documents:
84
+ typer.echo(f"hmd: not inside the namespace root: {raw}", err=True)
85
+ raise typer.Exit(EXIT_USAGE)
86
+ selected.append(candidate)
87
+ else:
88
+ typer.echo(f"hmd: not a {SUFFIX} file or directory: {raw}", err=True)
89
+ raise typer.Exit(EXIT_USAGE)
90
+ return sorted(set(selected))
91
+
92
+
93
+ @app.command()
94
+ def lint(
95
+ paths: Optional[list[Path]] = typer.Argument(None, help="Files or directories; default is the whole tree."),
96
+ root: Optional[Path] = RootOption,
97
+ output_format: str = FormatOption,
98
+ strict: bool = typer.Option(False, "--strict", help="Count warnings as errors."),
99
+ ) -> None:
100
+ """Parse, resolve, and report. The MVP's primary command."""
101
+ if output_format not in ("text", "json"):
102
+ typer.echo(f"hmd: unknown format {output_format!r} (expected text or json)", err=True)
103
+ raise typer.Exit(EXIT_USAGE)
104
+
105
+ workspace = _workspace(root)
106
+ diagnostics = check(workspace, _selected(workspace, paths))
107
+
108
+ render = format_json if output_format == "json" else format_text
109
+ typer.echo(render(diagnostics, strict))
110
+
111
+ errors, _ = summarize(diagnostics, strict)
112
+ raise typer.Exit(EXIT_DIAGNOSTICS if errors else EXIT_OK)
113
+
114
+
115
+ @app.command()
116
+ def graph(
117
+ root: Optional[Path] = RootOption,
118
+ output_format: str = typer.Option("json", "--format", help="Output format: json."),
119
+ ) -> None:
120
+ """Dump the resolved graph."""
121
+ if output_format != "json":
122
+ typer.echo(f"hmd: graph supports --format json only, got {output_format!r}", err=True)
123
+ raise typer.Exit(EXIT_USAGE)
124
+ typer.echo(graph_mod.to_json(_workspace(root)))
125
+
126
+
127
+ @app.command()
128
+ def render(
129
+ path: Path = typer.Argument(..., help="The card to render."),
130
+ root: Optional[Path] = RootOption,
131
+ to: str = typer.Option("markdown", "--to", help="Output format: markdown or html."),
132
+ ) -> None:
133
+ """Expand embeds and rewrite resolved links.
134
+
135
+ Flat markdown is a one-way build product; it does not round-trip back into
136
+ `.hmd`.
137
+ """
138
+ if to not in ("markdown", "html"):
139
+ typer.echo(f"hmd: unknown target {to!r} (expected markdown or html)", err=True)
140
+ raise typer.Exit(EXIT_USAGE)
141
+
142
+ workspace = _workspace(root)
143
+ target = path.resolve()
144
+ if target not in workspace.documents:
145
+ typer.echo(f"hmd: not a page inside the namespace root: {path}", err=True)
146
+ raise typer.Exit(EXIT_USAGE)
147
+
148
+ result = flat.to_html(workspace, target) if to == "html" else flat.render(workspace, target)
149
+ typer.echo(result.text)
150
+
151
+ for diagnostic in sorted(result.diagnostics, key=Diagnostic.sort_key):
152
+ typer.echo(
153
+ f"{diagnostic.path}:{diagnostic.line}:{diagnostic.column}: "
154
+ f"{diagnostic.severity}[{diagnostic.rule}] {diagnostic.message}",
155
+ err=True,
156
+ )
157
+ raise typer.Exit(EXIT_DIAGNOSTICS if result.diagnostics else EXIT_OK)
158
+
159
+
160
+ @app.command()
161
+ def info(root: Optional[Path] = RootOption) -> None:
162
+ """Show the resolved root and discovery policy."""
163
+ workspace = _workspace(root)
164
+ cfg = workspace.config
165
+ typer.echo(f"root: {cfg.root}")
166
+ typer.echo(f"config: {cfg.source or '(none — using defaults)'}")
167
+ typer.echo(f"autodiscovery: {cfg.autodiscovery}")
168
+ typer.echo(f"mode: {cfg.mode}")
169
+ typer.echo(f"pages: {len(workspace.pages())}")
170
+
171
+
172
+ def main() -> None: # pragma: no cover - console-script shim
173
+ app()
174
+
175
+
176
+ if __name__ == "__main__": # pragma: no cover
177
+ main()
@@ -0,0 +1,110 @@
1
+ """Root discovery and `.hmd/config.toml` (HMD-0001 §4, §5.3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ MARKER_DIR = ".hmd"
10
+ CONFIG_NAME = "config.toml"
11
+ DEFAULT_WIKI = "doc/wiki"
12
+ DEFAULT_MODE = "both"
13
+ VALID_MODES = frozenset({"both", "recursive"})
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Config:
18
+ """Resolved project configuration."""
19
+
20
+ root: Path # the namespace root, absolute
21
+ autodiscovery: bool = True
22
+ mode: str = DEFAULT_MODE
23
+ source: Path | None = None # the config file actually read, if any
24
+
25
+
26
+ class ConfigError(Exception):
27
+ """An unusable root or config file — exit code 2, not a lint finding."""
28
+
29
+
30
+ def find_project_root(start: Path) -> Path | None:
31
+ """Nearest ancestor holding `.hmd/`, else nearest holding `.git`."""
32
+ start = start.resolve()
33
+ candidates = [start, *start.parents] if start.is_dir() else list(start.parents)
34
+ for parent in candidates:
35
+ if (parent / MARKER_DIR).is_dir():
36
+ return parent
37
+ for parent in candidates:
38
+ if (parent / ".git").exists():
39
+ return parent
40
+ return None
41
+
42
+
43
+ def load(root_override: Path | None = None, start: Path | None = None) -> Config:
44
+ """Resolve the namespace root and discovery policy.
45
+
46
+ Absent `.hmd/config.toml` entirely, the root is `doc/wiki`, autodiscovery is
47
+ on, and the mode is `both` — a tree with no configuration behaves the way a
48
+ new author expects.
49
+ """
50
+ if root_override is not None:
51
+ root = root_override.resolve()
52
+ if not root.is_dir():
53
+ raise ConfigError(f"root is not a directory: {root}")
54
+ project = find_project_root(root) or root
55
+ data, source = _read(project)
56
+ return Config(
57
+ root=root,
58
+ autodiscovery=_autodiscovery(data),
59
+ mode=_mode(data),
60
+ source=source,
61
+ )
62
+
63
+ start = (start or Path.cwd()).resolve()
64
+ project = find_project_root(start)
65
+ if project is None:
66
+ raise ConfigError(
67
+ f"no project root above {start}: expected a .hmd/ or .git directory. "
68
+ f"Pass --root to name the namespace root directly."
69
+ )
70
+
71
+ data, source = _read(project)
72
+ wiki = data.get("wiki", DEFAULT_WIKI)
73
+ if not isinstance(wiki, str):
74
+ raise ConfigError(f"`wiki` must be a string in {source}")
75
+
76
+ root = (project / wiki).resolve()
77
+ if not root.is_dir():
78
+ raise ConfigError(f"namespace root does not exist: {root}")
79
+
80
+ return Config(root=root, autodiscovery=_autodiscovery(data), mode=_mode(data), source=source)
81
+
82
+
83
+ def _read(project: Path) -> tuple[dict, Path | None]:
84
+ path = project / MARKER_DIR / CONFIG_NAME
85
+ if not path.is_file():
86
+ return {}, None
87
+ try:
88
+ with path.open("rb") as handle:
89
+ return tomllib.load(handle), path
90
+ except (OSError, tomllib.TOMLDecodeError) as exc:
91
+ raise ConfigError(f"cannot read {path}: {exc}") from exc
92
+
93
+
94
+ def _discovery(data: dict) -> dict:
95
+ section = data.get("discovery", {})
96
+ return section if isinstance(section, dict) else {}
97
+
98
+
99
+ def _autodiscovery(data: dict) -> bool:
100
+ value = _discovery(data).get("autodiscovery", True)
101
+ if not isinstance(value, bool):
102
+ raise ConfigError("[discovery] autodiscovery must be a boolean")
103
+ return value
104
+
105
+
106
+ def _mode(data: dict) -> str:
107
+ value = _discovery(data).get("mode", DEFAULT_MODE)
108
+ if value not in VALID_MODES:
109
+ raise ConfigError(f"[discovery] mode must be one of {sorted(VALID_MODES)}, got {value!r}")
110
+ return value
@@ -0,0 +1,169 @@
1
+ """D2 diagrams for the Python line (HMD-0022 §5-§7).
2
+
3
+ HMD-0022 is a proposal of the TypeScript line and does not change this one: a
4
+ site build has a build step and no webview, so the no-subprocess rule of its §1
5
+ does not apply here and the `d2` binary stays the engine. What this module
6
+ takes from it is the part that *is* shared — the semantics.
7
+
8
+ - A ```` ```d2 ```` fence is a diagram. Its body is opaque to the resolver, and
9
+ produces no links and no graph edges (§7). The scanner already guarantees
10
+ this by masking fences.
11
+ - A missing engine degrades to a labelled placeholder showing the source, never
12
+ to a blank and never to a build failure (§5). A diagram that is merely not
13
+ drawn is not a defect in the card and must not look like one.
14
+ - Rendered SVG reaches the page as a `data:` URI `<img>`, never as inline markup
15
+ (§6). Diagram source comes from a cloned repository, SVG is a scripting
16
+ context, and an `<img>` cannot execute its payload. The cost is that diagrams
17
+ are not interactive, which is the right trade for a documentation diagram.
18
+ - The bounds of §4 are shared verbatim, so both lines refuse the same input.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import base64
24
+ import hashlib
25
+ import shutil
26
+ import subprocess
27
+ from collections import OrderedDict
28
+ from dataclasses import dataclass
29
+
30
+ #: The fence info strings this module claims.
31
+ LANGUAGES = frozenset({"d2"})
32
+
33
+ #: Bounds on a single render (HMD-0022 §4). Shared with the TypeScript line so
34
+ #: that a diagram refused there is refused here.
35
+ TIMEOUT_SECONDS = 2
36
+ MAX_SOURCE_BYTES = 64 * 1024
37
+ CACHE_ENTRIES = 64
38
+
39
+ #: Default for `D2Engine(executable=…)`, distinguishing "find one" from "none".
40
+ DISCOVER = "\0discover"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Result:
45
+ """Either an SVG, or the reason there isn't one. Never both, never neither."""
46
+
47
+ svg: str | None = None
48
+ failure: str | None = None
49
+
50
+
51
+ class D2Engine:
52
+ """Renders through the `d2` binary, if one is on PATH.
53
+
54
+ The engine is content-addressed and bounded rather than clever: the same
55
+ source and version produce the same bytes (P1), and a hostile diagram fails
56
+ instead of hanging.
57
+ """
58
+
59
+ id = "d2-binary"
60
+
61
+ def __init__(self, executable: str | None = DISCOVER):
62
+ # `None` means "no engine" and must stay expressible; discovery is what
63
+ # the default argument asks for, not what an explicit None asks for.
64
+ self.executable = shutil.which("d2") if executable is DISCOVER else executable
65
+ self._cache: OrderedDict[str, Result] = OrderedDict()
66
+ self._version: str | None = None
67
+
68
+ @property
69
+ def available(self) -> bool:
70
+ return self.executable is not None
71
+
72
+ @property
73
+ def version(self) -> str:
74
+ if not self.available:
75
+ return "none"
76
+ try:
77
+ done = subprocess.run(
78
+ [self.executable, "--version"],
79
+ capture_output=True,
80
+ text=True,
81
+ timeout=TIMEOUT_SECONDS,
82
+ )
83
+ except (OSError, subprocess.SubprocessError):
84
+ return "unknown"
85
+ return done.stdout.strip() or "unknown"
86
+
87
+ def render(self, source: str) -> Result:
88
+ if not self.available:
89
+ return Result(failure="no d2 engine is installed")
90
+
91
+ encoded = source.encode("utf-8")
92
+ if len(encoded) > MAX_SOURCE_BYTES:
93
+ return Result(failure=f"diagram source exceeds {MAX_SOURCE_BYTES // 1024} KiB")
94
+
95
+ key = self._key(source)
96
+ if key in self._cache:
97
+ self._cache.move_to_end(key)
98
+ return self._cache[key]
99
+
100
+ return self._store(key, self._run(encoded))
101
+
102
+ def _run(self, encoded: bytes) -> Result:
103
+ try:
104
+ done = subprocess.run(
105
+ [self.executable, "-", "-"],
106
+ input=encoded,
107
+ capture_output=True,
108
+ timeout=TIMEOUT_SECONDS,
109
+ )
110
+ except subprocess.TimeoutExpired:
111
+ return Result(failure=f"diagram render exceeded {TIMEOUT_SECONDS}s")
112
+ except OSError as exc:
113
+ return Result(failure=f"cannot run d2: {exc}")
114
+
115
+ if done.returncode != 0:
116
+ detail = done.stderr.decode("utf-8", "replace").strip().splitlines()
117
+ return Result(failure=detail[-1] if detail else "d2 exited non-zero")
118
+ return Result(svg=done.stdout.decode("utf-8", "replace"))
119
+
120
+ def _key(self, source: str) -> str:
121
+ """Every input that can change the output is in the key (§4)."""
122
+ if self._version is None:
123
+ self._version = self.version
124
+ digest = hashlib.sha256(source.encode("utf-8")).hexdigest()
125
+ return f"{digest}|{self.id}|{self._version}"
126
+
127
+ def _store(self, key: str, result: Result) -> Result:
128
+ self._cache[key] = result
129
+ # Bounded LRU: an unbounded cache in a long-lived process is a leak with
130
+ # a slow fuse, and 64 live diagrams in one build is not the case worth
131
+ # optimising for.
132
+ while len(self._cache) > CACHE_ENTRIES:
133
+ self._cache.popitem(last=False)
134
+ return result
135
+
136
+
137
+ def to_html(language: str, source: str, engine: D2Engine) -> str:
138
+ """Render one diagram fence to HTML, degrading rather than failing."""
139
+ result = engine.render(source)
140
+ if result.svg:
141
+ return _image(result.svg, language)
142
+ return _placeholder(language, source, result.failure or "not rendered")
143
+
144
+
145
+ def _image(svg: str, language: str) -> str:
146
+ """An `<img>` with a `data:` payload — SVG that cannot execute (§6)."""
147
+ payload = base64.b64encode(svg.encode("utf-8")).decode("ascii")
148
+ return (
149
+ f'<p class="hmd-diagram"><img alt="{language} diagram" '
150
+ f'src="data:image/svg+xml;base64,{payload}"></p>'
151
+ )
152
+
153
+
154
+ def _placeholder(language: str, source: str, reason: str) -> str:
155
+ """The source, labelled, with the reason it was not drawn (§5).
156
+
157
+ Shown *with* the source rather than instead of it: an author needs to see
158
+ what failed in order to fix it.
159
+ """
160
+ return (
161
+ f'<div class="hmd-diagram hmd-diagram--placeholder">\n'
162
+ f'<p class="hmd-diagram__note">{language} diagram — {_escape(reason)}</p>\n'
163
+ f"<pre><code>{_escape(source)}</code></pre>\n"
164
+ f"</div>"
165
+ )
166
+
167
+
168
+ def _escape(text: str) -> str:
169
+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")