tracecite-docs 0.0.1__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,382 @@
1
+ """Reusable Quarto documentation-build orchestration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ from collections.abc import Generator, Mapping, Sequence
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Literal
13
+
14
+ import yaml
15
+
16
+ from ..tables import SiteExportResult, export_embedding_site
17
+
18
+ Language = Literal["python", "julia"]
19
+ _SUFFIX_LANGUAGES: dict[str, Language] = {".py": "python", ".jl": "julia"}
20
+ BuildVariant = Literal["combined", "python", "julia", "prose"]
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class BuildSelection:
25
+ variant: BuildVariant
26
+ profile: str | None
27
+ included: tuple[Path, ...]
28
+ skipped: tuple[Path, ...]
29
+ warning: str | None
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class DocsBuildResult:
34
+ project_root: Path
35
+ output_root: Path
36
+ selection: BuildSelection
37
+ retained_count: int
38
+ inspection: SiteExportResult | None
39
+ changed_retained: tuple[Path, ...]
40
+
41
+
42
+ def _load_config(project_root: Path) -> dict:
43
+ path = project_root / "_quarto.yml"
44
+ if not path.is_file():
45
+ raise ValueError(f"Quarto project configuration does not exist: {path}")
46
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
47
+ return loaded if isinstance(loaded, dict) else {}
48
+
49
+
50
+ def discover_render_inputs(project_root: Path) -> tuple[Path, ...]:
51
+ """Expand the base project's ordered ``project.render`` entries."""
52
+ project_root = Path(project_root).resolve()
53
+ config = _load_config(project_root)
54
+ render = (config.get("project") or {}).get("render", [])
55
+ if isinstance(render, str):
56
+ render = [render]
57
+ found: list[Path] = []
58
+ for pattern in render:
59
+ if not isinstance(pattern, str) or pattern.startswith("!"):
60
+ continue
61
+ matches = sorted(project_root.glob(pattern))
62
+ for match in matches:
63
+ if (
64
+ match.is_file()
65
+ and not match.name.endswith(".html.md")
66
+ and match not in found
67
+ ):
68
+ found.append(match)
69
+ return tuple(found)
70
+
71
+
72
+ def _qmd_language(path: Path) -> Language | None:
73
+ text = path.read_text(encoding="utf-8")
74
+ if not text.startswith("---"):
75
+ return None
76
+ end = text.find("\n---", 3)
77
+ if end < 0:
78
+ return None
79
+ metadata = yaml.safe_load(text[3:end]) or {}
80
+ engine = str(metadata.get("jupyter", metadata.get("engine", ""))).lower()
81
+ if "julia" in engine:
82
+ return "julia"
83
+ if engine in {"python", "python3", "jupyter"} or "python" in engine:
84
+ return "python"
85
+ return None
86
+
87
+
88
+ def classify_render_inputs(paths: Sequence[Path]) -> dict[Language, tuple[Path, ...]]:
89
+ result: dict[Language, list[Path]] = {"python": [], "julia": []}
90
+ for path in paths:
91
+ suffix = path.suffix.lower()
92
+ language = _SUFFIX_LANGUAGES.get(suffix)
93
+ if suffix == ".qmd":
94
+ language = _qmd_language(path)
95
+ if language:
96
+ result[language].append(path)
97
+ return {key: tuple(value) for key, value in result.items()}
98
+
99
+
100
+ def _normalize_input_path(path: Path, project_root: Path) -> Path:
101
+ """Resolve an input path when it stays inside the project root."""
102
+ candidate = path if path.is_absolute() else project_root / path
103
+ resolved = candidate.resolve()
104
+ try:
105
+ resolved.relative_to(project_root)
106
+ except ValueError:
107
+ return candidate
108
+ return resolved
109
+
110
+
111
+ def select_build_variant(
112
+ project_root: Path,
113
+ inputs: Sequence[Path],
114
+ *,
115
+ only: Language | None = None,
116
+ julia: str | None = None,
117
+ ) -> BuildSelection:
118
+ project_root = Path(project_root).resolve()
119
+ inputs = tuple(_normalize_input_path(Path(path), project_root) for path in inputs)
120
+ classified = classify_render_inputs(inputs)
121
+ available = {language for language, paths in classified.items() if paths}
122
+ if only and not classified[only]:
123
+ raise ValueError(
124
+ f"Requested language is absent from configured render inputs: {only}"
125
+ )
126
+ if only == "julia" and not julia:
127
+ raise ValueError("Julia-only documentation build requires Julia on PATH")
128
+ if only and len(available) > 1:
129
+ overlay = project_root / f"_quarto-{only}.yml"
130
+ if not overlay.is_file():
131
+ raise ValueError(
132
+ f"Explicit {only} build requires reduced overlay: {overlay}"
133
+ )
134
+ if only:
135
+ skipped = tuple(
136
+ path
137
+ for language, paths in classified.items()
138
+ if language != only
139
+ for path in paths
140
+ )
141
+ profile = only if len(available) > 1 else None
142
+ return BuildSelection(
143
+ only,
144
+ profile,
145
+ tuple(path for path in inputs if path not in skipped),
146
+ skipped,
147
+ None,
148
+ )
149
+ if available == {"python", "julia"}:
150
+ if julia:
151
+ return BuildSelection("combined", None, tuple(inputs), (), None)
152
+ overlay = project_root / "_quarto-python.yml"
153
+ if not overlay.is_file():
154
+ raise ValueError(
155
+ f"Automatic Python fallback requires reduced overlay: {overlay}"
156
+ )
157
+ skipped = classified["julia"]
158
+ warning = "Julia unavailable; skipping configured files:\n" + "\n".join(
159
+ f"- {path.relative_to(project_root)}" for path in skipped
160
+ )
161
+ included = tuple(path for path in inputs if path not in skipped)
162
+ return BuildSelection("python", "python", included, skipped, warning)
163
+ if available == {"julia"}:
164
+ if julia:
165
+ return BuildSelection("julia", None, tuple(inputs), (), None)
166
+ raise ValueError("Configured Julia documentation inputs require Julia on PATH")
167
+ if available == {"python"}:
168
+ return BuildSelection("python", None, tuple(inputs), (), None)
169
+ return BuildSelection("prose", None, tuple(inputs), (), None)
170
+
171
+
172
+ def snapshot_retained_markdown(project_root: Path) -> dict[Path, bytes]:
173
+ project_root = Path(project_root).resolve()
174
+ output = _output_root(project_root)
175
+ return {
176
+ path.relative_to(project_root): path.read_bytes()
177
+ for path in project_root.rglob("*.html.md")
178
+ if not path.is_relative_to(output) and ".quarto" not in path.parts
179
+ }
180
+
181
+
182
+ def changed_retained_markdown(
183
+ before: Mapping[Path, bytes],
184
+ project_root: Path,
185
+ ) -> tuple[Path, ...]:
186
+ after = snapshot_retained_markdown(project_root)
187
+ return tuple(
188
+ sorted(
189
+ path
190
+ for path in before.keys() | after.keys()
191
+ if before.get(path) != after.get(path)
192
+ )
193
+ )
194
+
195
+
196
+ def stage_retained_markdown(
197
+ project_root: Path,
198
+ output_root: Path,
199
+ inputs: Sequence[Path],
200
+ ) -> int:
201
+ project_root = Path(project_root).resolve()
202
+ output_root = Path(output_root).resolve()
203
+ for stale in output_root.rglob("*.html.md") if output_root.exists() else ():
204
+ stale.unlink()
205
+ count = 0
206
+ for authored in inputs:
207
+ retained = _retained_destination(authored)
208
+ if not retained.is_file():
209
+ continue
210
+ relative = authored.relative_to(project_root)
211
+ destination = output_root / relative.with_name(relative.stem + ".html.md")
212
+ destination.parent.mkdir(parents=True, exist_ok=True)
213
+ shutil.copy2(retained, destination)
214
+ count += 1
215
+ return count
216
+
217
+
218
+ def _output_root(project_root: Path) -> Path:
219
+ project = _load_config(project_root).get("project") or {}
220
+ return project_root / project.get("output-dir", "_site")
221
+
222
+
223
+ def _contains_source_symlinks(project_root: Path, output_root: Path) -> bool:
224
+ """Return whether a Quarto source tree contains symlinked inputs/resources."""
225
+ project_root = project_root.resolve()
226
+ output_root = output_root.resolve()
227
+ for path in project_root.rglob("*"):
228
+ if path.is_relative_to(output_root) or ".quarto" in path.parts:
229
+ continue
230
+ if path.is_symlink():
231
+ return True
232
+ return False
233
+
234
+
235
+ def _copy_project_without_build_outputs(
236
+ project_root: Path,
237
+ staged_root: Path,
238
+ output_root: Path,
239
+ ) -> None:
240
+ """Materialise a symlinked Quarto project as ordinary files for rendering."""
241
+ try:
242
+ output_relative = output_root.relative_to(project_root)
243
+ except ValueError as error:
244
+ raise ValueError(
245
+ "Symlinked Quarto projects require project.output-dir to remain "
246
+ f"inside the project root: {output_root}"
247
+ ) from error
248
+ if not output_root.resolve().is_relative_to(project_root.resolve()):
249
+ raise ValueError(
250
+ "Symlinked Quarto projects require project.output-dir to remain "
251
+ f"inside the project root: {output_root}"
252
+ )
253
+
254
+ def ignore(directory: str, names: list[str]) -> set[str]:
255
+ relative = Path(directory).relative_to(project_root)
256
+ ignored: set[str] = set()
257
+ for name in names:
258
+ candidate = relative / name
259
+ if candidate == output_relative or name == ".quarto":
260
+ ignored.add(name)
261
+ return ignored
262
+
263
+ shutil.copytree(
264
+ project_root,
265
+ staged_root,
266
+ symlinks=False,
267
+ ignore=ignore,
268
+ dirs_exist_ok=True,
269
+ )
270
+
271
+
272
+ def _retained_destination(authored: Path) -> Path:
273
+ """Return the canonical retained-Markdown destination for an authored input."""
274
+ canonical = authored.resolve() if authored.is_symlink() else authored
275
+ return canonical.with_name(canonical.stem + ".html.md")
276
+
277
+
278
+ def _publish_materialised_render(
279
+ staged_root: Path,
280
+ project_root: Path,
281
+ inputs: Sequence[Path],
282
+ ) -> None:
283
+ """Publish a successful staged render and its retained Markdown."""
284
+ staged_output = _output_root(staged_root)
285
+ output_root = _output_root(project_root)
286
+ if not staged_output.is_dir():
287
+ raise RuntimeError(
288
+ f"Quarto did not create the configured output: {staged_output}"
289
+ )
290
+
291
+ for authored in inputs:
292
+ relative = authored.relative_to(project_root)
293
+ staged_authored = staged_root / relative
294
+ staged_retained = staged_authored.with_name(staged_authored.stem + ".html.md")
295
+ if not staged_retained.is_file():
296
+ continue
297
+ destination = _retained_destination(authored)
298
+ destination.parent.mkdir(parents=True, exist_ok=True)
299
+ shutil.copy2(staged_retained, destination)
300
+
301
+ if output_root.exists() or output_root.is_symlink():
302
+ if output_root.is_symlink() or output_root.is_file():
303
+ output_root.unlink()
304
+ else:
305
+ shutil.rmtree(output_root)
306
+ shutil.copytree(staged_output, output_root, symlinks=False)
307
+
308
+
309
+ @contextmanager
310
+ def _render_project_root(
311
+ project_root: Path,
312
+ output_root: Path,
313
+ ) -> Generator[tuple[Path, bool], None, None]:
314
+ """Yield a Quarto-safe project root, materialising symlinks when required."""
315
+ if not _contains_source_symlinks(project_root, output_root):
316
+ yield project_root, False
317
+ return
318
+
319
+ staged_root = Path(
320
+ tempfile.mkdtemp(
321
+ prefix=f".{project_root.name}-render-",
322
+ dir=project_root.parent,
323
+ )
324
+ )
325
+ try:
326
+ _copy_project_without_build_outputs(project_root, staged_root, output_root)
327
+ yield staged_root, True
328
+ finally:
329
+ shutil.rmtree(staged_root, ignore_errors=True)
330
+
331
+
332
+ def build_docs(
333
+ project_root: str | Path,
334
+ *,
335
+ only: Language | None = None,
336
+ quarto: str | Path | None = None,
337
+ inspection: bool = True,
338
+ render_inspection: bool = True,
339
+ strict_tables: bool = False,
340
+ check_retained: bool = False,
341
+ ) -> DocsBuildResult:
342
+ project_root = Path(project_root).resolve()
343
+ quarto_command = str(quarto) if quarto else shutil.which("quarto")
344
+ if not quarto_command:
345
+ raise FileNotFoundError("Quarto is required. Install Quarto or pass --quarto.")
346
+ inputs = discover_render_inputs(project_root)
347
+ julia = shutil.which("julia")
348
+ selection = select_build_variant(project_root, inputs, only=only, julia=julia)
349
+ if selection.warning:
350
+ print(selection.warning)
351
+ before = snapshot_retained_markdown(project_root) if check_retained else {}
352
+ output_root = _output_root(project_root)
353
+ with _render_project_root(project_root, output_root) as (render_root, staged):
354
+ command = [quarto_command, "render", render_root.name]
355
+ if selection.profile:
356
+ command.extend(["--profile", selection.profile])
357
+ subprocess.run(command, cwd=render_root.parent, check=True)
358
+ if staged:
359
+ _publish_materialised_render(
360
+ render_root,
361
+ project_root,
362
+ selection.included,
363
+ )
364
+ retained_count = stage_retained_markdown(
365
+ project_root, output_root, selection.included
366
+ )
367
+ exported = None
368
+ if inspection:
369
+ exported = export_embedding_site(
370
+ output_root,
371
+ project_root.parent / ".tracecite" / "embedding-site",
372
+ project_config=project_root / "_quarto.yml",
373
+ project_profile=selection.profile,
374
+ source_project=project_root,
375
+ strict=strict_tables,
376
+ render=render_inspection,
377
+ quarto=quarto_command,
378
+ )
379
+ changed = changed_retained_markdown(before, project_root) if check_retained else ()
380
+ return DocsBuildResult(
381
+ project_root, output_root, selection, retained_count, exported, changed
382
+ )
@@ -0,0 +1,114 @@
1
+ """TOML loading and deterministic validation for the docs contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from pathlib import Path
7
+
8
+ from .contract import DocsEvidenceContract
9
+
10
+ _FIELDS = {
11
+ "authored_root",
12
+ "retained_root",
13
+ "staged_root",
14
+ "source_links",
15
+ "index_output",
16
+ "publication_exclude",
17
+ "host_render_command",
18
+ }
19
+
20
+
21
+ def _path(value: object, *, name: str, repo_root: Path) -> Path:
22
+ if not isinstance(value, str) or not value:
23
+ raise ValueError(f"{name} must be a non-empty repository-relative path")
24
+ raw = Path(value)
25
+ if raw.is_absolute():
26
+ raise ValueError(f"{name} must be repository-relative")
27
+ if ".." in raw.parts:
28
+ raise ValueError(f"{name} must not escape the repository")
29
+ resolved = (repo_root / raw).resolve(strict=False)
30
+ if not resolved.is_relative_to(repo_root):
31
+ raise ValueError(f"{name} resolves outside the repository")
32
+ return resolved
33
+
34
+
35
+ def _overlap(left: Path, right: Path) -> bool:
36
+ return left.is_relative_to(right) or right.is_relative_to(left)
37
+
38
+
39
+ def load_docs_contract(
40
+ path: str | Path, *, repo_root: str | Path
41
+ ) -> DocsEvidenceContract:
42
+ config_path = Path(path).resolve()
43
+ root = Path(repo_root).resolve()
44
+ try:
45
+ data = tomllib.loads(config_path.read_text(encoding="utf-8"))
46
+ except (OSError, tomllib.TOMLDecodeError) as exc:
47
+ raise ValueError(f"invalid docs configuration: {exc}") from exc
48
+ if data.get("schema_version") != 1:
49
+ raise ValueError("docs configuration requires schema_version = 1")
50
+ if set(data) - {"schema_version", "docs"} or not isinstance(data.get("docs"), dict):
51
+ raise ValueError("docs configuration requires a [docs] table")
52
+ docs = data["docs"]
53
+ unknown = set(docs) - _FIELDS
54
+ if unknown:
55
+ raise ValueError(
56
+ f"unknown docs configuration field(s): {', '.join(sorted(unknown))}"
57
+ )
58
+ missing = _FIELDS - set(docs) - {"host_render_command"}
59
+ if missing:
60
+ raise ValueError(
61
+ f"missing docs configuration field(s): {', '.join(sorted(missing))}"
62
+ )
63
+
64
+ authored = _path(docs.get("authored_root"), name="authored_root", repo_root=root)
65
+ retained = _path(docs.get("retained_root"), name="retained_root", repo_root=root)
66
+ staged = _path(docs.get("staged_root"), name="staged_root", repo_root=root)
67
+ source_links = _path(docs.get("source_links"), name="source_links", repo_root=root)
68
+ index_output = _path(docs.get("index_output"), name="index_output", repo_root=root)
69
+ if not authored.is_dir() or not retained.is_dir():
70
+ raise ValueError("authored_root and retained_root must be existing directories")
71
+ if not source_links.is_file():
72
+ raise ValueError("source_links must be an existing file")
73
+ if _overlap(retained, staged):
74
+ raise ValueError("retained_root and staged_root must not overlap")
75
+ roots = (authored, retained, staged, source_links, index_output)
76
+ for index, left in enumerate(roots):
77
+ for right in roots[index + 1 :]:
78
+ if (left == authored and right == retained) or (
79
+ left == retained and right == authored
80
+ ):
81
+ if not _overlap(left, right) or left == right:
82
+ continue
83
+ raise ValueError(
84
+ "authored_root and retained_root may overlap only when equal"
85
+ )
86
+ if _overlap(left, right):
87
+ raise ValueError("docs contract paths must not contain one another")
88
+
89
+ excludes = docs.get("publication_exclude")
90
+ if not isinstance(excludes, list):
91
+ raise ValueError("publication_exclude must be an array") # noqa: TRY004
92
+ publication_exclude = tuple(
93
+ _path(value, name="publication_exclude", repo_root=root) for value in excludes
94
+ )
95
+ command = docs.get("host_render_command")
96
+ if command is not None:
97
+ if (
98
+ not isinstance(command, list)
99
+ or not command
100
+ or not all(isinstance(item, str) and item for item in command)
101
+ ):
102
+ raise ValueError("host_render_command must be a non-empty argument array")
103
+ command_tuple = tuple(command)
104
+ else:
105
+ command_tuple = None
106
+ return DocsEvidenceContract(
107
+ authored,
108
+ retained,
109
+ staged,
110
+ source_links,
111
+ index_output,
112
+ publication_exclude,
113
+ command_tuple,
114
+ )
@@ -0,0 +1,17 @@
1
+ """Validated, repository-neutral documentation evidence contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class DocsEvidenceContract:
11
+ authored_root: Path
12
+ retained_root: Path
13
+ staged_root: Path
14
+ source_links: Path
15
+ index_output: Path
16
+ publication_exclude: tuple[Path, ...]
17
+ host_render_command: tuple[str, ...] | None = None