This repository was archived by the owner on Oct 15, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathserve.py
More file actions
180 lines (161 loc) · 5.63 KB
/
Copy pathserve.py
File metadata and controls
180 lines (161 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#!/usr/bin/env python3
"""Zero-dependency live-reload static server for the markdown-driven guide.
How the "edit .md -> refresh" workflow works:
1. This server serves the static files (same as `python3 -m http.server`).
2. It injects a tiny reload client into every .html response.
3. A background thread watches all .md/.html/.css/.js/.svg/... files.
4. When you save a file, the client is notified and the browser reloads.
No build step, no external packages, works on GitHub Pages unchanged.
Usage:
python3 serve.py [port] # default 8000
Then open http://localhost:<port>/ and edit any .md — the page reloads on save.
"""
import http.server
import os
import sys
import time
import threading
ROOT = os.path.dirname(os.path.abspath(__file__))
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
_lock = threading.Lock()
_state = {} # path -> mtime
_counter = 0
_event = threading.Event()
IGNORE_DIRS = {'.git', 'node_modules', '__pycache__', '.codebuddy'}
WATCH_EXT = ('.md', '.html', '.css', '.js', '.svg', '.png', '.jpg', '.jpeg', '.gif')
def scan(initial=False):
global _counter
changed = False
seen = set()
for dirpath, dirnames, filenames in os.walk(ROOT):
dirnames[:] = [d for d in dirnames if d not in IGNORE_DIRS]
for fn in filenames:
if not fn.lower().endswith(WATCH_EXT):
continue
p = os.path.join(dirpath, fn)
seen.add(p)
try:
m = os.path.getmtime(p)
except OSError:
continue
if initial:
_state[p] = m
else:
old = _state.get(p)
if old is None or old != m:
_state[p] = m
changed = True
if not initial:
for p in list(_state):
if p not in seen:
del _state[p]
changed = True
if changed and not initial:
with _lock:
_counter += 1
_event.set()
_event.clear()
def watcher():
scan(initial=True)
while True:
time.sleep(0.5)
scan(initial=False)
CONTENT_TYPES = {
'.html': 'text/html; charset=utf-8',
'.md': 'text/markdown; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.json': 'application/json',
}
RELOAD_CLIENT = b"""<script>
(function(){
// Persist the last-seen counter across reloads. Otherwise `last` resets to 0
// on every page load while the server's counter only ever increases, so the
// page reloads again immediately after each reload (infinite refresh loop).
var KEY = 'livereload-last';
var last = parseInt(sessionStorage.getItem(KEY) || '0', 10);
function poll(){
fetch('/__reload?last='+last).then(function(r){ return r.text(); }).then(function(t){
var n = parseInt(t, 10);
if (n > last) {
sessionStorage.setItem(KEY, n);
location.reload();
} else {
poll();
}
}).catch(function(){ setTimeout(poll, 2000); });
}
poll();
})();
</script>
"""
class Handler(http.server.BaseHTTPRequestHandler):
def _safe(self, path):
real = os.path.realpath(path)
return real == ROOT or real.startswith(ROOT + os.sep)
def do_GET(self):
url = self.path.split('?', 1)[0]
if url == '/__reload':
self.handle_reload()
return
if url == '/':
url = '/index.html'
fpath = os.path.normpath(os.path.join(ROOT, url.lstrip('/')))
if not self._safe(fpath) or not os.path.isfile(fpath):
self.send_error(404, 'Not found')
return
ext = os.path.splitext(fpath)[1].lower()
ctype = CONTENT_TYPES.get(ext, 'application/octet-stream')
with open(fpath, 'rb') as f:
data = f.read()
if ext == '.html':
idx = data.rfind(b'</body>')
if idx != -1:
data = data[:idx] + RELOAD_CLIENT + data[idx:]
self.send_response(200)
self.send_header('Content-Type', ctype)
self.send_header('Content-Length', str(len(data)))
self.send_header('Cache-Control', 'no-store')
self.end_headers()
try:
self.wfile.write(data)
except BrokenPipeError:
# Client closed the connection early (refresh/close/tab switch).
# Harmless — the response was already sent; just ignore it.
pass
def handle_reload(self):
try:
last = int(self.path.split('last=', 1)[1])
except Exception:
last = 0
deadline = time.time() + 60
while True:
with _lock:
cur = _counter
if cur > last or time.time() > deadline:
break
_event.wait(0.5)
try:
self.send_response(200)
self.send_header('Content-Type', 'text/plain; charset=utf-8')
self.send_header('Cache-Control', 'no-store')
self.end_headers()
self.wfile.write(str(_counter).encode())
except BrokenPipeError:
# Client gave up waiting (e.g. navigated away). Ignore.
pass
def log_message(self, fmt, *args):
pass
if __name__ == '__main__':
threading.Thread(target=watcher, daemon=True).start()
srv = http.server.ThreadingHTTPServer(('0.0.0.0', PORT), Handler)
print(f"Live-reload server on http://localhost:{PORT}/ (Ctrl+C to stop)")
try:
srv.serve_forever()
except KeyboardInterrupt:
srv.shutdown()