1import gzip
2import os
3import shutil
4from collections.abc import Iterator
5from pathlib import Path
6
7from plain.runtime import PLAIN_TEMP_PATH
8
9from .finders import Asset, _iter_assets, is_build_output
10from .manifest import AssetsManifest, compute_fingerprint
11
12_SKIP_COMPRESS_EXTENSIONS = (
13 # Images
14 ".jpg",
15 ".jpeg",
16 ".png",
17 ".gif",
18 ".webp",
19 # Compressed files
20 ".zip",
21 ".gz",
22 ".tgz",
23 ".bz2",
24 ".tbz",
25 ".xz",
26 ".br",
27 # Fonts
28 ".woff",
29 ".woff2",
30 # Video
31 ".3gp",
32 ".3gpp",
33 ".asf",
34 ".avi",
35 ".m4v",
36 ".mov",
37 ".mp4",
38 ".mpeg",
39 ".mpg",
40 ".webm",
41 ".wmv",
42)
43
44
45def get_compiled_path() -> Path:
46 """
47 Get the path at runtime to the compiled assets directory.
48
49 There's no reason currently for this to be a user-facing setting.
50 """
51 return PLAIN_TEMP_PATH / "assets" / "compiled"
52
53
54def compile_assets(
55 *, target_dir: str, keep_original: bool, fingerprint: bool, compress: bool
56) -> Iterator[tuple[str, str, list[str]]]:
57 """
58 Compile all assets to the target directory and save a JSON manifest.
59
60 Manifest format:
61 - original path → fingerprinted path (if fingerprinting enabled)
62 - fingerprinted path → None (terminal, no redirect)
63 - original path → None (if no fingerprinting, terminal)
64 """
65 manifest = AssetsManifest()
66
67 for asset in _iter_assets():
68 url_path = asset.url_path
69
70 # Output under dist/ is already content-hashed by the build tool: copy
71 # it as-is (no md5 rename) and serve it immutable at its own name.
72 build_output = is_build_output(url_path)
73
74 fingerprinted_path, compiled_paths = compile_asset(
75 asset=asset,
76 target_dir=target_dir,
77 keep_original=keep_original or build_output,
78 fingerprint=fingerprint and not build_output,
79 compress=compress,
80 )
81
82 if build_output:
83 manifest.add_already_hashed(url_path)
84 resolved_path = url_path
85 elif fingerprinted_path:
86 manifest.add_fingerprinted(url_path, fingerprinted_path)
87 resolved_path = fingerprinted_path
88 else:
89 manifest.add_non_fingerprinted(url_path)
90 resolved_path = url_path
91
92 yield url_path, resolved_path, compiled_paths
93
94 manifest.save()
95
96
97def compile_asset(
98 *,
99 asset: Asset,
100 target_dir: str,
101 keep_original: bool,
102 fingerprint: bool,
103 compress: bool,
104) -> tuple[str | None, list[str]]:
105 """
106 Compile an asset to multiple output paths.
107
108 Returns the fingerprinted URL path (or None) and the list of compiled file paths.
109 """
110 compiled_paths: list[str] = []
111 fingerprinted_url_path: str | None = None
112
113 # The expected destination for the original asset
114 target_path = os.path.join(target_dir, asset.url_path)
115
116 # Make sure all the expected directories exist
117 os.makedirs(os.path.dirname(target_path), exist_ok=True)
118
119 base, extension = os.path.splitext(asset.url_path)
120
121 # Copy the original asset if requested
122 if keep_original:
123 shutil.copy(asset.absolute_path, target_path)
124 compiled_paths.append(target_path)
125
126 # Create fingerprinted version if requested
127 if fingerprint:
128 fingerprint_hash = compute_fingerprint(asset.absolute_path)
129
130 fingerprinted_basename = f"{base}.{fingerprint_hash}{extension}"
131 fingerprinted_path = os.path.join(target_dir, fingerprinted_basename)
132 shutil.copy(asset.absolute_path, fingerprinted_path)
133 compiled_paths.append(fingerprinted_path)
134
135 fingerprinted_url_path = str(os.path.relpath(fingerprinted_path, target_dir))
136
137 if compress and extension.lower() not in _SKIP_COMPRESS_EXTENSIONS:
138 for path in compiled_paths.copy():
139 gzip_path = f"{path}.gz"
140 with gzip.GzipFile(gzip_path, "wb", mtime=0) as f, open(path, "rb") as f2:
141 f.write(f2.read())
142 compiled_paths.append(gzip_path)
143
144 return fingerprinted_url_path, compiled_paths