md2site-cli 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.
md2site/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """md2site: Compile a folder of Markdown into a static, offline-capable HTML docs site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.2.0"
6
+
7
+ __all__ = ["__version__"]
md2site/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Entry point for ``python -m md2site``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from md2site.cli import main
8
+
9
+ if __name__ == "__main__":
10
+ sys.exit(main())
md2site/assets.py ADDED
@@ -0,0 +1,211 @@
1
+ """Static asset copying, content-hash write skipping, and stale output cleanup."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import tempfile
8
+ from collections.abc import Iterable
9
+ from pathlib import Path, PurePosixPath
10
+
11
+ from md2site.config import Config, ConfigError
12
+ from md2site.markdown import pygments_css
13
+ from md2site.model import Site
14
+
15
+ _PACKAGE_STATIC_DIR = Path(__file__).resolve().parent / "static"
16
+ MANIFEST_FILENAME = ".md2site-manifest.json"
17
+
18
+
19
+ def write_if_changed(dest: Path, data: bytes) -> bool:
20
+ """Atomically write ``data`` to ``dest`` only if missing or byte-different.
21
+
22
+ Returns ``True`` if the file was written, ``False`` if skipped.
23
+ """
24
+ if dest.is_file():
25
+ try:
26
+ if dest.read_bytes() == data:
27
+ return False
28
+ except OSError:
29
+ pass
30
+ dest.parent.mkdir(parents=True, exist_ok=True)
31
+ tmp_path: Path | None = None
32
+ try:
33
+ with tempfile.NamedTemporaryFile(
34
+ mode="wb",
35
+ dir=dest.parent,
36
+ prefix=f".{dest.name}.",
37
+ suffix=".tmp",
38
+ delete=False,
39
+ ) as handle:
40
+ tmp_path = Path(handle.name)
41
+ handle.write(data)
42
+ os.replace(tmp_path, dest)
43
+ tmp_path = None
44
+ finally:
45
+ if tmp_path is not None:
46
+ tmp_path.unlink(missing_ok=True)
47
+ return True
48
+
49
+
50
+ def copy_if_changed(src: Path, dest: Path) -> bool:
51
+ """Copy ``src`` bytes to ``dest`` only if missing or byte-different."""
52
+ data = src.read_bytes()
53
+ return write_if_changed(dest, data)
54
+
55
+
56
+ def validate_safe_output_dir(out_dir: Path, config: Config) -> None:
57
+ """Refuse dangerous output directories such as docs_dir, repo_root, or ancestors."""
58
+ resolved_out = out_dir.resolve()
59
+ resolved_docs = config.docs_dir.resolve()
60
+ resolved_repo = config.repo_root.resolve()
61
+
62
+ if resolved_out == resolved_out.parent:
63
+ raise ConfigError(f"Refusing unsafe output_dir at filesystem root: {resolved_out}")
64
+ if resolved_out == resolved_docs or resolved_out in resolved_docs.parents:
65
+ raise ConfigError(
66
+ f"Refusing unsafe output_dir ({resolved_out}): "
67
+ f"cannot equal or contain docs_dir ({resolved_docs})"
68
+ )
69
+ if resolved_out == resolved_repo or resolved_out in resolved_repo.parents:
70
+ raise ConfigError(
71
+ f"Refusing unsafe output_dir ({resolved_out}): "
72
+ f"cannot equal or contain repo_root ({resolved_repo})"
73
+ )
74
+ if (resolved_out / ".git").exists():
75
+ raise ConfigError(f"Refusing unsafe output_dir containing .git: {resolved_out}")
76
+
77
+
78
+ def plan_static_rel_paths(
79
+ config: Config,
80
+ *,
81
+ has_mermaid: bool = False,
82
+ has_search_index: bool = False,
83
+ ) -> list[PurePosixPath]:
84
+ """Return sorted relative POSIX paths of static files emitted for ``config``."""
85
+ paths: list[PurePosixPath] = [
86
+ PurePosixPath("assets/md2site.css"),
87
+ PurePosixPath("assets/pygments.css"),
88
+ PurePosixPath("assets/app.js"),
89
+ ]
90
+ if config.search.enabled:
91
+ paths.append(PurePosixPath("assets/search.js"))
92
+ if has_search_index:
93
+ paths.append(PurePosixPath("assets/search-index.js"))
94
+ if has_mermaid and config.mermaid:
95
+ paths.append(PurePosixPath("assets/mermaid-init.js"))
96
+ paths.append(PurePosixPath("assets/vendor/mermaid.min.js"))
97
+ if (config.docs_dir / "custom.css").is_file():
98
+ paths.append(PurePosixPath("custom.css"))
99
+ return sorted(paths, key=lambda p: p.as_posix())
100
+
101
+
102
+ def emit_static(
103
+ config: Config,
104
+ out_dir: Path,
105
+ *,
106
+ has_mermaid: bool = False,
107
+ search_index_js: str | None = None,
108
+ ) -> list[Path]:
109
+ """Emit built-in CSS/JS, vendored Mermaid (if needed), Pygments CSS, and custom.css.
110
+
111
+ Skips writes whose destination bytes are already identical. Returns the list
112
+ of files that were actually written.
113
+ """
114
+ validate_safe_output_dir(out_dir, config)
115
+ out_dir.mkdir(parents=True, exist_ok=True)
116
+ written: list[Path] = []
117
+
118
+ def _copy_pkg(rel_src: str, rel_dest: str) -> None:
119
+ src = _PACKAGE_STATIC_DIR / rel_src
120
+ dest = out_dir / rel_dest
121
+ if copy_if_changed(src, dest):
122
+ written.append(dest)
123
+
124
+ _copy_pkg("css/md2site.css", "assets/md2site.css")
125
+ _copy_pkg("js/app.js", "assets/app.js")
126
+
127
+ if config.search.enabled:
128
+ _copy_pkg("js/search.js", "assets/search.js")
129
+ if search_index_js is not None:
130
+ dest_idx = out_dir / "assets" / "search-index.js"
131
+ if write_if_changed(dest_idx, search_index_js.encode("utf-8")):
132
+ written.append(dest_idx)
133
+
134
+ if has_mermaid and config.mermaid:
135
+ _copy_pkg("js/mermaid-init.js", "assets/mermaid-init.js")
136
+ _copy_pkg("vendor/mermaid.min.js", "assets/vendor/mermaid.min.js")
137
+
138
+ pyg_css = pygments_css(config.theme.code_theme_light, config.theme.code_theme_dark)
139
+ dest_pyg = out_dir / "assets" / "pygments.css"
140
+ if write_if_changed(dest_pyg, pyg_css.encode("utf-8")):
141
+ written.append(dest_pyg)
142
+
143
+ custom_css = config.docs_dir / "custom.css"
144
+ if custom_css.is_file():
145
+ dest_custom = out_dir / "custom.css"
146
+ if copy_if_changed(custom_css, dest_custom):
147
+ written.append(dest_custom)
148
+
149
+ return written
150
+
151
+
152
+ def emit_copies(site: Site, out_dir: Path) -> list[Path]:
153
+ """Copy planned ``AssetCopy`` files into ``out_dir`` using content-hash skipping."""
154
+ validate_safe_output_dir(out_dir, site.config)
155
+ written: list[Path] = []
156
+ for asset in sorted(site.assets, key=lambda a: a.dest_rel.as_posix()):
157
+ dest = out_dir / asset.dest_rel
158
+ if copy_if_changed(asset.src, dest):
159
+ written.append(dest)
160
+ return written
161
+
162
+
163
+ def clean_stale_files(
164
+ out_dir: Path,
165
+ expected_rel_paths: Iterable[PurePosixPath | str],
166
+ config: Config,
167
+ ) -> list[Path]:
168
+ """Remove files in ``out_dir`` not produced by the current build and update manifest.
169
+
170
+ Refuses to delete anything if ``out_dir`` fails safety validation. Returns
171
+ removed file paths in deterministic order.
172
+ """
173
+ validate_safe_output_dir(out_dir, config)
174
+ resolved_out = out_dir.resolve()
175
+ if not resolved_out.exists():
176
+ return []
177
+
178
+ expected = sorted({PurePosixPath(p).as_posix() for p in expected_rel_paths})
179
+ expected_set = set(expected)
180
+ expected_set.add(MANIFEST_FILENAME)
181
+
182
+ removed: list[Path] = []
183
+ dirs_bottom_up: list[Path] = []
184
+
185
+ def _scan_dir(curr: Path, rel_dir: PurePosixPath | None) -> None:
186
+ with os.scandir(curr) as it:
187
+ entries = sorted(it, key=lambda e: e.name)
188
+ for entry in entries:
189
+ entry_rel = PurePosixPath(entry.name) if rel_dir is None else rel_dir / entry.name
190
+ entry_path = Path(entry.path)
191
+ if entry.is_dir(follow_symlinks=False):
192
+ _scan_dir(entry_path, entry_rel)
193
+ dirs_bottom_up.append(entry_path)
194
+ elif (
195
+ entry.is_file(follow_symlinks=False) or entry.is_symlink()
196
+ ) and entry_rel.as_posix() not in expected_set:
197
+ entry_path.unlink()
198
+ removed.append(entry_path)
199
+
200
+ _scan_dir(resolved_out, None)
201
+
202
+ for directory in dirs_bottom_up:
203
+ try:
204
+ if not any(directory.iterdir()):
205
+ directory.rmdir()
206
+ except OSError:
207
+ pass
208
+
209
+ manifest_bytes = (json.dumps({"files": expected}, indent=2) + "\n").encode("utf-8")
210
+ write_if_changed(resolved_out / MANIFEST_FILENAME, manifest_bytes)
211
+ return sorted(removed)
md2site/build.py ADDED
@@ -0,0 +1,152 @@
1
+ """Two-pass build and check pipeline orchestrator for md2site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass
7
+ from pathlib import Path, PurePosixPath
8
+
9
+ from md2site.assets import (
10
+ clean_stale_files,
11
+ emit_copies,
12
+ emit_static,
13
+ plan_static_rel_paths,
14
+ validate_safe_output_dir,
15
+ write_if_changed,
16
+ )
17
+ from md2site.config import Config
18
+ from md2site.links import resolve_site
19
+ from md2site.markdown import make_engine, parse, render
20
+ from md2site.model import Diagnostic, Site
21
+ from md2site.nav import resolve_nav
22
+ from md2site.render import RenderSession, render_landing, render_page
23
+ from md2site.scanner import scan
24
+ from md2site.search import build_search_index_js
25
+
26
+
27
+ @dataclass
28
+ class BuildResult:
29
+ """Result returned by ``run_pipeline``."""
30
+
31
+ site: Site
32
+ diagnostics: list[Diagnostic]
33
+ written_files: list[Path]
34
+ skipped_count: int
35
+ removed_files: list[Path]
36
+ duration_ms: int
37
+ generated_landing: bool = False
38
+
39
+
40
+ def run_pipeline(
41
+ config: Config,
42
+ *,
43
+ drafts: bool = False,
44
+ write: bool = True,
45
+ ) -> BuildResult:
46
+ """Execute the two-pass md2site pipeline.
47
+
48
+ When ``write`` is False (``md2site check``), stops immediately after
49
+ ``resolve_site`` without touching the output directory on disk.
50
+ """
51
+ t0 = time.perf_counter()
52
+
53
+ # Pass 1: scan
54
+ pages, scan_diags = scan(config, include_drafts=drafts)
55
+
56
+ # Pass 2a: parse (reuse one MarkdownIt engine per run)
57
+ engine = make_engine(config)
58
+ for page in pages:
59
+ raw_text = page.src.read_bytes().decode("utf-8-sig", errors="replace")
60
+ parse(page, raw_text, engine)
61
+
62
+ # Pass 2b: index + resolve
63
+ cfg_label = config.config_path.name if config.config_path is not None else "md2site.config.json"
64
+ nav, nav_diags = resolve_nav(pages, config.nav, config_file=cfg_label)
65
+ site = Site(
66
+ config=config,
67
+ pages=pages,
68
+ nav=nav,
69
+ by_rel={},
70
+ assets=[],
71
+ diagnostics=[*scan_diags, *nav_diags],
72
+ )
73
+ resolve_site(site)
74
+
75
+ if not write:
76
+ duration_ms = int((time.perf_counter() - t0) * 1000)
77
+ return BuildResult(
78
+ site=site,
79
+ diagnostics=list(site.diagnostics),
80
+ written_files=[],
81
+ skipped_count=0,
82
+ removed_files=[],
83
+ duration_ms=duration_ms,
84
+ )
85
+
86
+ out_dir = config.output_dir
87
+ validate_safe_output_dir(out_dir, config)
88
+
89
+ has_mermaid = any(bool(config.mermaid and p.meta.get("_has_mermaid")) for p in site.pages)
90
+ search_index_js = build_search_index_js(site) if config.search.enabled else None
91
+
92
+ written: list[Path] = []
93
+ skipped = 0
94
+
95
+ static_written = emit_static(
96
+ config,
97
+ out_dir,
98
+ has_mermaid=has_mermaid,
99
+ search_index_js=search_index_js,
100
+ )
101
+ written.extend(static_written)
102
+ static_expected = plan_static_rel_paths(
103
+ config,
104
+ has_mermaid=has_mermaid,
105
+ has_search_index=config.search.enabled,
106
+ )
107
+ skipped += max(0, len(static_expected) - len(static_written))
108
+
109
+ copies_written = emit_copies(site, out_dir)
110
+ written.extend(copies_written)
111
+ skipped += max(0, len(site.assets) - len(copies_written))
112
+
113
+ expected_rel_paths: list[PurePosixPath] = [*static_expected, *(a.dest_rel for a in site.assets)]
114
+ has_root_index = False
115
+
116
+ session = RenderSession.create(site)
117
+ for page in site.pages:
118
+ if page.out_rel == PurePosixPath("index.html"):
119
+ has_root_index = True
120
+ body_html = render(page, engine)
121
+ full_html = render_page(site, page, body_html, session=session)
122
+ dest_html = out_dir / page.out_rel
123
+ expected_rel_paths.append(page.out_rel)
124
+ if write_if_changed(dest_html, full_html.encode("utf-8")):
125
+ written.append(dest_html)
126
+ else:
127
+ skipped += 1
128
+
129
+ generated_landing = False
130
+ if not has_root_index:
131
+ landing_html = render_landing(site)
132
+ landing_rel = PurePosixPath("index.html")
133
+ landing_dest = out_dir / landing_rel
134
+ expected_rel_paths.append(landing_rel)
135
+ if write_if_changed(landing_dest, landing_html.encode("utf-8")):
136
+ written.append(landing_dest)
137
+ else:
138
+ skipped += 1
139
+ generated_landing = True
140
+
141
+ removed_files = clean_stale_files(out_dir, expected_rel_paths, config)
142
+ duration_ms = int((time.perf_counter() - t0) * 1000)
143
+
144
+ return BuildResult(
145
+ site=site,
146
+ diagnostics=list(site.diagnostics),
147
+ written_files=written,
148
+ skipped_count=skipped,
149
+ removed_files=removed_files,
150
+ duration_ms=duration_ms,
151
+ generated_landing=generated_landing,
152
+ )