context-mapper 0.20.2__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,166 @@
1
+ """Serve the built site, and rebuild it while the YAML files change.
2
+
3
+ `context-mapper serve` builds the site once and serves the output directory
4
+ over HTTP. With `--watch` it also polls the model and style files and rebuilds
5
+ whenever they change: a rebuild that fails says why on the terminal and leaves
6
+ the last good site up, so a broken edit never takes the page down.
7
+
8
+ The watcher is a plain polling loop over each file's mtime and size, so there
9
+ is no dependency beyond the standard library. In watch mode the served HTML
10
+ pages carry a small script that reloads the page after each successful rebuild;
11
+ it is injected on the wire only — the files on disk stay exactly what the
12
+ build wrote, ready to publish as they are.
13
+ """
14
+ import argparse
15
+ import functools
16
+ import http.server
17
+ import sys
18
+ import threading
19
+ from pathlib import Path
20
+
21
+ from .build import add_input_flags, build_site
22
+
23
+ POLL_SECONDS = 0.5 # how often the watcher checks the YAML files
24
+ SETTLE_SECONDS = 0.2 # grace period for editors that write in place
25
+
26
+ RELOAD_SNIPPET = """\
27
+ <script>
28
+ (function () {
29
+ var buildId = null;
30
+ setInterval(function () {
31
+ fetch("/__build_id", {cache: "no-store"})
32
+ .then(function (response) { return response.text(); })
33
+ .then(function (id) {
34
+ if (buildId !== null && id !== buildId) location.reload();
35
+ buildId = id;
36
+ })
37
+ .catch(function () {});
38
+ }, 1000);
39
+ })();
40
+ </script>"""
41
+
42
+
43
+ class Handler(http.server.SimpleHTTPRequestHandler):
44
+ """Serves the output directory; in watch mode HTML pages reload themselves."""
45
+
46
+ def do_GET(self):
47
+ if self.server.watching:
48
+ path = self.path.split("?", 1)[0]
49
+ if path == "/__build_id":
50
+ self._send_text(str(self.server.build_id), "text/plain; charset=utf-8")
51
+ return
52
+ page = Path(self.translate_path(path))
53
+ if page.is_dir():
54
+ page = page / "index.html"
55
+ if page.suffix == ".html" and page.is_file():
56
+ try:
57
+ html = page.read_text()
58
+ except OSError:
59
+ self.send_error(404, "File not found")
60
+ return
61
+ self._send_text(html.replace("</body>", RELOAD_SNIPPET + "</body>"),
62
+ "text/html; charset=utf-8")
63
+ return
64
+ super().do_GET()
65
+
66
+ def _send_text(self, text, content_type):
67
+ body = text.encode("utf-8")
68
+ self.send_response(200)
69
+ self.send_header("Content-Type", content_type)
70
+ self.send_header("Content-Length", str(len(body)))
71
+ self.send_header("Cache-Control", "no-store")
72
+ self.end_headers()
73
+ self.wfile.write(body)
74
+
75
+ def log_request(self, code="-", size="-"):
76
+ if self.path.split("?", 1)[0] != "/__build_id": # the page polls it every second
77
+ super().log_request(code, size)
78
+
79
+
80
+ class Server(http.server.ThreadingHTTPServer):
81
+ """A file server for the output directory that also carries the build id."""
82
+
83
+ def __init__(self, address, out, watching):
84
+ super().__init__(address, functools.partial(Handler, directory=str(out)))
85
+ self.watching = watching
86
+ self.build_id = 0
87
+
88
+
89
+ def file_stamp(path):
90
+ """What counts as a change: a file's mtime and size, or None if it is gone."""
91
+ try:
92
+ stat = path.stat()
93
+ except OSError:
94
+ return None
95
+ return stat.st_mtime_ns, stat.st_size
96
+
97
+
98
+ def watch(server, paths, rebuild, stop=None, ready=None):
99
+ """Poll the files and rebuild on every change; runs on a daemon thread.
100
+
101
+ A rebuild that raises SystemExit has already said why (or carries the
102
+ message itself): report it, keep the last good site up, and keep watching —
103
+ the next save fixes it. A successful rebuild bumps the build id, which is
104
+ what tells the pages to reload.
105
+ """
106
+ stop = stop or threading.Event()
107
+ stamps = {path: file_stamp(path) for path in paths}
108
+ if ready:
109
+ ready.set()
110
+ while not stop.is_set():
111
+ stop.wait(POLL_SECONDS)
112
+ current = {path: file_stamp(path) for path in paths}
113
+ if current == stamps:
114
+ continue
115
+ changed = [str(path) for path in paths if current[path] != stamps[path]]
116
+ stamps = current
117
+ print(f"change detected in {', '.join(changed)}; rebuilding")
118
+ stop.wait(SETTLE_SECONDS)
119
+ try:
120
+ rebuild()
121
+ except SystemExit as err:
122
+ if err.code not in (None, 1): # 1 has already been reported; a string has not
123
+ print(err.code, file=sys.stderr)
124
+ print("rebuild failed; the page still shows the last good build", file=sys.stderr)
125
+ else:
126
+ server.build_id += 1
127
+
128
+
129
+ def parse_args(argv=None):
130
+ parser = argparse.ArgumentParser(
131
+ prog="context-mapper serve",
132
+ description="Build the site and serve it over HTTP. With --watch, rebuild "
133
+ "it whenever the model or style file changes.")
134
+ add_input_flags(parser)
135
+ parser.add_argument("--host", default="127.0.0.1",
136
+ help="the interface to listen on (default: %(default)s)")
137
+ parser.add_argument("--port", type=int, default=8000,
138
+ help="the port to listen on (default: %(default)s)")
139
+ parser.add_argument("--watch", action="store_true",
140
+ help="rebuild whenever the model or style file changes")
141
+ return parser.parse_args(argv)
142
+
143
+
144
+ def serve(argv=None):
145
+ args = parse_args(argv)
146
+ build_site(args) # the same fail-fast as a plain build
147
+ try:
148
+ server = Server((args.host, args.port), args.out, args.watch)
149
+ except OSError as err:
150
+ sys.exit(f"error: cannot listen on {args.host}:{args.port}: {err.strerror or err}")
151
+ host = "localhost" if args.host in ("", "0.0.0.0", "::") else args.host
152
+ print(f"serving {args.out} at http://{host}:{server.server_port}/ (Ctrl+C to stop)", flush=True)
153
+ if args.watch:
154
+ print(f"watching {args.model} and {args.diagrams}", flush=True)
155
+
156
+ def rebuild():
157
+ build_site(args)
158
+
159
+ threading.Thread(target=watch, args=(server, (args.model, args.diagrams), rebuild),
160
+ daemon=True).start()
161
+ try:
162
+ server.serve_forever()
163
+ except KeyboardInterrupt:
164
+ print("\nstopped")
165
+ finally:
166
+ server.server_close()