stilo-cli 0.2.0__tar.gz → 0.3.0__tar.gz

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.
Files changed (63) hide show
  1. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/PKG-INFO +2 -2
  2. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/pyproject.toml +9 -3
  3. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/cli/commands.py +35 -1
  4. stilo_cli-0.3.0/src/stilo/cli/project.py +83 -0
  5. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/server/app.py +22 -3
  6. stilo_cli-0.3.0/src/stilo/server/home.py +72 -0
  7. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/server/storage.py +34 -7
  8. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  9. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  10. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  11. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  12. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  13. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  14. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  15. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  16. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  17. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  18. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  19. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  20. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  21. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  22. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  23. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  24. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  25. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  26. stilo_cli-0.3.0/src/stilo/web/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  27. stilo_cli-0.3.0/src/stilo/web/assets/index-BT3YAPgN.js +2349 -0
  28. stilo_cli-0.3.0/src/stilo/web/assets/texl_wasm_bg-DXo4-iTL.wasm +0 -0
  29. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/index.html +1 -1
  30. stilo_cli-0.3.0/texl-lib/dataframe.texl +113 -0
  31. stilo_cli-0.3.0/texl-lib/index.texl +16 -0
  32. stilo_cli-0.2.0/src/stilo/web/assets/index-BUxoyfxd.js +0 -1712
  33. stilo_cli-0.2.0/src/stilo/web/assets/texl_wasm_bg-2_KrrXbk.wasm +0 -0
  34. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/.gitignore +0 -0
  35. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/LICENSE +0 -0
  36. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/README.md +0 -0
  37. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/__init__.py +0 -0
  38. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/__main__.py +0 -0
  39. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/cli/__init__.py +0 -0
  40. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/cli/errors.py +0 -0
  41. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/server/__init__.py +0 -0
  42. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/index-kR4PIGIs.css +0 -0
  43. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-cyrillic-ext-opsz-italic-5yUt4G_9.woff2 +0 -0
  44. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-cyrillic-ext-opsz-normal-C5tfwALZ.woff2 +0 -0
  45. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-cyrillic-opsz-italic-Bj0ndbyp.woff2 +0 -0
  46. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-cyrillic-opsz-normal-DgmypKXX.woff2 +0 -0
  47. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-greek-ext-opsz-italic-DFpO5j-Z.woff2 +0 -0
  48. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-greek-ext-opsz-normal-DGm64vGR.woff2 +0 -0
  49. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-greek-opsz-italic-CHERNRFq.woff2 +0 -0
  50. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-greek-opsz-normal-DFglUmAd.woff2 +0 -0
  51. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-latin-ext-opsz-italic-4y8iAqqs.woff2 +0 -0
  52. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-latin-ext-opsz-normal-STiTPs0F.woff2 +0 -0
  53. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-latin-opsz-italic-CJ93D38p.woff2 +0 -0
  54. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-latin-opsz-normal-BHZsWIlc.woff2 +0 -0
  55. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-vietnamese-opsz-italic-BdcrZMcO.woff2 +0 -0
  56. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/literata-vietnamese-opsz-normal-Gqw5JQlq.woff2 +0 -0
  57. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/source-sans-3-cyrillic-ext-wght-normal-c-5QAGAI.woff2 +0 -0
  58. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/source-sans-3-cyrillic-wght-normal-BMDVbyM7.woff2 +0 -0
  59. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/source-sans-3-greek-ext-wght-normal-BXZfsJY4.woff2 +0 -0
  60. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/source-sans-3-greek-wght-normal-Cc-u-6OI.woff2 +0 -0
  61. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/source-sans-3-latin-ext-wght-normal-C8iNium2.woff2 +0 -0
  62. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/source-sans-3-latin-wght-normal-Bo_j9asI.woff2 +0 -0
  63. {stilo_cli-0.2.0 → stilo_cli-0.3.0}/src/stilo/web/assets/source-sans-3-vietnamese-wght-normal-BDs68eHQ.woff2 +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stilo-cli
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Stilo: edit and render a folder of linked Texl documents
5
5
  Project-URL: Documentation, https://www.onlabs.org/manual/
6
6
  Project-URL: Source, https://github.com/onlabsorg/stilo
@@ -8,7 +8,7 @@ License-Expression: MIT
8
8
  License-File: LICENSE
9
9
  Requires-Python: >=3.11
10
10
  Requires-Dist: fastapi>=0.115
11
- Requires-Dist: pytexl>=0.6.0
11
+ Requires-Dist: pytexl>=0.8.0
12
12
  Requires-Dist: uvicorn>=0.30
13
13
  Description-Content-Type: text/markdown
14
14
 
@@ -6,6 +6,8 @@
6
6
  # src/stilo/web the built web app, written by `npm run build` in web/
7
7
  # (git-ignored; built into the package when present —
8
8
  # the release workflow checks that the wheel has it)
9
+ # texl-lib/ the Texl library `stilo init` copies into projects,
10
+ # shipped in the wheel as stilo/texl-lib
9
11
  #
10
12
  # Build:
11
13
  #
@@ -14,7 +16,7 @@
14
16
 
15
17
  [project]
16
18
  name = "stilo-cli"
17
- version = "0.2.0"
19
+ version = "0.3.0"
18
20
  description = "Stilo: edit and render a folder of linked Texl documents"
19
21
  readme = "README.md"
20
22
  license = "MIT"
@@ -22,7 +24,7 @@ license-files = ["LICENSE"]
22
24
  requires-python = ">=3.11"
23
25
  dependencies = [
24
26
  "fastapi>=0.115",
25
- "pytexl>=0.6.0",
27
+ "pytexl>=0.8.0",
26
28
  "uvicorn>=0.30",
27
29
  ]
28
30
 
@@ -44,11 +46,15 @@ requires = ["hatchling"]
44
46
  build-backend = "hatchling.build"
45
47
 
46
48
  [tool.hatch.build.targets.sdist]
47
- only-include = ["src/stilo", "README.md", "LICENSE"]
49
+ only-include = ["src/stilo", "texl-lib", "README.md", "LICENSE"]
48
50
 
49
51
  [tool.hatch.build.targets.wheel]
50
52
  packages = ["src/stilo"]
51
53
 
54
+ # In a checkout the CLI reads texl-lib/ where it is (stilo/cli/project.py).
55
+ [tool.hatch.build.targets.wheel.force-include]
56
+ "texl-lib" = "stilo/texl-lib"
57
+
52
58
  # src/stilo/web is git-ignored: include it anyway when it is there. Not a
53
59
  # forced include, so that editable installs (`uv run`) work without it.
54
60
  [tool.hatch.build]
@@ -6,6 +6,7 @@ the order `stilo --help` shows them; a plugin system can later add its own.
6
6
  """
7
7
 
8
8
  import asyncio
9
+ import shutil
9
10
  import sys
10
11
  from dataclasses import dataclass
11
12
  from pathlib import Path
@@ -17,6 +18,7 @@ import uvicorn
17
18
  from stilo.server import create_app
18
19
 
19
20
  from .errors import count_returned, find_errors, format_report, numbered_text
21
+ from .project import LIB, LIBRARY_NAME, MANIFEST, TEXL_LIB, create_engine, manifest
20
22
 
21
23
  # The built web app, `stilo/web`: written there by `npm run build` in a
22
24
  # checkout, shipped there in the package
@@ -46,7 +48,7 @@ def render(args) -> int:
46
48
  """Renders a document to standard output or a file, like `texl`."""
47
49
  path = args.file.resolve()
48
50
  try:
49
- doc = asyncio.run(pytexl.Engine().load(path.as_uri()))
51
+ doc = asyncio.run(create_engine().load(path.as_uri()))
50
52
  except pytexl.LoadError as e:
51
53
  print(f"stilo: {args.file}: could not be loaded: {e.reason}", file=sys.stderr)
52
54
  return 1
@@ -96,7 +98,39 @@ def serve(args) -> int:
96
98
  return 0
97
99
 
98
100
 
101
+ def init_arguments(parser):
102
+ parser.add_argument("folder", type=Path, nargs="?", default=Path("."),
103
+ help="folder of the project, created if missing (default: the current folder)")
104
+ parser.add_argument("--name", help="project name (default: the folder's name)")
105
+
106
+
107
+ def init(args) -> int:
108
+ """Makes a folder a Stilo project: writes project.texl, creates lib/ and
109
+ copies the bundled library into lib/stilo/, never over an existing one."""
110
+ folder = args.folder.resolve()
111
+ if (folder / MANIFEST).exists():
112
+ print(f"stilo: {args.folder}: already a project ({MANIFEST} exists)", file=sys.stderr)
113
+ return 1
114
+ library = folder / LIB / LIBRARY_NAME
115
+ try:
116
+ folder.mkdir(parents=True, exist_ok=True)
117
+ with open(folder / MANIFEST, "x", encoding="utf-8") as file:
118
+ file.write(manifest(args.name or folder.name))
119
+ (folder / LIB).mkdir(exist_ok=True)
120
+ kept = library.exists()
121
+ if not kept:
122
+ shutil.copytree(TEXL_LIB, library)
123
+ except OSError as e:
124
+ print(f"stilo: {args.folder}: {e}", file=sys.stderr)
125
+ return 1
126
+ print(f"Stilo: {folder} is a project: {MANIFEST}, {LIB}/")
127
+ if kept:
128
+ print(f"Stilo: {LIB}/{LIBRARY_NAME}/ already exists: left as it is")
129
+ return 0
130
+
131
+
99
132
  COMMANDS = [
133
+ Command("init", "make a folder a Stilo project, with the Stilo library", init_arguments, init),
100
134
  Command("render", "render a Texl document", render_arguments, render),
101
135
  Command("serve", "serve a folder of Texl documents with the web app", serve_arguments, serve),
102
136
  ]
@@ -0,0 +1,83 @@
1
+ """Projects in the CLI (DECISIONS.md S10): the engine that resolves `~` in
2
+ file paths, and what `stilo init` writes.
3
+
4
+ The rule itself is in `stilo.server.home`, shared with the server.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from importlib.metadata import PackageNotFoundError, version
11
+ from pathlib import Path
12
+
13
+ import pytexl
14
+ from pytexl.loaders import file_path, load_file
15
+
16
+ from stilo.server.home import MANIFEST, expand_home, has_home
17
+
18
+ # The Texl library Stilo bundles, copied into a project's lib/stilo/ by
19
+ # `stilo init`. Its source is `texl-lib/` at the root of the checkout; the
20
+ # wheel ships it as `stilo/texl-lib` (pyproject.toml).
21
+ PACKAGE = Path(__file__).resolve().parents[1]
22
+ _INSTALLED_LIB = PACKAGE / "texl-lib"
23
+ TEXL_LIB = _INSTALLED_LIB if _INSTALLED_LIB.is_dir() else PACKAGE.parents[1] / "texl-lib"
24
+
25
+ LIB = "lib"
26
+ LIBRARY_NAME = "stilo"
27
+
28
+
29
+ def stilo_version() -> str:
30
+ """The version of the installed package (pyproject.toml), the one place it is set."""
31
+ try:
32
+ return version("stilo-cli")
33
+ except PackageNotFoundError: # a checkout run without installing
34
+ return "0.0.0"
35
+
36
+
37
+ def top_of(folder: Path) -> Path:
38
+ """The highest folder the search for a home may reach from `folder`: the
39
+ user's home directory, or the file-system root for a folder outside it."""
40
+ user_home = Path.home().resolve()
41
+ return user_home if folder.is_relative_to(user_home) else Path(folder.anchor)
42
+
43
+
44
+ def resolve_file(uri: str) -> Path:
45
+ """The file a `file://` URL or an absolute path stands for, `~` resolved."""
46
+ path = file_path(uri)
47
+ if not has_home(path):
48
+ return path
49
+ return expand_home(Path(path.anchor), path.parts[1:], top_of)
50
+
51
+
52
+ async def load_project_file(uri: str) -> str | tuple[str, str]:
53
+ """pytexl's file loader, with `~` resolved. A path with `~` gives the
54
+ real file as the document's final URL (Texl 0.8): its identity, so
55
+ imports of one library by different paths share it, and a cycle
56
+ through `~` ends."""
57
+ if not has_home(file_path(uri)):
58
+ return await load_file(uri)
59
+ final_url = resolve_file(uri).as_uri()
60
+ return final_url, await load_file(final_url)
61
+
62
+
63
+ def create_engine() -> pytexl.Engine:
64
+ """The engine of every CLI command that renders."""
65
+ engine = pytexl.Engine()
66
+ engine.add_loader("file", load_project_file)
67
+ engine.set_default_loader(load_project_file)
68
+ return engine
69
+
70
+
71
+ def manifest(name: str) -> str:
72
+ """The text of a new `project.texl`. Swan strings have no escapes, so
73
+ the name loses any `"` and `%>`."""
74
+ name = re.sub(r'"|%>', "", name).strip() or "project"
75
+ return f"""# {name}
76
+
77
+ This folder is a Stilo project. This file marks its home folder: in an
78
+ import, `~` stands for it, as in `~/lib/stilo/index.texl`. The values below
79
+ configure the project.
80
+
81
+ <% project_name = "{name}" %>
82
+ <% stilo_version = "{stilo_version()}" %>
83
+ """
@@ -4,11 +4,13 @@ from __future__ import annotations
4
4
 
5
5
  import mimetypes
6
6
  from pathlib import Path
7
+ from urllib.parse import quote
7
8
 
8
9
  from fastapi import FastAPI, Query, Request
9
- from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
10
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
10
11
  from fastapi.staticfiles import StaticFiles
11
12
 
13
+ from .home import has_home
12
14
  from .storage import BadRequest, Storage, StorageError
13
15
 
14
16
  TEXT = "text/plain; charset=utf-8"
@@ -44,14 +46,29 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
44
46
  """The server app for the documents under `root`. `web_dist` is the built
45
47
  web app (`stilo/web` in the CLI); without it, app pages show a notice."""
46
48
  storage = Storage(root)
47
- app = FastAPI(title="Stilo server", version="0.2.0")
49
+ app = FastAPI(title="Stilo server", version="0.3.0")
48
50
 
49
51
  @app.exception_handler(StorageError)
50
52
  async def storage_error(request: Request, error: StorageError):
51
53
  return JSONResponse({"error": str(error)}, status_code=error.status)
52
54
 
55
+ def home_redirect(prefix: str, path: str, request: Request) -> Response | None:
56
+ """A read whose path has `~` segments is redirected to the real path
57
+ (docs/protocol.md): the document is the one at the URL a redirect
58
+ leads to, its identity for Texl (final URLs, Texl 0.8), so imports of
59
+ one library by different paths share it, and a cycle through `~`
60
+ ends. Temporary, since the home depends on manifests that can change."""
61
+ if not has_home(path):
62
+ return None
63
+ url = prefix + quote(storage.expand_home(path), safe="/")
64
+ if request.url.query:
65
+ url += "?" + request.url.query
66
+ return RedirectResponse(url, status_code=307, headers=NO_CACHE)
67
+
53
68
  @app.api_route("/_api/files/{path:path}", methods=["GET", "HEAD"])
54
- async def get_file(path: str):
69
+ async def get_file(path: str, request: Request):
70
+ if redirect := home_redirect("/_api/files/", path, request):
71
+ return redirect
55
72
  content, tag = storage.read(path)
56
73
  return Response(content, media_type=TEXT, headers={"ETag": tag, **NO_CACHE})
57
74
 
@@ -109,6 +126,8 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
109
126
  # root from ?root=); any other client (texl.import) gets the file itself.
110
127
  @app.api_route("/{path:path}", methods=["GET", "HEAD"], include_in_schema=False)
111
128
  async def page(path: str, request: Request):
129
+ if redirect := home_redirect("/", path, request):
130
+ return redirect
112
131
  vary = {"Vary": "Accept"}
113
132
  if storage.is_other_file(path):
114
133
  return other_file_response(path, *storage.read(path))
@@ -0,0 +1,72 @@
1
+ """The project home and the `~` segment of import paths (DECISIONS.md S10).
2
+
3
+ A project is a folder holding a manifest, `project.texl`. The home of a
4
+ folder is the nearest folder at or above it that holds one, or, without
5
+ one, the top: the highest folder the caller lets the search reach (the
6
+ served folder for the server; the user's home directory, or the file-system
7
+ root, for the CLI).
8
+
9
+ In a path, a segment `~` stands for the home of the folder before it. Texl
10
+ gives `~` no meaning, so an import of `~/lib/x.texl` from `/p/docs/a.texl`
11
+ asks for `/p/docs/~/lib/x.texl`; `expand_home` turns that into the real
12
+ path, one `~` at a time from the left. Several `~` occur naturally: a
13
+ library loaded as `.../~/lib/a/a.texl` that imports `~/lib/b/b.texl` asks
14
+ for `.../~/lib/a/~/lib/b/b.texl`, whose second `~` is the home of `lib/a`
15
+ (the library's own, if it has a manifest, else the project's).
16
+
17
+ Hosts give Texl the real path as the document's final URL (Texl 0.8): the
18
+ server redirects, the CLI's loader returns it. So a library is the document
19
+ at its real path, and a library importing itself through `~` asks again for
20
+ that path, an import cycle Texl ends. A path with more than `MAX_HOMES` `~`
21
+ segments is still refused, a safeguard for clients that keep the `~` URL
22
+ (`a/~/lib/x/~/lib/x/...` would grow at every turn).
23
+
24
+ Used by the server (`storage.py`) and by the CLI's file loader, so that
25
+ both resolve the same way. It reads the file system only to look for
26
+ manifests; validating the result is the caller's job.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from pathlib import Path, PurePath
32
+ from typing import Callable, Iterable
33
+
34
+ MANIFEST = "project.texl"
35
+ HOME = "~"
36
+ MAX_HOMES = 16
37
+
38
+
39
+ class HomeCycle(ValueError):
40
+ """A path with more `~` segments than any real chain of imports needs."""
41
+
42
+
43
+ def home_of(folder: Path, top: Path) -> Path:
44
+ """The nearest folder at or above `folder`, up to `top`, that holds a
45
+ manifest; `top` if none does. `folder` is expected inside `top`."""
46
+ for candidate in (folder, *folder.parents):
47
+ if (candidate / MANIFEST).is_file():
48
+ return candidate
49
+ if candidate == top:
50
+ break
51
+ return top
52
+
53
+
54
+ def expand_home(base: Path, segments: Iterable[str],
55
+ top_of: Callable[[Path], Path]) -> Path:
56
+ """The path of `segments` under `base`, with every `~` segment replaced,
57
+ from the left, by the home of the folder built so far. `top_of(folder)`
58
+ gives the highest folder the search for that folder's home may reach.
59
+ Raises `HomeCycle` beyond `MAX_HOMES` `~` segments."""
60
+ segments = list(segments)
61
+ if segments.count(HOME) > MAX_HOMES:
62
+ raise HomeCycle(f"more than {MAX_HOMES} {HOME} segments: an import cycle through {HOME}?")
63
+ current = base
64
+ for segment in segments:
65
+ current = home_of(current, top_of(current)) if segment == HOME else current / segment
66
+ return current
67
+
68
+
69
+ def has_home(path: str | PurePath) -> bool:
70
+ """Whether a path (a "/"-separated string or a path object) has a `~` segment."""
71
+ parts = path.parts if isinstance(path, PurePath) else str(path).split("/")
72
+ return HOME in parts
@@ -13,6 +13,8 @@ import shutil
13
13
  from datetime import datetime, timezone
14
14
  from pathlib import Path
15
15
 
16
+ from .home import HOME, HomeCycle, expand_home, has_home
17
+
16
18
  DOCUMENT_SUFFIX = ".texl"
17
19
  TRASH = ".trash"
18
20
 
@@ -50,13 +52,32 @@ class Storage:
50
52
 
51
53
  # -- paths ---------------------------------------------------------------
52
54
 
53
- def resolve(self, path: str) -> Path:
54
- """The absolute file-system path of `path`, refusing paths that are
55
- malformed, hidden, reserved or outside the root."""
55
+ @staticmethod
56
+ def _segments(path: str) -> list[str]:
56
57
  segments = path.strip("/").split("/") if path.strip("/") else []
57
58
  for segment in segments:
58
59
  if segment in ("", ".", "..") or segment.startswith("."):
59
60
  raise BadRequest(f"invalid path: {path!r}")
61
+ return segments
62
+
63
+ def expand_home(self, path: str) -> str:
64
+ """`path` with its `~` segments replaced by the project home they
65
+ stand for (home.py); the search never leaves the root. Only reads
66
+ expand `~`: as a name it is refused."""
67
+ if not has_home(path):
68
+ return path
69
+ try:
70
+ target = expand_home(self.root, self._segments(path), lambda folder: self.root)
71
+ except HomeCycle as e:
72
+ raise BadRequest(f"{e}: {path!r}") from None
73
+ return target.relative_to(self.root).as_posix() if target != self.root else ""
74
+
75
+ def resolve(self, path: str) -> Path:
76
+ """The absolute file-system path of `path`, refusing paths that are
77
+ malformed, hidden, reserved or outside the root."""
78
+ segments = self._segments(path)
79
+ if HOME in segments:
80
+ raise BadRequest(f"{HOME} stands for the project home and cannot be a name: {path!r}")
60
81
  if segments and segments[0].startswith("_"):
61
82
  raise BadRequest(f"reserved path: {path!r}")
62
83
  target = self.root.joinpath(*segments).resolve()
@@ -70,7 +91,7 @@ class Storage:
70
91
  # -- files ---------------------------------------------------------------
71
92
 
72
93
  def read(self, path: str) -> tuple[bytes, str]:
73
- target = self.resolve(path)
94
+ target = self.resolve(self.expand_home(path))
74
95
  if target.is_dir():
75
96
  raise BadRequest(f"not a file: {path!r}")
76
97
  if not target.is_file():
@@ -82,7 +103,7 @@ class Storage:
82
103
  """Whether `path` is an existing file that is not a Texl document. A
83
104
  path the protocol refuses is not one."""
84
105
  try:
85
- target = self.resolve(path)
106
+ target = self.resolve(self.expand_home(path))
86
107
  except BadRequest:
87
108
  return False
88
109
  return target.is_file() and target.suffix != DOCUMENT_SUFFIX
@@ -191,7 +212,7 @@ class Storage:
191
212
  """Add the documents under `folder`, and its folders with the deepest
192
213
  first. What the tree does not list as a document or a folder is left."""
193
214
  for entry in folder.iterdir():
194
- if entry.name.startswith("."):
215
+ if self._hidden(entry.name):
195
216
  continue
196
217
  if entry.is_dir():
197
218
  if not entry.is_symlink():
@@ -235,6 +256,12 @@ class Storage:
235
256
  raise Conflict(f"a file is in the way: {path!r}") from None
236
257
 
237
258
 
259
+ @staticmethod
260
+ def _hidden(name: str) -> bool:
261
+ """Entries the protocol never shows: hidden ones, and `~`, which in a
262
+ path stands for the project home."""
263
+ return name.startswith(".") or name == HOME
264
+
238
265
  def tree(self, path: str, depth: int | None = None) -> dict:
239
266
  target = self.resolve(path)
240
267
  if target.is_file():
@@ -250,7 +277,7 @@ class Storage:
250
277
  return node
251
278
  folders, files = [], []
252
279
  for entry in sorted(folder.iterdir(), key=lambda e: e.name):
253
- if entry.name.startswith(".") or (folder == self.root and entry.name.startswith("_")):
280
+ if self._hidden(entry.name) or (folder == self.root and entry.name.startswith("_")):
254
281
  continue
255
282
  if not entry.resolve().is_relative_to(self.root):
256
283
  continue