mdshelf 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.
- mdshelf/__init__.py +3 -0
- mdshelf/__main__.py +3 -0
- mdshelf/cli.py +75 -0
- mdshelf/server.py +237 -0
- mdshelf/static/index.html +1013 -0
- mdshelf/static/vendor/inter-latin-wght-normal.woff2 +0 -0
- mdshelf/static/vendor/jetbrains-mono-latin-wght-normal.woff2 +0 -0
- mdshelf/static/vendor/marked-12.0.2.min.js +6 -0
- mdshelf/static/vendor/mermaid-10.9.1.min.js +2029 -0
- mdshelf-0.1.0.dist-info/METADATA +103 -0
- mdshelf-0.1.0.dist-info/RECORD +18 -0
- mdshelf-0.1.0.dist-info/WHEEL +4 -0
- mdshelf-0.1.0.dist-info/entry_points.txt +2 -0
- mdshelf-0.1.0.dist-info/licenses/LICENSE +21 -0
- mdshelf-0.1.0.dist-info/licenses/licenses/inter-OFL.txt +93 -0
- mdshelf-0.1.0.dist-info/licenses/licenses/jetbrains-mono-OFL.txt +93 -0
- mdshelf-0.1.0.dist-info/licenses/licenses/marked-LICENSE.md +44 -0
- mdshelf-0.1.0.dist-info/licenses/licenses/mermaid-LICENSE.txt +21 -0
mdshelf/__init__.py
ADDED
mdshelf/__main__.py
ADDED
mdshelf/cli.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Command line entry point: `mdshelf [FOLDER]`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import errno
|
|
8
|
+
import sys
|
|
9
|
+
import webbrowser
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .server import DEFAULT_EXCLUDES, Config, make_server
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main(argv: list[str] | None = None) -> None:
|
|
17
|
+
p = argparse.ArgumentParser(
|
|
18
|
+
prog="mdshelf",
|
|
19
|
+
description="Browse the Markdown files in a folder: sidebar, outline, highlights, "
|
|
20
|
+
"margin comments, share and archive. Local only; nothing leaves your machine.",
|
|
21
|
+
)
|
|
22
|
+
p.add_argument("folder", nargs="?", default=".", help="folder to browse (default: current)")
|
|
23
|
+
p.add_argument("-p", "--port", type=int, default=8780, help="port on 127.0.0.1 (default 8780)")
|
|
24
|
+
p.add_argument("--no-open", action="store_true", help="don't open a browser tab")
|
|
25
|
+
p.add_argument("--title", default="", help="name shown in the sidebar (default: folder name)")
|
|
26
|
+
p.add_argument(
|
|
27
|
+
"--archive-dir",
|
|
28
|
+
default="archived",
|
|
29
|
+
help="folder, relative to FOLDER, that Archive moves files into (default: archived)",
|
|
30
|
+
)
|
|
31
|
+
p.add_argument(
|
|
32
|
+
"--exclude",
|
|
33
|
+
action="append",
|
|
34
|
+
default=[],
|
|
35
|
+
metavar="DIR",
|
|
36
|
+
help="extra directory name to skip anywhere (repeatable)",
|
|
37
|
+
)
|
|
38
|
+
p.add_argument(
|
|
39
|
+
"--read-only",
|
|
40
|
+
action="store_true",
|
|
41
|
+
help="disable Archive/Restore, so the server never changes any file",
|
|
42
|
+
)
|
|
43
|
+
p.add_argument("--version", action="version", version=f"mdshelf {__version__}")
|
|
44
|
+
args = p.parse_args(argv)
|
|
45
|
+
|
|
46
|
+
root = Path(args.folder).expanduser()
|
|
47
|
+
if not root.is_dir():
|
|
48
|
+
sys.exit(f"mdshelf: {root} is not a folder.")
|
|
49
|
+
archive = args.archive_dir.strip("/")
|
|
50
|
+
if not archive or ".." in Path(archive).parts or Path(archive).is_absolute():
|
|
51
|
+
sys.exit("mdshelf: --archive-dir must be a plain folder name inside FOLDER.")
|
|
52
|
+
|
|
53
|
+
cfg = Config(
|
|
54
|
+
root=root,
|
|
55
|
+
title=args.title,
|
|
56
|
+
archive_name=archive,
|
|
57
|
+
exclude=DEFAULT_EXCLUDES | frozenset(args.exclude),
|
|
58
|
+
read_only=args.read_only,
|
|
59
|
+
)
|
|
60
|
+
try:
|
|
61
|
+
server = make_server(cfg, args.port)
|
|
62
|
+
except OSError as exc:
|
|
63
|
+
if exc.errno != errno.EADDRINUSE:
|
|
64
|
+
raise
|
|
65
|
+
sys.exit(
|
|
66
|
+
f"mdshelf: port {args.port} is already in use (maybe another mdshelf).\n"
|
|
67
|
+
f" Use another port: mdshelf --port {args.port + 1}"
|
|
68
|
+
)
|
|
69
|
+
url = f"http://127.0.0.1:{args.port}/"
|
|
70
|
+
print(f"mdshelf: serving {cfg.root}\n {url} (Ctrl+C to stop)")
|
|
71
|
+
if not args.no_open:
|
|
72
|
+
webbrowser.open(url)
|
|
73
|
+
with contextlib.suppress(KeyboardInterrupt):
|
|
74
|
+
server.serve_forever()
|
|
75
|
+
server.server_close()
|
mdshelf/server.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Local Markdown browser: point it at a folder and read every .md file in it.
|
|
2
|
+
|
|
3
|
+
Standard library only, and works offline (marked, mermaid and two fonts ship inside the package).
|
|
4
|
+
Binds to 127.0.0.1 and serves nothing but .md files under the folder plus the bundled assets.
|
|
5
|
+
The only write it allows is moving a .md file to or from the archive folder (see --read-only).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from http import HTTPStatus
|
|
14
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from urllib.parse import unquote, urlparse
|
|
17
|
+
|
|
18
|
+
STATIC = Path(__file__).with_name("static")
|
|
19
|
+
VENDOR = STATIC / "vendor"
|
|
20
|
+
VENDOR_TYPES = {".js": "text/javascript", ".woff2": "font/woff2"}
|
|
21
|
+
DEFAULT_EXCLUDES = frozenset(
|
|
22
|
+
{
|
|
23
|
+
".git",
|
|
24
|
+
"node_modules",
|
|
25
|
+
".venv",
|
|
26
|
+
"venv",
|
|
27
|
+
"dist",
|
|
28
|
+
"build",
|
|
29
|
+
"vendor",
|
|
30
|
+
"__pycache__",
|
|
31
|
+
".pytest_cache",
|
|
32
|
+
".ruff_cache",
|
|
33
|
+
".mypy_cache",
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
CSRF_HEADER = ("X-Requested-With", "mdshelf")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Config:
|
|
41
|
+
root: Path
|
|
42
|
+
title: str = ""
|
|
43
|
+
archive_name: str = "archived"
|
|
44
|
+
exclude: frozenset[str] = DEFAULT_EXCLUDES
|
|
45
|
+
read_only: bool = False
|
|
46
|
+
|
|
47
|
+
def __post_init__(self) -> None:
|
|
48
|
+
object.__setattr__(self, "root", self.root.resolve())
|
|
49
|
+
if not self.title:
|
|
50
|
+
object.__setattr__(self, "title", self.root.name or "Docs")
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def archive(self) -> Path:
|
|
54
|
+
return self.root / self.archive_name
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def project_id(self) -> str:
|
|
58
|
+
"""Stable per folder, so notes and highlights from different projects never mix."""
|
|
59
|
+
return hashlib.sha1(str(self.root).encode()).hexdigest()[:10]
|
|
60
|
+
|
|
61
|
+
def public(self) -> dict:
|
|
62
|
+
return {
|
|
63
|
+
"title": self.title,
|
|
64
|
+
"id": self.project_id,
|
|
65
|
+
"archiveName": self.archive_name,
|
|
66
|
+
"readOnly": self.read_only,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class MoveError(Exception):
|
|
71
|
+
def __init__(self, message: str, status: HTTPStatus):
|
|
72
|
+
super().__init__(message)
|
|
73
|
+
self.status = status
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def list_markdown(cfg: Config) -> list[str]:
|
|
77
|
+
files = []
|
|
78
|
+
for path in cfg.root.rglob("*.md"):
|
|
79
|
+
rel = path.relative_to(cfg.root)
|
|
80
|
+
if rel.parts[0] != cfg.archive_name and not cfg.exclude.intersection(rel.parts[:-1]):
|
|
81
|
+
files.append(rel.as_posix())
|
|
82
|
+
# Top-level files first, then grouped by folder.
|
|
83
|
+
return sorted(files, key=lambda p: ("/" in p, p.rpartition("/")[0].lower(), p.lower()))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def list_archived(cfg: Config) -> list[str]:
|
|
87
|
+
"""Archived docs, as root-relative paths that start with the archive folder name."""
|
|
88
|
+
if not cfg.archive.is_dir():
|
|
89
|
+
return []
|
|
90
|
+
return sorted(p.relative_to(cfg.root).as_posix() for p in cfg.archive.rglob("*.md"))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def resolve_markdown(cfg: Config, rel: str) -> Path | None:
|
|
94
|
+
"""Map a request path to a .md file under the root (or the archive), else None."""
|
|
95
|
+
path = (cfg.root / rel).resolve()
|
|
96
|
+
if path.suffix.lower() != ".md" or not path.is_file() or not path.is_relative_to(cfg.root):
|
|
97
|
+
return None
|
|
98
|
+
dirs = path.relative_to(cfg.root).parts[:-1]
|
|
99
|
+
if dirs[:1] == (cfg.archive_name,):
|
|
100
|
+
dirs = dirs[1:]
|
|
101
|
+
if cfg.exclude.intersection(dirs):
|
|
102
|
+
return None
|
|
103
|
+
return path
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def move_doc(cfg: Config, rel: str, archive: bool) -> str:
|
|
107
|
+
"""Archive `rel` into <archive>/<same path>, or restore it from there. Returns the new path."""
|
|
108
|
+
if cfg.read_only:
|
|
109
|
+
raise MoveError("Read-only mode.", HTTPStatus.FORBIDDEN)
|
|
110
|
+
src = resolve_markdown(cfg, rel)
|
|
111
|
+
if src is None:
|
|
112
|
+
raise MoveError("No such Markdown file.", HTTPStatus.NOT_FOUND)
|
|
113
|
+
in_archive = src.is_relative_to(cfg.archive)
|
|
114
|
+
if archive and in_archive:
|
|
115
|
+
raise MoveError("Already archived.", HTTPStatus.BAD_REQUEST)
|
|
116
|
+
if not archive and not in_archive:
|
|
117
|
+
raise MoveError("Not in the archive.", HTTPStatus.BAD_REQUEST)
|
|
118
|
+
rel_path = src.relative_to(cfg.archive if in_archive else cfg.root)
|
|
119
|
+
dest = cfg.root / rel_path if in_archive else cfg.archive / rel_path
|
|
120
|
+
if dest.exists():
|
|
121
|
+
where = "the original location" if in_archive else "the archive"
|
|
122
|
+
raise MoveError(
|
|
123
|
+
f"A file already exists at {dest.relative_to(cfg.root).as_posix()} ({where}). "
|
|
124
|
+
"Rename or remove it first.",
|
|
125
|
+
HTTPStatus.CONFLICT,
|
|
126
|
+
)
|
|
127
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
128
|
+
src.rename(dest)
|
|
129
|
+
return dest.relative_to(cfg.root).as_posix()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def vendor_files() -> set[str]:
|
|
133
|
+
return {p.name for p in VENDOR.iterdir() if p.suffix in VENDOR_TYPES}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class Handler(BaseHTTPRequestHandler):
|
|
137
|
+
server: MdServer # type: ignore[assignment]
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def cfg(self) -> Config:
|
|
141
|
+
return self.server.cfg
|
|
142
|
+
|
|
143
|
+
def do_GET(self) -> None:
|
|
144
|
+
route = unquote(urlparse(self.path).path)
|
|
145
|
+
if route == "/":
|
|
146
|
+
self._send(self._page(), "text/html; charset=utf-8")
|
|
147
|
+
elif route == "/api/config":
|
|
148
|
+
self._send_json(self.cfg.public())
|
|
149
|
+
elif route == "/api/files":
|
|
150
|
+
self._send_json(list_markdown(self.cfg))
|
|
151
|
+
elif route == "/api/archived":
|
|
152
|
+
self._send_json(list_archived(self.cfg))
|
|
153
|
+
elif route.startswith("/raw/") and (
|
|
154
|
+
path := resolve_markdown(self.cfg, route.removeprefix("/raw/"))
|
|
155
|
+
):
|
|
156
|
+
self._send(path.read_bytes(), "text/markdown; charset=utf-8")
|
|
157
|
+
elif (
|
|
158
|
+
route.startswith("/vendor/")
|
|
159
|
+
and (name := route.removeprefix("/vendor/")) in vendor_files()
|
|
160
|
+
):
|
|
161
|
+
# File names carry the version, so the browser can keep them.
|
|
162
|
+
self._send(
|
|
163
|
+
(VENDOR / name).read_bytes(),
|
|
164
|
+
VENDOR_TYPES[Path(name).suffix],
|
|
165
|
+
cache="max-age=86400",
|
|
166
|
+
)
|
|
167
|
+
else:
|
|
168
|
+
self.send_error(HTTPStatus.NOT_FOUND)
|
|
169
|
+
|
|
170
|
+
def _page(self) -> bytes:
|
|
171
|
+
# Hand the folder's settings to the page; "</" is escaped so the JSON can't end the script.
|
|
172
|
+
cfg_json = json.dumps(self.cfg.public()).replace("</", "<\\/")
|
|
173
|
+
html = (STATIC / "index.html").read_text(encoding="utf-8")
|
|
174
|
+
return html.replace("__MDSHELF_CONFIG__", cfg_json).encode()
|
|
175
|
+
|
|
176
|
+
def do_POST(self) -> None:
|
|
177
|
+
route = urlparse(self.path).path
|
|
178
|
+
if route not in ("/api/archive", "/api/restore"):
|
|
179
|
+
return self.send_error(HTTPStatus.NOT_FOUND)
|
|
180
|
+
# Only our own page may call this: block DNS rebinding (Host) and cross-site posts
|
|
181
|
+
# (Origin, plus a custom header that browsers won't send cross-origin without a preflight).
|
|
182
|
+
port = self.server.server_port
|
|
183
|
+
allowed = {f"127.0.0.1:{port}", f"localhost:{port}"}
|
|
184
|
+
origin = self.headers.get("Origin")
|
|
185
|
+
if (
|
|
186
|
+
self.headers.get("Host") not in allowed
|
|
187
|
+
or (origin and origin.removeprefix("http://") not in allowed)
|
|
188
|
+
or self.headers.get(CSRF_HEADER[0]) != CSRF_HEADER[1]
|
|
189
|
+
):
|
|
190
|
+
return self.send_error(HTTPStatus.FORBIDDEN)
|
|
191
|
+
try:
|
|
192
|
+
length = int(self.headers.get("Content-Length", "0"))
|
|
193
|
+
rel = json.loads(self.rfile.read(min(length, 4096)))["path"]
|
|
194
|
+
if not isinstance(rel, str):
|
|
195
|
+
raise TypeError
|
|
196
|
+
new = move_doc(self.cfg, rel, archive=route == "/api/archive")
|
|
197
|
+
except MoveError as exc:
|
|
198
|
+
return self._send_json({"error": str(exc)}, exc.status)
|
|
199
|
+
except (ValueError, KeyError, TypeError):
|
|
200
|
+
return self._send_json({"error": "Bad request."}, HTTPStatus.BAD_REQUEST)
|
|
201
|
+
except OSError as exc:
|
|
202
|
+
return self._send_json(
|
|
203
|
+
{"error": f"Move failed: {exc.strerror}"}, HTTPStatus.INTERNAL_SERVER_ERROR
|
|
204
|
+
)
|
|
205
|
+
self._send_json({"path": new})
|
|
206
|
+
|
|
207
|
+
def _send_json(self, data: object, status: HTTPStatus = HTTPStatus.OK) -> None:
|
|
208
|
+
self._send(json.dumps(data).encode(), "application/json", status=status)
|
|
209
|
+
|
|
210
|
+
def _send(
|
|
211
|
+
self,
|
|
212
|
+
body: bytes,
|
|
213
|
+
content_type: str,
|
|
214
|
+
cache: str = "no-store",
|
|
215
|
+
status: HTTPStatus = HTTPStatus.OK,
|
|
216
|
+
) -> None:
|
|
217
|
+
self.send_response(status)
|
|
218
|
+
self.send_header("Content-Type", content_type)
|
|
219
|
+
self.send_header("Cache-Control", cache)
|
|
220
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
221
|
+
self.send_header("Content-Length", str(len(body)))
|
|
222
|
+
self.end_headers()
|
|
223
|
+
self.wfile.write(body)
|
|
224
|
+
|
|
225
|
+
def log_message(self, *args) -> None: # keep the terminal quiet
|
|
226
|
+
pass
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class MdServer(ThreadingHTTPServer):
|
|
230
|
+
def __init__(self, cfg: Config, port: int):
|
|
231
|
+
super().__init__(("127.0.0.1", port), Handler)
|
|
232
|
+
self.cfg = cfg
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def make_server(cfg: Config, port: int = 0) -> MdServer:
|
|
236
|
+
"""Create (but don't start) a server bound to 127.0.0.1. Port 0 picks a free one."""
|
|
237
|
+
return MdServer(cfg, port)
|