v0.166.0
 1import os
 2from collections.abc import Iterator
 3from pathlib import Path
 4
 5from plain.packages import packages_registry
 6from plain.runtime import APP_PATH
 7
 8_APP_ASSETS_DIR = APP_PATH / "assets"
 9
10_SKIP_ASSETS = (".DS_Store", ".gitignore")
11
12# A top-level `src/` in any asset dir holds build inputs — a build tool's entry
13# points and the modules they import. They are consumed by the build, never served.
14_BUILD_INPUT_DIR = "src"
15
16# A top-level `dist/` holds build output that is already content-hashed by the
17# build tool. Plain serves it immutable without re-fingerprinting (skips its md5).
18_BUILD_OUTPUT_DIR = "dist"
19
20
21def is_build_output(url_path: str) -> bool:
22    """Whether a url_path lives under the top-level `dist/` build-output dir."""
23    return url_path.startswith(_BUILD_OUTPUT_DIR + os.sep)
24
25
26class Asset:
27    def __init__(self, *, url_path: str, absolute_path: str):
28        self.url_path = url_path
29        self.absolute_path = absolute_path
30
31    def __str__(self) -> str:
32        return self.url_path
33
34
35def _iter_assets() -> Iterator[Asset]:
36    """
37    Iterate all valid asset files found in the installed
38    packages and the app itself.
39    """
40
41    def __iter_assets_dir(path: str | Path) -> Iterator[tuple[str, str]]:
42        at_root = True
43        for root, dirs, files in os.walk(path):
44            if at_root:
45                # Prune the top-level `src/` build-input dir — only here at the
46                # root (os.walk yields it first), never a nested `foo/src/`.
47                dirs[:] = [d for d in dirs if d != _BUILD_INPUT_DIR]
48                at_root = False
49            for f in files:
50                if f in _SKIP_ASSETS:
51                    continue
52                abs_path = os.path.join(root, f)
53                url_path = os.path.relpath(abs_path, path)
54                yield url_path, abs_path
55
56    for asset_dir in _iter_asset_dirs():
57        for url_path, abs_path in __iter_assets_dir(asset_dir):
58            yield Asset(url_path=url_path, absolute_path=abs_path)
59
60
61def _iter_asset_dirs() -> Iterator[str | Path]:
62    """
63    Iterate all directories containing assets, from installed
64    packages and from app/assets.
65    """
66    # Iterate the installed package assets, in order
67    for pkg in packages_registry.get_package_configs():
68        asset_dir = os.path.join(pkg.path, "assets")
69        if os.path.exists(asset_dir):
70            yield asset_dir
71
72    # The app/assets take priority over everything
73    if _APP_ASSETS_DIR.exists():
74        yield _APP_ASSETS_DIR