doxtr-cli 0.1.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.
- doxtr_cli/__init__.py +48 -0
- doxtr_cli/__main__.py +8 -0
- doxtr_cli/builders.py +596 -0
- doxtr_cli/cli.py +301 -0
- doxtr_cli/config.py +330 -0
- doxtr_cli/confluence.py +166 -0
- doxtr_cli/errors.py +49 -0
- doxtr_cli/git_meta.py +118 -0
- doxtr_cli/prompts.py +89 -0
- doxtr_cli/server.py +800 -0
- doxtr_cli-0.1.0.dist-info/METADATA +110 -0
- doxtr_cli-0.1.0.dist-info/RECORD +16 -0
- doxtr_cli-0.1.0.dist-info/WHEEL +5 -0
- doxtr_cli-0.1.0.dist-info/entry_points.txt +2 -0
- doxtr_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- doxtr_cli-0.1.0.dist-info/top_level.txt +1 -0
doxtr_cli/server.py
ADDED
|
@@ -0,0 +1,800 @@
|
|
|
1
|
+
"""Preview & production documentation server supporting Nginx and pure Python backends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import json
|
|
7
|
+
import mimetypes
|
|
8
|
+
import posixpath
|
|
9
|
+
import re
|
|
10
|
+
import shutil
|
|
11
|
+
import signal
|
|
12
|
+
import socket
|
|
13
|
+
import subprocess
|
|
14
|
+
import tempfile
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from http import HTTPStatus
|
|
19
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
from urllib.parse import parse_qs, unquote, urlparse
|
|
23
|
+
|
|
24
|
+
from .builders import CommandRunner, default_runner, require_binary
|
|
25
|
+
from .config import DoxtrConfig, validate_scheme_name
|
|
26
|
+
from .errors import BuildError, MissingBinaryError
|
|
27
|
+
|
|
28
|
+
WATCH_EXTENSIONS = {".rst", ".md", ".d2", ".drawio", ".py", ".css", ".js", ".toml"}
|
|
29
|
+
|
|
30
|
+
_DEFAULT_SERVER_TEMPLATE = """server {
|
|
31
|
+
listen ##SERVER_PORT##;
|
|
32
|
+
listen [::]:##SERVER_PORT##;
|
|
33
|
+
|
|
34
|
+
server_name localhost;
|
|
35
|
+
|
|
36
|
+
disable_symlinks off;
|
|
37
|
+
root ##SERVER_BUILD_DIR##;
|
|
38
|
+
index index.html;
|
|
39
|
+
|
|
40
|
+
location / {
|
|
41
|
+
try_files $uri $uri/ =404;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
_CLOSING_BRACE_RE = re.compile(r"\n\}\s*$")
|
|
47
|
+
_HEAD_OPEN_RE = re.compile(r"(<head\b[^>]*>)", re.IGNORECASE)
|
|
48
|
+
_BODY_CLOSE_RE = re.compile(r"(</body>)", re.IGNORECASE)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _ipv6_available() -> bool:
|
|
52
|
+
try:
|
|
53
|
+
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
|
|
54
|
+
sock.bind(("::1", 0))
|
|
55
|
+
return True
|
|
56
|
+
except OSError:
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def resolve_nginx_template(configured: str | None) -> Path | None:
|
|
61
|
+
"""Find an existing Nginx server template path or fall back to ``None`` (built-in)."""
|
|
62
|
+
candidates: list[Path] = []
|
|
63
|
+
if configured:
|
|
64
|
+
candidates.append(Path(configured))
|
|
65
|
+
candidates.extend(
|
|
66
|
+
[
|
|
67
|
+
Path("/workspaces/docs/reactor/default.template"),
|
|
68
|
+
Path("/etc/nginx/templates/default.template"),
|
|
69
|
+
]
|
|
70
|
+
)
|
|
71
|
+
for candidate in candidates:
|
|
72
|
+
if candidate.is_file():
|
|
73
|
+
return candidate
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def select_backend(
|
|
78
|
+
requested: str,
|
|
79
|
+
*,
|
|
80
|
+
watch: bool = False,
|
|
81
|
+
theme: str | None = None,
|
|
82
|
+
scheme: str | None = None,
|
|
83
|
+
which_fn: Callable[[str], str | None] = shutil.which,
|
|
84
|
+
) -> str:
|
|
85
|
+
"""Choose ``'nginx'`` or ``'python'`` backend based on flags and installed binaries."""
|
|
86
|
+
if requested == "nginx":
|
|
87
|
+
require_binary("nginx", which_fn=which_fn)
|
|
88
|
+
return "nginx"
|
|
89
|
+
if requested == "python":
|
|
90
|
+
return "python"
|
|
91
|
+
if watch or theme or scheme:
|
|
92
|
+
return "python"
|
|
93
|
+
return "nginx" if which_fn("nginx") else "python"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def discover_versions(versions_dir: Path | None) -> list[dict[str, Any]]:
|
|
97
|
+
"""Return sorted version directory descriptors found under *versions_dir*."""
|
|
98
|
+
if versions_dir is None or not versions_dir.is_dir():
|
|
99
|
+
return []
|
|
100
|
+
entries: list[dict[str, Any]] = []
|
|
101
|
+
for child in sorted(versions_dir.iterdir(), key=lambda p: p.name):
|
|
102
|
+
if not child.is_dir() or child.name.startswith("."):
|
|
103
|
+
continue
|
|
104
|
+
entries.append(
|
|
105
|
+
{
|
|
106
|
+
"name": child.name,
|
|
107
|
+
"url": f"/{child.name}/",
|
|
108
|
+
"path": str(child.resolve()),
|
|
109
|
+
"has_index": (child / "index.html").is_file(),
|
|
110
|
+
"is_test": child.name.startswith("test"),
|
|
111
|
+
}
|
|
112
|
+
)
|
|
113
|
+
return entries
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def resolve_default_doc_root(config: DoxtrConfig, explicit_dir: Path | None = None) -> Path:
|
|
117
|
+
"""Pick the most suitable built HTML directory to serve when ``--dir`` is omitted."""
|
|
118
|
+
if explicit_dir is not None:
|
|
119
|
+
return explicit_dir.resolve()
|
|
120
|
+
candidates = [
|
|
121
|
+
config.build_path / "html",
|
|
122
|
+
config.build_path / "html-test",
|
|
123
|
+
config.versions_path / "latest",
|
|
124
|
+
]
|
|
125
|
+
for candidate in candidates:
|
|
126
|
+
if candidate.is_dir():
|
|
127
|
+
return candidate.resolve()
|
|
128
|
+
return (config.build_path / "html").resolve()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _strip_ipv6_listen(block: str) -> str:
|
|
132
|
+
kept = [line for line in block.splitlines() if "listen [::]:" not in line]
|
|
133
|
+
return "\n".join(kept)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def render_nginx_config(
|
|
137
|
+
*,
|
|
138
|
+
doc_root: Path,
|
|
139
|
+
port: int,
|
|
140
|
+
host: str = "0.0.0.0",
|
|
141
|
+
template_path: Path | None = None,
|
|
142
|
+
versions_dir: Path | None = None,
|
|
143
|
+
runtime_dir: Path | None = None,
|
|
144
|
+
enable_ipv6: bool | None = None,
|
|
145
|
+
) -> str:
|
|
146
|
+
"""Render a self-contained Nginx configuration file matching Doxtr reactor templates."""
|
|
147
|
+
ipv6_ok = _ipv6_available() if enable_ipv6 is None else enable_ipv6
|
|
148
|
+
raw = (
|
|
149
|
+
template_path.read_text(encoding="utf-8")
|
|
150
|
+
if template_path is not None
|
|
151
|
+
else _DEFAULT_SERVER_TEMPLATE
|
|
152
|
+
)
|
|
153
|
+
root_str = str(doc_root.resolve())
|
|
154
|
+
listen_prefix = f"{host}:" if host and host not in {"0.0.0.0", "*"} else ""
|
|
155
|
+
|
|
156
|
+
if not ipv6_ok or host not in {"0.0.0.0", "*", "::"}:
|
|
157
|
+
raw = _strip_ipv6_listen(raw)
|
|
158
|
+
else:
|
|
159
|
+
raw = raw.replace("listen [::]:##SERVER_PORT##", f"listen [::]:{port}").replace(
|
|
160
|
+
"listen [::]:${PORT}", f"listen [::]:{port}"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
rendered = (
|
|
164
|
+
raw.replace("##SERVER_PORT##", f"{listen_prefix}{port}")
|
|
165
|
+
.replace("##SERVER_BUILD_DIR##", root_str)
|
|
166
|
+
.replace("${PORT}", str(port))
|
|
167
|
+
.replace("${HOST}", host)
|
|
168
|
+
.replace("${DOC_ROOT}", root_str)
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
extra_blocks: list[str] = [
|
|
172
|
+
"",
|
|
173
|
+
" location ~* \\.pdf$ {",
|
|
174
|
+
' add_header Content-Disposition "attachment";',
|
|
175
|
+
" }",
|
|
176
|
+
]
|
|
177
|
+
for ver in discover_versions(versions_dir):
|
|
178
|
+
v_name = ver["name"]
|
|
179
|
+
v_path = ver["path"]
|
|
180
|
+
extra_blocks.extend(
|
|
181
|
+
[
|
|
182
|
+
"",
|
|
183
|
+
f" location /{v_name}/ {{",
|
|
184
|
+
f" alias {v_path}/;",
|
|
185
|
+
" index index.html;",
|
|
186
|
+
" try_files $uri $uri/ =404;",
|
|
187
|
+
" }",
|
|
188
|
+
]
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
injection = "\n".join(extra_blocks) + "\n}\n"
|
|
192
|
+
if _CLOSING_BRACE_RE.search(rendered):
|
|
193
|
+
server_block = _CLOSING_BRACE_RE.sub(injection, rendered)
|
|
194
|
+
else:
|
|
195
|
+
server_block = rendered.rstrip() + "\n"
|
|
196
|
+
|
|
197
|
+
if re.search(r"^\s*http\s*\{", server_block, flags=re.MULTILINE):
|
|
198
|
+
return server_block
|
|
199
|
+
|
|
200
|
+
rt = (runtime_dir or Path(tempfile.gettempdir()) / f"doxtr-nginx-{port}").resolve()
|
|
201
|
+
rt.mkdir(parents=True, exist_ok=True)
|
|
202
|
+
mime_line = (
|
|
203
|
+
" include /etc/nginx/mime.types;\n" if Path("/etc/nginx/mime.types").is_file() else ""
|
|
204
|
+
)
|
|
205
|
+
indented_server = "\n".join(f" {line}" if line else "" for line in server_block.splitlines())
|
|
206
|
+
|
|
207
|
+
return (
|
|
208
|
+
f"pid {rt / 'nginx.pid'};\n"
|
|
209
|
+
"error_log /dev/stderr warn;\n\n"
|
|
210
|
+
"events {\n"
|
|
211
|
+
" worker_connections 1024;\n"
|
|
212
|
+
"}\n\n"
|
|
213
|
+
"http {\n"
|
|
214
|
+
f"{mime_line}"
|
|
215
|
+
" default_type application/octet-stream;\n"
|
|
216
|
+
" sendfile on;\n"
|
|
217
|
+
" access_log /dev/stdout;\n"
|
|
218
|
+
f" client_body_temp_path {rt / 'client_body'};\n"
|
|
219
|
+
f" proxy_temp_path {rt / 'proxy'};\n"
|
|
220
|
+
f" fastcgi_temp_path {rt / 'fastcgi'};\n"
|
|
221
|
+
f" uwsgi_temp_path {rt / 'uwsgi'};\n"
|
|
222
|
+
f" scgi_temp_path {rt / 'scgi'};\n\n"
|
|
223
|
+
f"{indented_server}\n"
|
|
224
|
+
"}\n"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def serve_nginx(
|
|
229
|
+
*,
|
|
230
|
+
doc_root: Path,
|
|
231
|
+
port: int,
|
|
232
|
+
host: str = "0.0.0.0",
|
|
233
|
+
template_path: Path | None = None,
|
|
234
|
+
versions_dir: Path | None = None,
|
|
235
|
+
which_fn: Callable[[str], str | None] = shutil.which,
|
|
236
|
+
) -> int:
|
|
237
|
+
"""Render an Nginx runtime config and run ``nginx -c ... -g 'daemon off;'``."""
|
|
238
|
+
nginx_bin = require_binary("nginx", which_fn=which_fn)
|
|
239
|
+
with tempfile.TemporaryDirectory(prefix="doxtr-nginx-") as tmp_dir:
|
|
240
|
+
runtime_dir = Path(tmp_dir)
|
|
241
|
+
conf_path = runtime_dir / "nginx.conf"
|
|
242
|
+
conf_path.write_text(
|
|
243
|
+
render_nginx_config(
|
|
244
|
+
doc_root=doc_root,
|
|
245
|
+
port=port,
|
|
246
|
+
host=host,
|
|
247
|
+
template_path=template_path,
|
|
248
|
+
versions_dir=versions_dir,
|
|
249
|
+
runtime_dir=runtime_dir,
|
|
250
|
+
),
|
|
251
|
+
encoding="utf-8",
|
|
252
|
+
)
|
|
253
|
+
proc = subprocess.Popen([nginx_bin, "-c", str(conf_path), "-g", "daemon off;"])
|
|
254
|
+
try:
|
|
255
|
+
return proc.wait()
|
|
256
|
+
except KeyboardInterrupt:
|
|
257
|
+
proc.send_signal(signal.SIGTERM)
|
|
258
|
+
proc.wait(timeout=5)
|
|
259
|
+
raise
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def build_theme_preview_cache(
|
|
263
|
+
config: DoxtrConfig,
|
|
264
|
+
theme: str,
|
|
265
|
+
*,
|
|
266
|
+
scheme: str | None = None,
|
|
267
|
+
runner: CommandRunner = default_runner,
|
|
268
|
+
which_fn: Callable[[str], str | None] = shutil.which,
|
|
269
|
+
) -> Path:
|
|
270
|
+
"""Build HTML documentation for *theme* into an isolated preview cache directory."""
|
|
271
|
+
sphinx_bin = require_binary("sphinx-build", which_fn=which_fn)
|
|
272
|
+
safe_theme = re.sub(r"[^A-Za-z0-9_.-]+", "_", theme)
|
|
273
|
+
preview_dir = config.build_path / f"preview-{safe_theme}"
|
|
274
|
+
doctree_dir = config.build_path / f"doctrees-preview-{safe_theme}"
|
|
275
|
+
preview_dir.mkdir(parents=True, exist_ok=True)
|
|
276
|
+
cmd = [
|
|
277
|
+
sphinx_bin,
|
|
278
|
+
"-b",
|
|
279
|
+
"html",
|
|
280
|
+
"-d",
|
|
281
|
+
str(doctree_dir),
|
|
282
|
+
"-D",
|
|
283
|
+
f"html_theme={theme}",
|
|
284
|
+
]
|
|
285
|
+
if scheme:
|
|
286
|
+
cmd.extend(["-D", f"doxtr_color_scheme={scheme}"])
|
|
287
|
+
cmd.extend(["-D", f"doxtr_dark_mode={1 if scheme == 'dark' else 0}"])
|
|
288
|
+
cmd.extend([str(config.source_path), str(preview_dir)])
|
|
289
|
+
runner(cmd, config.project_root)
|
|
290
|
+
return preview_dir
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _snapshot_watched_files(watch_root: Path) -> dict[Path, int]:
|
|
294
|
+
snapshot: dict[Path, int] = {}
|
|
295
|
+
if not watch_root.exists():
|
|
296
|
+
return snapshot
|
|
297
|
+
for path in watch_root.rglob("*"):
|
|
298
|
+
if path.is_file() and path.suffix.lower() in WATCH_EXTENSIONS:
|
|
299
|
+
try:
|
|
300
|
+
snapshot[path] = path.stat().st_mtime_ns
|
|
301
|
+
except OSError:
|
|
302
|
+
continue
|
|
303
|
+
return snapshot
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class SourceWatcher:
|
|
307
|
+
"""File watcher using ``watchfiles``, ``watchdog``, or stdlib mtime polling."""
|
|
308
|
+
|
|
309
|
+
def __init__(
|
|
310
|
+
self,
|
|
311
|
+
watch_dir: Path,
|
|
312
|
+
on_change: Callable[[list[Path]], None],
|
|
313
|
+
*,
|
|
314
|
+
poll_interval: float = 0.25,
|
|
315
|
+
prefer_polling: bool = False,
|
|
316
|
+
) -> None:
|
|
317
|
+
self.watch_dir = watch_dir.resolve()
|
|
318
|
+
self.on_change = on_change
|
|
319
|
+
self.poll_interval = poll_interval
|
|
320
|
+
self.prefer_polling = prefer_polling
|
|
321
|
+
self._stop_event = threading.Event()
|
|
322
|
+
self._thread: threading.Thread | None = None
|
|
323
|
+
self._observer: Any | None = None
|
|
324
|
+
self.backend = "poll"
|
|
325
|
+
|
|
326
|
+
def start(self) -> None:
|
|
327
|
+
"""Start watching ``self.watch_dir`` on a background daemon thread."""
|
|
328
|
+
if not self.prefer_polling:
|
|
329
|
+
if self._try_start_watchfiles():
|
|
330
|
+
return
|
|
331
|
+
if self._try_start_watchdog():
|
|
332
|
+
return
|
|
333
|
+
self.backend = "poll"
|
|
334
|
+
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
|
|
335
|
+
self._thread.start()
|
|
336
|
+
|
|
337
|
+
def _try_start_watchfiles(self) -> bool:
|
|
338
|
+
try:
|
|
339
|
+
from watchfiles import watch as wf_watch
|
|
340
|
+
except ImportError:
|
|
341
|
+
return False
|
|
342
|
+
|
|
343
|
+
self.backend = "watchfiles"
|
|
344
|
+
|
|
345
|
+
def _loop() -> None:
|
|
346
|
+
for changes in wf_watch(str(self.watch_dir), stop_event=self._stop_event):
|
|
347
|
+
changed = [
|
|
348
|
+
Path(p) for _, p in changes if Path(p).suffix.lower() in WATCH_EXTENSIONS
|
|
349
|
+
]
|
|
350
|
+
if changed:
|
|
351
|
+
self.on_change(changed)
|
|
352
|
+
|
|
353
|
+
self._thread = threading.Thread(target=_loop, daemon=True)
|
|
354
|
+
self._thread.start()
|
|
355
|
+
return True
|
|
356
|
+
|
|
357
|
+
def _try_start_watchdog(self) -> bool:
|
|
358
|
+
try:
|
|
359
|
+
from watchdog.events import FileSystemEventHandler
|
|
360
|
+
from watchdog.observers import Observer
|
|
361
|
+
except ImportError:
|
|
362
|
+
return False
|
|
363
|
+
|
|
364
|
+
self.backend = "watchdog"
|
|
365
|
+
callback = self.on_change
|
|
366
|
+
|
|
367
|
+
def _on_any_event(event: Any) -> None:
|
|
368
|
+
if getattr(event, "is_directory", False):
|
|
369
|
+
return
|
|
370
|
+
src = getattr(event, "src_path", "")
|
|
371
|
+
p = Path(src)
|
|
372
|
+
if p.suffix.lower() in WATCH_EXTENSIONS:
|
|
373
|
+
callback([p])
|
|
374
|
+
|
|
375
|
+
handler: Any = FileSystemEventHandler()
|
|
376
|
+
handler.on_any_event = _on_any_event
|
|
377
|
+
observer = Observer()
|
|
378
|
+
observer.schedule(handler, str(self.watch_dir), recursive=True)
|
|
379
|
+
observer.start()
|
|
380
|
+
self._observer = observer
|
|
381
|
+
return True
|
|
382
|
+
|
|
383
|
+
def _poll_loop(self) -> None:
|
|
384
|
+
previous = _snapshot_watched_files(self.watch_dir)
|
|
385
|
+
while not self._stop_event.wait(self.poll_interval):
|
|
386
|
+
current = _snapshot_watched_files(self.watch_dir)
|
|
387
|
+
changed = [p for p, mtime in current.items() if previous.get(p) != mtime] + [
|
|
388
|
+
p for p in previous if p not in current
|
|
389
|
+
]
|
|
390
|
+
if changed:
|
|
391
|
+
previous = current
|
|
392
|
+
self.on_change(changed)
|
|
393
|
+
|
|
394
|
+
def stop(self) -> None:
|
|
395
|
+
"""Stop the background watcher cleanly."""
|
|
396
|
+
self._stop_event.set()
|
|
397
|
+
if self._observer is not None:
|
|
398
|
+
self._observer.stop()
|
|
399
|
+
self._observer.join(timeout=2)
|
|
400
|
+
self._observer = None
|
|
401
|
+
if self._thread is not None and self._thread.is_alive():
|
|
402
|
+
self._thread.join(timeout=2)
|
|
403
|
+
self._thread = None
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _inject_scheme_script(html_text: str, scheme: str) -> str:
|
|
407
|
+
snippet = (
|
|
408
|
+
"\n<script>(function(){"
|
|
409
|
+
f"var m={json.dumps(scheme)};"
|
|
410
|
+
"var r=document.documentElement;"
|
|
411
|
+
"r.dataset.colorScheme=m;"
|
|
412
|
+
"var mt=document.getElementById('doxtr-color-scheme-meta');"
|
|
413
|
+
"if(mt)mt.setAttribute('content',m);"
|
|
414
|
+
"var pl=document.getElementById('pygments_dark_css');"
|
|
415
|
+
"if(pl){if(m==='dark'){pl.media='all';pl.disabled=false;}"
|
|
416
|
+
"else if(m==='light'){pl.media='not all';pl.disabled=true;}}"
|
|
417
|
+
"})();</script>"
|
|
418
|
+
)
|
|
419
|
+
if _HEAD_OPEN_RE.search(html_text):
|
|
420
|
+
return _HEAD_OPEN_RE.sub(lambda m: f"{m.group(1)}{snippet}", html_text, count=1)
|
|
421
|
+
return snippet + html_text
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _inject_version_bar(html_text: str, versions: list[dict[str, Any]], active: str | None) -> str:
|
|
425
|
+
links = " ".join(
|
|
426
|
+
f'<a href="{html.escape(v["url"])}"'
|
|
427
|
+
+ (' aria-current="page"' if v["name"] == active else "")
|
|
428
|
+
+ f">{html.escape(v['name'])}</a>"
|
|
429
|
+
for v in versions
|
|
430
|
+
)
|
|
431
|
+
bar = (
|
|
432
|
+
'<div id="doxtr-version-bar" data-doxtr-versions '
|
|
433
|
+
'style="position:fixed;bottom:12px;right:12px;z-index:9999;padding:6px 10px;'
|
|
434
|
+
"border-radius:8px;background:rgba(17,19,24,0.88);color:#fff;font:12px/1.4 system-ui,sans-serif;"
|
|
435
|
+
'display:flex;gap:8px;align-items:center">'
|
|
436
|
+
f"<span>Versions:</span>{links}</div>"
|
|
437
|
+
)
|
|
438
|
+
if _BODY_CLOSE_RE.search(html_text):
|
|
439
|
+
return _BODY_CLOSE_RE.sub(lambda m: f"{bar}\n{m.group(1)}", html_text, count=1)
|
|
440
|
+
return html_text + bar
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _inject_reload_script(html_text: str, initial_build_id: int) -> str:
|
|
444
|
+
script = (
|
|
445
|
+
"\n<script>(function(){"
|
|
446
|
+
f"var b={initial_build_id};"
|
|
447
|
+
"setInterval(function(){fetch('/__doxtr_reload').then(function(r){return r.json();})"
|
|
448
|
+
".then(function(d){if(d&&d.build_id!==b){location.reload();}}).catch(function(){});},1000);"
|
|
449
|
+
"})();</script>"
|
|
450
|
+
)
|
|
451
|
+
if _BODY_CLOSE_RE.search(html_text):
|
|
452
|
+
return _BODY_CLOSE_RE.sub(lambda m: f"{script}\n{m.group(1)}", html_text, count=1)
|
|
453
|
+
return html_text + script
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
class _PreviewHTTPServer(ThreadingHTTPServer):
|
|
457
|
+
allow_reuse_address = True
|
|
458
|
+
|
|
459
|
+
def __init__(
|
|
460
|
+
self,
|
|
461
|
+
server_address: tuple[str, int],
|
|
462
|
+
handler_cls: type[BaseHTTPRequestHandler],
|
|
463
|
+
preview: DoxtrPreviewServer,
|
|
464
|
+
) -> None:
|
|
465
|
+
self.preview = preview
|
|
466
|
+
super().__init__(server_address, handler_cls)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
class _PreviewRequestHandler(BaseHTTPRequestHandler):
|
|
470
|
+
server: _PreviewHTTPServer
|
|
471
|
+
|
|
472
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
473
|
+
return
|
|
474
|
+
|
|
475
|
+
def do_GET(self) -> None:
|
|
476
|
+
self._serve(head_only=False)
|
|
477
|
+
|
|
478
|
+
def do_HEAD(self) -> None:
|
|
479
|
+
self._serve(head_only=True)
|
|
480
|
+
|
|
481
|
+
def _send_bytes(
|
|
482
|
+
self,
|
|
483
|
+
status: HTTPStatus,
|
|
484
|
+
body: bytes,
|
|
485
|
+
content_type: str,
|
|
486
|
+
*,
|
|
487
|
+
extra_headers: dict[str, str] | None = None,
|
|
488
|
+
head_only: bool = False,
|
|
489
|
+
) -> None:
|
|
490
|
+
self.send_response(status)
|
|
491
|
+
self.send_header("Content-Type", content_type)
|
|
492
|
+
self.send_header("Content-Length", str(len(body)))
|
|
493
|
+
if extra_headers:
|
|
494
|
+
for k, v in extra_headers.items():
|
|
495
|
+
self.send_header(k, v)
|
|
496
|
+
self.end_headers()
|
|
497
|
+
if not head_only:
|
|
498
|
+
self.wfile.write(body)
|
|
499
|
+
|
|
500
|
+
def _serve(self, *, head_only: bool) -> None:
|
|
501
|
+
preview = self.server.preview
|
|
502
|
+
parsed = urlparse(self.path)
|
|
503
|
+
raw_path = unquote(parsed.path or "/")
|
|
504
|
+
|
|
505
|
+
if raw_path == "/versions.json":
|
|
506
|
+
payload = json.dumps(
|
|
507
|
+
{
|
|
508
|
+
"root": str(preview.doc_root),
|
|
509
|
+
"default_scheme": preview.default_scheme,
|
|
510
|
+
"versions": discover_versions(preview.versions_dir),
|
|
511
|
+
},
|
|
512
|
+
indent=2,
|
|
513
|
+
).encode("utf-8")
|
|
514
|
+
self._send_bytes(
|
|
515
|
+
HTTPStatus.OK, payload, "application/json; charset=utf-8", head_only=head_only
|
|
516
|
+
)
|
|
517
|
+
return
|
|
518
|
+
|
|
519
|
+
if raw_path == "/__doxtr_reload":
|
|
520
|
+
payload = json.dumps({"build_id": preview.build_id}).encode("utf-8")
|
|
521
|
+
self._send_bytes(
|
|
522
|
+
HTTPStatus.OK, payload, "application/json; charset=utf-8", head_only=head_only
|
|
523
|
+
)
|
|
524
|
+
return
|
|
525
|
+
|
|
526
|
+
resolved_file, active_version = preview.resolve_target(raw_path)
|
|
527
|
+
if resolved_file is None:
|
|
528
|
+
self._send_bytes(
|
|
529
|
+
HTTPStatus.NOT_FOUND,
|
|
530
|
+
b"Not Found",
|
|
531
|
+
"text/plain; charset=utf-8",
|
|
532
|
+
head_only=head_only,
|
|
533
|
+
)
|
|
534
|
+
return
|
|
535
|
+
|
|
536
|
+
if resolved_file == Path("/__FORBIDDEN__"):
|
|
537
|
+
self._send_bytes(
|
|
538
|
+
HTTPStatus.FORBIDDEN,
|
|
539
|
+
b"Forbidden",
|
|
540
|
+
"text/plain; charset=utf-8",
|
|
541
|
+
head_only=head_only,
|
|
542
|
+
)
|
|
543
|
+
return
|
|
544
|
+
|
|
545
|
+
data = resolved_file.read_bytes()
|
|
546
|
+
suffix = resolved_file.suffix.lower()
|
|
547
|
+
mime_type, _ = mimetypes.guess_type(resolved_file.name)
|
|
548
|
+
if suffix == ".svg":
|
|
549
|
+
mime_type = "image/svg+xml"
|
|
550
|
+
elif suffix == ".css":
|
|
551
|
+
mime_type = "text/css; charset=utf-8"
|
|
552
|
+
elif suffix == ".json":
|
|
553
|
+
mime_type = "application/json; charset=utf-8"
|
|
554
|
+
elif suffix == ".js":
|
|
555
|
+
mime_type = "application/javascript; charset=utf-8"
|
|
556
|
+
elif suffix in {".html", ".htm"}:
|
|
557
|
+
mime_type = "text/html; charset=utf-8"
|
|
558
|
+
elif mime_type is None:
|
|
559
|
+
mime_type = "application/octet-stream"
|
|
560
|
+
|
|
561
|
+
extra_headers: dict[str, str] = {}
|
|
562
|
+
if suffix == ".pdf":
|
|
563
|
+
extra_headers["Content-Disposition"] = f'attachment; filename="{resolved_file.name}"'
|
|
564
|
+
|
|
565
|
+
if suffix in {".html", ".htm"}:
|
|
566
|
+
query = parse_qs(parsed.query)
|
|
567
|
+
requested_scheme = query.get("scheme", [None])[0]
|
|
568
|
+
scheme = (
|
|
569
|
+
requested_scheme
|
|
570
|
+
if requested_scheme in {"light", "dark"}
|
|
571
|
+
else preview.default_scheme
|
|
572
|
+
)
|
|
573
|
+
html_text = data.decode("utf-8", errors="replace")
|
|
574
|
+
if scheme:
|
|
575
|
+
html_text = _inject_scheme_script(html_text, scheme)
|
|
576
|
+
versions = discover_versions(preview.versions_dir)
|
|
577
|
+
if versions:
|
|
578
|
+
html_text = _inject_version_bar(html_text, versions, active_version)
|
|
579
|
+
if preview.watch:
|
|
580
|
+
html_text = _inject_reload_script(html_text, preview.build_id)
|
|
581
|
+
data = html_text.encode("utf-8")
|
|
582
|
+
|
|
583
|
+
self._send_bytes(
|
|
584
|
+
HTTPStatus.OK,
|
|
585
|
+
data,
|
|
586
|
+
mime_type,
|
|
587
|
+
extra_headers=extra_headers,
|
|
588
|
+
head_only=head_only,
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
class DoxtrPreviewServer:
|
|
593
|
+
"""Pure-Python multi-version HTTP server with theme scheme preview and watch reload."""
|
|
594
|
+
|
|
595
|
+
def __init__(
|
|
596
|
+
self,
|
|
597
|
+
*,
|
|
598
|
+
doc_root: Path,
|
|
599
|
+
host: str = "127.0.0.1",
|
|
600
|
+
port: int = 8008,
|
|
601
|
+
versions_dir: Path | None = None,
|
|
602
|
+
default_scheme: str | None = None,
|
|
603
|
+
watch: bool = False,
|
|
604
|
+
) -> None:
|
|
605
|
+
self.doc_root = doc_root.resolve()
|
|
606
|
+
self.host = host
|
|
607
|
+
self.port = port
|
|
608
|
+
self.versions_dir = versions_dir.resolve() if versions_dir is not None else None
|
|
609
|
+
self.default_scheme = validate_scheme_name(default_scheme)
|
|
610
|
+
self.watch = watch
|
|
611
|
+
self._lock = threading.Lock()
|
|
612
|
+
self._build_id = 1
|
|
613
|
+
self._httpd: _PreviewHTTPServer | None = None
|
|
614
|
+
self._thread: threading.Thread | None = None
|
|
615
|
+
|
|
616
|
+
@property
|
|
617
|
+
def build_id(self) -> int:
|
|
618
|
+
with self._lock:
|
|
619
|
+
return self._build_id
|
|
620
|
+
|
|
621
|
+
def bump_build_id(self) -> int:
|
|
622
|
+
with self._lock:
|
|
623
|
+
self._build_id += 1
|
|
624
|
+
return self._build_id
|
|
625
|
+
|
|
626
|
+
@property
|
|
627
|
+
def bound_port(self) -> int:
|
|
628
|
+
if self._httpd is None:
|
|
629
|
+
return self.port
|
|
630
|
+
return int(self._httpd.server_address[1])
|
|
631
|
+
|
|
632
|
+
def _safe_file_under(self, base_dir: Path, rel_parts: list[str]) -> Path | None:
|
|
633
|
+
base_resolved = base_dir.resolve()
|
|
634
|
+
normalized = posixpath.normpath("/" + "/".join(rel_parts)).lstrip("/")
|
|
635
|
+
if ".." in rel_parts:
|
|
636
|
+
return Path("/__FORBIDDEN__")
|
|
637
|
+
candidate = (base_resolved / normalized).resolve()
|
|
638
|
+
if not candidate.is_relative_to(base_resolved):
|
|
639
|
+
return Path("/__FORBIDDEN__")
|
|
640
|
+
if candidate.is_dir():
|
|
641
|
+
index_file = candidate / "index.html"
|
|
642
|
+
return index_file if index_file.is_file() else None
|
|
643
|
+
if candidate.is_file():
|
|
644
|
+
return candidate
|
|
645
|
+
return None
|
|
646
|
+
|
|
647
|
+
def resolve_target(self, url_path: str) -> tuple[Path | None, str | None]:
|
|
648
|
+
raw_parts = [p for p in url_path.split("/") if p]
|
|
649
|
+
if ".." in raw_parts:
|
|
650
|
+
return Path("/__FORBIDDEN__"), None
|
|
651
|
+
|
|
652
|
+
if self.versions_dir is not None and self.versions_dir.is_dir() and raw_parts:
|
|
653
|
+
version_name = raw_parts[0]
|
|
654
|
+
version_base = (self.versions_dir / version_name).resolve()
|
|
655
|
+
if version_base.is_dir() and version_base.is_relative_to(self.versions_dir.resolve()):
|
|
656
|
+
resolved = self._safe_file_under(version_base, raw_parts[1:])
|
|
657
|
+
return resolved, version_name
|
|
658
|
+
|
|
659
|
+
resolved_root = self._safe_file_under(self.doc_root, raw_parts)
|
|
660
|
+
return resolved_root, None
|
|
661
|
+
|
|
662
|
+
def start(self, *, background: bool = True) -> None:
|
|
663
|
+
"""Start the HTTP server (daemon thread when *background* is True)."""
|
|
664
|
+
mimetypes.add_type("application/javascript", ".js")
|
|
665
|
+
self._httpd = _PreviewHTTPServer((self.host, self.port), _PreviewRequestHandler, self)
|
|
666
|
+
if background:
|
|
667
|
+
self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)
|
|
668
|
+
self._thread.start()
|
|
669
|
+
else:
|
|
670
|
+
try:
|
|
671
|
+
self._httpd.serve_forever()
|
|
672
|
+
finally:
|
|
673
|
+
self.stop()
|
|
674
|
+
|
|
675
|
+
def stop(self) -> None:
|
|
676
|
+
"""Shutdown HTTP server and thread cleanly."""
|
|
677
|
+
if self._httpd is not None:
|
|
678
|
+
self._httpd.shutdown()
|
|
679
|
+
self._httpd.server_close()
|
|
680
|
+
self._httpd = None
|
|
681
|
+
if self._thread is not None and self._thread.is_alive():
|
|
682
|
+
self._thread.join(timeout=2)
|
|
683
|
+
self._thread = None
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def serve_documentation(
|
|
687
|
+
config: DoxtrConfig,
|
|
688
|
+
*,
|
|
689
|
+
doc_dir: Path | None = None,
|
|
690
|
+
backend: str | None = None,
|
|
691
|
+
host: str | None = None,
|
|
692
|
+
port: int | None = None,
|
|
693
|
+
versions_dir: Path | None = None,
|
|
694
|
+
nginx_template: Path | None = None,
|
|
695
|
+
theme: str | None = None,
|
|
696
|
+
scheme: str | None = None,
|
|
697
|
+
watch: bool = False,
|
|
698
|
+
which_fn: Callable[[str], str | None] = shutil.which,
|
|
699
|
+
output_fn: Callable[[str], None] = print,
|
|
700
|
+
runner: CommandRunner = default_runner,
|
|
701
|
+
) -> None:
|
|
702
|
+
"""Serve built documentation via Nginx or Python preview server."""
|
|
703
|
+
validated_scheme = validate_scheme_name(scheme)
|
|
704
|
+
req_backend = backend or config.serve.default_backend
|
|
705
|
+
selected_backend = select_backend(
|
|
706
|
+
req_backend,
|
|
707
|
+
watch=watch,
|
|
708
|
+
theme=theme,
|
|
709
|
+
scheme=validated_scheme,
|
|
710
|
+
which_fn=which_fn,
|
|
711
|
+
)
|
|
712
|
+
resolved_host = host or config.serve.host
|
|
713
|
+
resolved_port = port if port is not None else config.serve.port
|
|
714
|
+
resolved_versions = (
|
|
715
|
+
versions_dir.resolve()
|
|
716
|
+
if versions_dir is not None
|
|
717
|
+
else (config.versions_path if config.versions_path.is_dir() else None)
|
|
718
|
+
)
|
|
719
|
+
doc_root = resolve_default_doc_root(config, explicit_dir=doc_dir)
|
|
720
|
+
|
|
721
|
+
if theme and not doc_dir:
|
|
722
|
+
doc_root = build_theme_preview_cache(
|
|
723
|
+
config,
|
|
724
|
+
theme,
|
|
725
|
+
scheme=validated_scheme,
|
|
726
|
+
runner=runner,
|
|
727
|
+
which_fn=which_fn,
|
|
728
|
+
)
|
|
729
|
+
|
|
730
|
+
if selected_backend == "nginx":
|
|
731
|
+
tpl = (
|
|
732
|
+
nginx_template.resolve()
|
|
733
|
+
if nginx_template is not None
|
|
734
|
+
else resolve_nginx_template(config.serve.nginx_template)
|
|
735
|
+
)
|
|
736
|
+
output_fn(f"Serving {doc_root} with Nginx at http://{resolved_host}:{resolved_port}/")
|
|
737
|
+
rc = serve_nginx(
|
|
738
|
+
doc_root=doc_root,
|
|
739
|
+
port=resolved_port,
|
|
740
|
+
host=resolved_host,
|
|
741
|
+
template_path=tpl,
|
|
742
|
+
versions_dir=resolved_versions,
|
|
743
|
+
which_fn=which_fn,
|
|
744
|
+
)
|
|
745
|
+
if rc != 0:
|
|
746
|
+
raise BuildError(f"Nginx exited with non-zero status {rc}.")
|
|
747
|
+
return
|
|
748
|
+
|
|
749
|
+
server = DoxtrPreviewServer(
|
|
750
|
+
doc_root=doc_root,
|
|
751
|
+
host=resolved_host,
|
|
752
|
+
port=resolved_port,
|
|
753
|
+
versions_dir=resolved_versions,
|
|
754
|
+
default_scheme=validated_scheme,
|
|
755
|
+
watch=watch,
|
|
756
|
+
)
|
|
757
|
+
watcher: SourceWatcher | None = None
|
|
758
|
+
if watch:
|
|
759
|
+
active_theme = theme or config.html.theme
|
|
760
|
+
|
|
761
|
+
def _rebuild(changed: list[Path]) -> None:
|
|
762
|
+
try:
|
|
763
|
+
sphinx_bin = require_binary("sphinx-build", which_fn=which_fn)
|
|
764
|
+
doctrees = config.build_path / "doctrees-watch"
|
|
765
|
+
cmd = [
|
|
766
|
+
sphinx_bin,
|
|
767
|
+
"-b",
|
|
768
|
+
"html",
|
|
769
|
+
"-d",
|
|
770
|
+
str(doctrees),
|
|
771
|
+
"-D",
|
|
772
|
+
f"html_theme={active_theme}",
|
|
773
|
+
]
|
|
774
|
+
if validated_scheme:
|
|
775
|
+
cmd.extend(["-D", f"doxtr_color_scheme={validated_scheme}"])
|
|
776
|
+
cmd.extend([str(config.source_path), str(doc_root)])
|
|
777
|
+
runner(cmd, config.project_root)
|
|
778
|
+
new_id = server.bump_build_id()
|
|
779
|
+
output_fn(f"[watch] Rebuilt HTML after {changed[0].name} (build #{new_id})")
|
|
780
|
+
except MissingBinaryError:
|
|
781
|
+
raise
|
|
782
|
+
except Exception as exc:
|
|
783
|
+
output_fn(f"[watch] Rebuild error: {exc}")
|
|
784
|
+
|
|
785
|
+
watcher = SourceWatcher(config.source_path, _rebuild)
|
|
786
|
+
watcher.start()
|
|
787
|
+
|
|
788
|
+
output_fn(
|
|
789
|
+
f"Serving {doc_root} with Python preview server at http://{resolved_host}:{resolved_port}/"
|
|
790
|
+
)
|
|
791
|
+
server.start(background=True)
|
|
792
|
+
try:
|
|
793
|
+
while True:
|
|
794
|
+
time.sleep(0.5)
|
|
795
|
+
except KeyboardInterrupt:
|
|
796
|
+
raise
|
|
797
|
+
finally:
|
|
798
|
+
if watcher is not None:
|
|
799
|
+
watcher.stop()
|
|
800
|
+
server.stop()
|