stilo-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.
- stilo/__init__.py +6 -0
- stilo/__main__.py +7 -0
- stilo/cli/__init__.py +18 -0
- stilo/cli/commands.py +80 -0
- stilo/server/__init__.py +5 -0
- stilo/server/app.py +78 -0
- stilo/server/storage.py +140 -0
- stilo/web/assets/index-4AKEJowe.css +1 -0
- stilo/web/assets/index-CM5cmnCe.js +889 -0
- stilo/web/assets/texl_wasm_bg-DqOV-p_i.wasm +0 -0
- stilo/web/index.html +20 -0
- stilo_cli-0.1.0.dist-info/METADATA +75 -0
- stilo_cli-0.1.0.dist-info/RECORD +16 -0
- stilo_cli-0.1.0.dist-info/WHEEL +4 -0
- stilo_cli-0.1.0.dist-info/entry_points.txt +2 -0
- stilo_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
stilo/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Stilo: edit and render a folder of linked Texl documents.
|
|
2
|
+
|
|
3
|
+
Subpackages: `stilo.cli` (the `stilo` command), `stilo.server` (the HTTP
|
|
4
|
+
server), and `web/` (the built web app, not Python: written by `npm run
|
|
5
|
+
build` in `web/`). The server never imports the CLI.
|
|
6
|
+
"""
|
stilo/__main__.py
ADDED
stilo/cli/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""The `stilo` command line: one subcommand per entry in `COMMANDS`."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
|
|
5
|
+
from .commands import COMMANDS
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv=None) -> int:
|
|
9
|
+
parser = argparse.ArgumentParser(
|
|
10
|
+
prog="stilo", description="Edit and render a folder of linked Texl documents.")
|
|
11
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
12
|
+
for command in COMMANDS:
|
|
13
|
+
sub = subparsers.add_parser(command.name, help=command.help)
|
|
14
|
+
command.add_arguments(sub)
|
|
15
|
+
sub.set_defaults(run=command.run)
|
|
16
|
+
args = parser.parse_args(argv)
|
|
17
|
+
return args.run(args)
|
|
18
|
+
|
stilo/cli/commands.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The `stilo` subcommands.
|
|
2
|
+
|
|
3
|
+
Each command is a `Command`: a name, a help line, a function that adds its
|
|
4
|
+
arguments to a parser and a function that runs it. `COMMANDS` lists them in
|
|
5
|
+
the order `stilo --help` shows them; a plugin system can later add its own.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
import pytexl
|
|
15
|
+
import uvicorn
|
|
16
|
+
|
|
17
|
+
from stilo.server import create_app
|
|
18
|
+
|
|
19
|
+
# The built web app, `stilo/web`: written there by `npm run build` in a
|
|
20
|
+
# checkout, shipped there in the package
|
|
21
|
+
WEB_DIST = Path(__file__).resolve().parents[1] / "web"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Command:
|
|
26
|
+
name: str
|
|
27
|
+
help: str
|
|
28
|
+
add_arguments: Callable
|
|
29
|
+
run: Callable # (args) -> exit status
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def render_arguments(parser):
|
|
33
|
+
parser.add_argument("file", type=Path,
|
|
34
|
+
help="document to render; relative imports resolve from its folder")
|
|
35
|
+
parser.add_argument("-o", "--output", type=Path,
|
|
36
|
+
help="output file (default: standard output)")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def render(args) -> int:
|
|
40
|
+
"""Renders a document to standard output or a file, like `texl`."""
|
|
41
|
+
path = args.file.resolve()
|
|
42
|
+
doc = asyncio.run(pytexl.Engine().load(path.as_uri()))
|
|
43
|
+
if doc is None:
|
|
44
|
+
print(f"stilo: {args.file}: could not be loaded", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
if args.output:
|
|
47
|
+
try:
|
|
48
|
+
args.output.write_text(doc.rendering, encoding="utf-8")
|
|
49
|
+
except OSError as e:
|
|
50
|
+
print(f"stilo: {args.output}: {e}", file=sys.stderr)
|
|
51
|
+
return 1
|
|
52
|
+
else:
|
|
53
|
+
sys.stdout.write(doc.rendering)
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def serve_arguments(parser):
|
|
58
|
+
parser.add_argument("folder", type=Path, nargs="?", default=Path("."),
|
|
59
|
+
help="folder of the documents (default: the current folder)")
|
|
60
|
+
parser.add_argument("--host", default="127.0.0.1",
|
|
61
|
+
help="address to listen on (default: 127.0.0.1)")
|
|
62
|
+
parser.add_argument("--port", type=int, default=8000)
|
|
63
|
+
parser.add_argument("--web", type=Path, default=WEB_DIST,
|
|
64
|
+
help="built web app (default: the one installed with stilo)")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def serve(args) -> int:
|
|
68
|
+
"""Serves a folder of documents and the Stilo web app over HTTP."""
|
|
69
|
+
if not args.folder.is_dir():
|
|
70
|
+
print(f"stilo: {args.folder}: not a folder", file=sys.stderr)
|
|
71
|
+
return 1
|
|
72
|
+
print(f"Stilo: serving {args.folder.resolve()} at http://{args.host}:{args.port}/")
|
|
73
|
+
uvicorn.run(create_app(args.folder, args.web), host=args.host, port=args.port)
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
COMMANDS = [
|
|
78
|
+
Command("render", "render a Texl document", render_arguments, render),
|
|
79
|
+
Command("serve", "serve a folder of Texl documents with the web app", serve_arguments, serve),
|
|
80
|
+
]
|
stilo/server/__init__.py
ADDED
stilo/server/app.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""HTTP layer: protocol v0 (docs/src/protocol.md) and the web app's files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from fastapi import FastAPI, Query, Request
|
|
8
|
+
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
|
|
9
|
+
from fastapi.staticfiles import StaticFiles
|
|
10
|
+
|
|
11
|
+
from .storage import Storage, StorageError
|
|
12
|
+
|
|
13
|
+
TEXT = "text/plain; charset=utf-8"
|
|
14
|
+
|
|
15
|
+
# Document contents change and the editor fetches imports on every rendering:
|
|
16
|
+
# browsers must not reuse a stored copy without asking the server again.
|
|
17
|
+
NO_CACHE = {"Cache-Control": "no-cache"}
|
|
18
|
+
|
|
19
|
+
NO_BUILD = """<!doctype html><meta charset="utf-8"><title>Stilo</title>
|
|
20
|
+
<p>The web app is not built. Run <code>npm run build</code> in <code>web/</code>
|
|
21
|
+
of the Stilo checkout, or use the Vite dev server (<code>npm run dev</code>).</p>"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
|
|
25
|
+
"""The server app for the documents under `root`. `web_dist` is the built
|
|
26
|
+
web app (`stilo/web` in the CLI); without it, app pages show a notice."""
|
|
27
|
+
storage = Storage(root)
|
|
28
|
+
app = FastAPI(title="Stilo server", version="0.1.0")
|
|
29
|
+
|
|
30
|
+
@app.exception_handler(StorageError)
|
|
31
|
+
async def storage_error(request: Request, error: StorageError):
|
|
32
|
+
return JSONResponse({"error": str(error)}, status_code=error.status)
|
|
33
|
+
|
|
34
|
+
@app.api_route("/_api/files/{path:path}", methods=["GET", "HEAD"])
|
|
35
|
+
async def get_file(path: str):
|
|
36
|
+
content, tag = storage.read(path)
|
|
37
|
+
return Response(content, media_type=TEXT, headers={"ETag": tag, **NO_CACHE})
|
|
38
|
+
|
|
39
|
+
@app.post("/_api/files/{path:path}", status_code=201)
|
|
40
|
+
async def create_file(path: str, request: Request):
|
|
41
|
+
tag = storage.create(path, await request.body())
|
|
42
|
+
return Response(status_code=201,
|
|
43
|
+
headers={"ETag": tag, "Location": f"/_api/files/{path}"})
|
|
44
|
+
|
|
45
|
+
@app.put("/_api/files/{path:path}")
|
|
46
|
+
async def update_file(path: str, request: Request):
|
|
47
|
+
tag = storage.update(path, await request.body(), request.headers.get("if-match"))
|
|
48
|
+
return Response(status_code=200, headers={"ETag": tag})
|
|
49
|
+
|
|
50
|
+
@app.get("/_api/tree/{path:path}")
|
|
51
|
+
async def get_tree(path: str, depth: int | None = Query(None, ge=1)):
|
|
52
|
+
return storage.tree(path, depth)
|
|
53
|
+
|
|
54
|
+
@app.api_route("/_api/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
|
|
55
|
+
async def unknown_api(path: str):
|
|
56
|
+
return JSONResponse({"error": f"unknown endpoint: /_api/{path}"}, status_code=404)
|
|
57
|
+
|
|
58
|
+
dist = Path(web_dist) if web_dist else None
|
|
59
|
+
if dist and (dist / "index.html").is_file():
|
|
60
|
+
# The bundle is built with base "/_app/" (web/vite.config.js).
|
|
61
|
+
app.mount("/_app", StaticFiles(directory=dist), name="app")
|
|
62
|
+
|
|
63
|
+
# Every other path is a document's public URL. Browsers asking for HTML
|
|
64
|
+
# get the web app, which reads the open document from the URL path (and
|
|
65
|
+
# the navigation root from ?root=); any other client (texl.import) gets
|
|
66
|
+
# the file itself.
|
|
67
|
+
@app.api_route("/{path:path}", methods=["GET", "HEAD"], include_in_schema=False)
|
|
68
|
+
async def page(path: str, request: Request):
|
|
69
|
+
vary = {"Vary": "Accept"}
|
|
70
|
+
if "text/html" not in request.headers.get("accept", ""):
|
|
71
|
+
content, tag = storage.read(path)
|
|
72
|
+
return Response(content, media_type=TEXT,
|
|
73
|
+
headers={"ETag": tag, **NO_CACHE, **vary})
|
|
74
|
+
if dist and (dist / "index.html").is_file():
|
|
75
|
+
return FileResponse(dist / "index.html", media_type="text/html", headers=vary)
|
|
76
|
+
return HTMLResponse(NO_BUILD, headers=vary)
|
|
77
|
+
|
|
78
|
+
return app
|
stilo/server/storage.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""File-system storage of Texl documents (protocol v0, see docs/src/protocol.md).
|
|
2
|
+
|
|
3
|
+
Paths are relative to the storage root, with "/" separators. Every public
|
|
4
|
+
method validates its path and raises a StorageError subclass that the HTTP
|
|
5
|
+
layer maps to a status code.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import os
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
DOCUMENT_SUFFIX = ".texl"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class StorageError(Exception):
|
|
19
|
+
status = 500
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BadRequest(StorageError):
|
|
23
|
+
status = 400
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class NotFound(StorageError):
|
|
27
|
+
status = 404
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Conflict(StorageError):
|
|
31
|
+
status = 409
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PreconditionFailed(StorageError):
|
|
35
|
+
status = 412
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def etag(content: bytes) -> str:
|
|
39
|
+
"""Strong ETag of a file's content, quoted as HTTP requires."""
|
|
40
|
+
return '"' + hashlib.sha256(content).hexdigest() + '"'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Storage:
|
|
44
|
+
def __init__(self, root: Path | str):
|
|
45
|
+
self.root = Path(root).resolve()
|
|
46
|
+
if not self.root.is_dir():
|
|
47
|
+
raise ValueError(f"storage root is not a folder: {self.root}")
|
|
48
|
+
|
|
49
|
+
# -- paths ---------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
def resolve(self, path: str) -> Path:
|
|
52
|
+
"""The absolute file-system path of `path`, refusing paths that are
|
|
53
|
+
malformed, hidden, reserved or outside the root."""
|
|
54
|
+
segments = path.strip("/").split("/") if path.strip("/") else []
|
|
55
|
+
for segment in segments:
|
|
56
|
+
if segment in ("", ".", "..") or segment.startswith("."):
|
|
57
|
+
raise BadRequest(f"invalid path: {path!r}")
|
|
58
|
+
if segments and segments[0].startswith("_"):
|
|
59
|
+
raise BadRequest(f"reserved path: {path!r}")
|
|
60
|
+
target = self.root.joinpath(*segments).resolve()
|
|
61
|
+
if not target.is_relative_to(self.root):
|
|
62
|
+
raise BadRequest(f"path outside the root: {path!r}")
|
|
63
|
+
return target
|
|
64
|
+
|
|
65
|
+
def relative(self, target: Path) -> str:
|
|
66
|
+
return target.relative_to(self.root).as_posix() if target != self.root else ""
|
|
67
|
+
|
|
68
|
+
# -- files ---------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
def read(self, path: str) -> tuple[bytes, str]:
|
|
71
|
+
target = self.resolve(path)
|
|
72
|
+
if target.is_dir():
|
|
73
|
+
raise BadRequest(f"not a file: {path!r}")
|
|
74
|
+
if not target.is_file():
|
|
75
|
+
raise NotFound(f"no such file: {path!r}")
|
|
76
|
+
content = target.read_bytes()
|
|
77
|
+
return content, etag(content)
|
|
78
|
+
|
|
79
|
+
def create(self, path: str, content: bytes) -> str:
|
|
80
|
+
target = self._writable(path)
|
|
81
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
try:
|
|
83
|
+
with open(target, "xb") as file:
|
|
84
|
+
file.write(content)
|
|
85
|
+
except FileExistsError:
|
|
86
|
+
raise Conflict(f"already exists: {path!r}") from None
|
|
87
|
+
return etag(content)
|
|
88
|
+
|
|
89
|
+
def update(self, path: str, content: bytes, if_match: str | None = None) -> str:
|
|
90
|
+
target = self._writable(path)
|
|
91
|
+
if not target.is_file():
|
|
92
|
+
raise NotFound(f"no such file: {path!r}")
|
|
93
|
+
if if_match is not None and if_match != etag(target.read_bytes()):
|
|
94
|
+
raise PreconditionFailed(f"changed since it was read: {path!r}")
|
|
95
|
+
# Write a sibling and rename it over the target, so readers never see
|
|
96
|
+
# a half-written document.
|
|
97
|
+
temp = target.with_name(f".{target.name}.tmp")
|
|
98
|
+
temp.write_bytes(content)
|
|
99
|
+
os.replace(temp, target)
|
|
100
|
+
return etag(content)
|
|
101
|
+
|
|
102
|
+
def _writable(self, path: str) -> Path:
|
|
103
|
+
target = self.resolve(path)
|
|
104
|
+
if target.suffix != DOCUMENT_SUFFIX:
|
|
105
|
+
raise BadRequest(f"only {DOCUMENT_SUFFIX} files can be written: {path!r}")
|
|
106
|
+
if target.is_dir():
|
|
107
|
+
raise BadRequest(f"is a folder: {path!r}")
|
|
108
|
+
return target
|
|
109
|
+
|
|
110
|
+
# -- tree ----------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
def tree(self, path: str, depth: int | None = None) -> dict:
|
|
113
|
+
target = self.resolve(path)
|
|
114
|
+
if target.is_file():
|
|
115
|
+
raise BadRequest(f"not a folder: {path!r}")
|
|
116
|
+
if not target.is_dir():
|
|
117
|
+
raise NotFound(f"no such folder: {path!r}")
|
|
118
|
+
return self._folder(target, depth)
|
|
119
|
+
|
|
120
|
+
def _folder(self, folder: Path, depth: int | None) -> dict:
|
|
121
|
+
node = {"name": folder.name if folder != self.root else "",
|
|
122
|
+
"path": self.relative(folder), "type": "folder"}
|
|
123
|
+
if depth is not None and depth <= 0:
|
|
124
|
+
return node
|
|
125
|
+
folders, files = [], []
|
|
126
|
+
for entry in sorted(folder.iterdir(), key=lambda e: e.name):
|
|
127
|
+
if entry.name.startswith(".") or (folder == self.root and entry.name.startswith("_")):
|
|
128
|
+
continue
|
|
129
|
+
if not entry.resolve().is_relative_to(self.root):
|
|
130
|
+
continue
|
|
131
|
+
if entry.is_dir():
|
|
132
|
+
folders.append(self._folder(entry, None if depth is None else depth - 1))
|
|
133
|
+
elif entry.is_file() and entry.suffix == DOCUMENT_SUFFIX:
|
|
134
|
+
stat = entry.stat()
|
|
135
|
+
modified = datetime.fromtimestamp(stat.st_mtime, timezone.utc)
|
|
136
|
+
files.append({"name": entry.name, "path": self.relative(entry), "type": "file",
|
|
137
|
+
"size": stat.st_size,
|
|
138
|
+
"modified": modified.strftime("%Y-%m-%dT%H:%M:%SZ")})
|
|
139
|
+
node["children"] = folders + files
|
|
140
|
+
return node
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
:root{--font:"Inter", system-ui, -apple-system, "Segoe UI", sans-serif;--radius:8px;--bar-height:3rem;--nav-width:16rem;--pane-width:20rem;--transition:.16s ease}:root[data-theme=light]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--bg:#f4f5f7;--surface:#fff;--surface-2:#f8f9fb;--border:#e3e6eb;--text:#1d2330;--text-muted:#687085;--hover:#0f172a0f;--active:#2563eb1a;--accent:#2563eb;--danger:#c2410c;--shadow:0 1px 3px #0000000f, 0 6px 24px #0000000f}:root[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--bg:#14161b;--surface:#1b1e24;--surface-2:#22262e;--border:#2d323c;--text:#e4e7ec;--text-muted:#8b93a3;--hover:#ffffff0f;--active:#60a5fa24;--accent:#60a5fa;--danger:#fb923c;--shadow:0 1px 3px #0000004d, 0 6px 24px #00000040;--texl-paper:#1b1e24;--texl-line:#262a32;--texl-margin-line:#34507f;--texl-line-number:#4a5160;--texl-line-number-active:#8b93a3;--texl-accent:#60a5fa;--texl-selected-bg:#60a5fa12;--texl-selected-ring:#60a5fa66;--texl-edit-bg:#22262e;--texl-comment:#e0a64b;--texl-hover-bg:#ffffff12;--texl-icon-active:#c4c9d4;--texl-menu-bg:#22262e;--texl-menu-border:#2d323c;--texl-menu-text:#e4e7ec;--texl-menu-icon:#8b93a3;--texl-menu-active-bg:#60a5fa24}html,body{height:100%;margin:0}body{background:var(--bg);color:var(--text);font-family:var(--font);-webkit-font-smoothing:antialiased;font-size:14px}
|