| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import errno |
| 4 |
import os |
| 5 |
import re |
| 6 |
import textwrap |
| 7 |
from collections.abc import Generator |
| 8 |
from collections.abc import Iterator |
| 9 |
from concurrent.futures import ThreadPoolExecutor |
| 10 |
from concurrent.futures import as_completed |
| 11 |
from typing import Any |
| 12 |
from typing import Union |
| 13 |
|
| 14 |
from django.conf import settings |
| 15 |
from django.contrib.staticfiles.storage import ManifestStaticFilesStorage |
| 16 |
from django.contrib.staticfiles.storage import StaticFilesStorage |
| 17 |
|
| 18 |
from whitenoise.compress import Compressor |
| 19 |
|
| 20 |
_PostProcessT = Iterator[Union[tuple[str, str, bool], tuple[str, None, RuntimeError]]] |
| 21 |
|
| 22 |
|
| 23 |
class CompressedStaticFilesStorage(StaticFilesStorage): |
| 24 |
""" |
| 25 |
StaticFilesStorage subclass that compresses output files. |
| 26 |
""" |
| 27 |
|
| 28 |
def post_process( |
| 29 |
self, paths: dict[str, Any], dry_run: bool = False, **options: Any |
| 30 |
) -> _PostProcessT: |
| 31 |
if dry_run: |
| 32 |
return |
| 33 |
|
| 34 |
extensions = getattr(settings, "WHITENOISE_SKIP_COMPRESS_EXTENSIONS", None) |
| 35 |
self.compressor = self.create_compressor(extensions=extensions, quiet=True) |
| 36 |
|
| 37 |
def _compress_path(path: str) -> Generator[tuple[str, str, bool]]: |
| 38 |
compressed: list[tuple[str, str, bool]] = [] |
| 39 |
full_path = self.path(path) |
| 40 |
prefix_len = len(full_path) - len(path) |
| 41 |
for compressed_path in self.compressor.compress(full_path): |
| 42 |
compressed_name = compressed_path[prefix_len:] |
| 43 |
compressed.append((path, compressed_name, True)) |
| 44 |
return compressed |
| 45 |
|
| 46 |
with ThreadPoolExecutor() as executor: |
| 47 |
futures = ( |
| 48 |
executor.submit(_compress_path, path) |
| 49 |
for path in paths |
| 50 |
if self.compressor.should_compress(path) |
| 51 |
) |
| 52 |
for future in as_completed(futures): |
| 53 |
yield from future.result() |
| 54 |
|
| 55 |
def create_compressor(self, **kwargs: Any) -> Compressor: |
| 56 |
return Compressor(**kwargs) |
| 57 |
|
| 58 |
|
| 59 |
class MissingFileError(ValueError): |
| 60 |
pass |
| 61 |
|
| 62 |
|
| 63 |
class CompressedManifestStaticFilesStorage(ManifestStaticFilesStorage): |
| 64 |
""" |
| 65 |
Extends ManifestStaticFilesStorage instance to create compressed versions |
| 66 |
of its output files and, optionally, to delete the non-hashed files (i.e. |
| 67 |
those without the hash in their name) |
| 68 |
""" |
| 69 |
|
| 70 |
_new_files = None |
| 71 |
|
| 72 |
def __init__(self, *args, **kwargs): |
| 73 |
manifest_strict = getattr(settings, "WHITENOISE_MANIFEST_STRICT", None) |
| 74 |
if manifest_strict is not None: |
| 75 |
self.manifest_strict = manifest_strict |
| 76 |
super().__init__(*args, **kwargs) |
| 77 |
|
| 78 |
def post_process(self, *args, **kwargs): |
| 79 |
files = super().post_process(*args, **kwargs) |
| 80 |
|
| 81 |
if not kwargs.get("dry_run"): |
| 82 |
files = self.post_process_with_compression(files) |
| 83 |
|
| 84 |
# Make exception messages helpful |
| 85 |
for name, hashed_name, processed in files: |
| 86 |
if isinstance(processed, Exception): |
| 87 |
processed = self.make_helpful_exception(processed, name) |
| 88 |
yield name, hashed_name, processed |
| 89 |
|
| 90 |
def post_process_with_compression(self, files): |
| 91 |
# Files may get hashed multiple times, we want to keep track of all the |
| 92 |
# intermediate files generated during the process and which of these |
| 93 |
# are the final names used for each file. As not every intermediate |
| 94 |
# file is yielded we have to hook in to the `hashed_name` method to |
| 95 |
# keep track of them all. |
| 96 |
hashed_names = {} |
| 97 |
new_files = set() |
| 98 |
self.start_tracking_new_files(new_files) |
| 99 |
for name, hashed_name, processed in files: |
| 100 |
if hashed_name and not isinstance(processed, Exception): |
| 101 |
hashed_names[self.clean_name(name)] = hashed_name |
| 102 |
yield name, hashed_name, processed |
| 103 |
self.stop_tracking_new_files() |
| 104 |
original_files = set(hashed_names.keys()) |
| 105 |
hashed_files = set(hashed_names.values()) |
| 106 |
if self.keep_only_hashed_files: |
| 107 |
files_to_delete = (original_files | new_files) - hashed_files |
| 108 |
files_to_compress = hashed_files |
| 109 |
else: |
| 110 |
files_to_delete = set() |
| 111 |
files_to_compress = original_files | hashed_files |
| 112 |
self.delete_files(files_to_delete) |
| 113 |
for name, compressed_name in self.compress_files(files_to_compress): |
| 114 |
yield name, compressed_name, True |
| 115 |
|
| 116 |
def hashed_name(self, *args, **kwargs): |
| 117 |
name = super().hashed_name(*args, **kwargs) |
| 118 |
if self._new_files is not None: |
| 119 |
self._new_files.add(self.clean_name(name)) |
| 120 |
return name |
| 121 |
|
| 122 |
def start_tracking_new_files(self, new_files): |
| 123 |
self._new_files = new_files |
| 124 |
|
| 125 |
def stop_tracking_new_files(self): |
| 126 |
self._new_files = None |
| 127 |
|
| 128 |
@property |
| 129 |
def keep_only_hashed_files(self): |
| 130 |
return getattr(settings, "WHITENOISE_KEEP_ONLY_HASHED_FILES", False) |
| 131 |
|
| 132 |
def delete_files(self, files_to_delete): |
| 133 |
for name in files_to_delete: |
| 134 |
try: |
| 135 |
os.unlink(self.path(name)) |
| 136 |
except OSError as e: |
| 137 |
if e.errno != errno.ENOENT: |
| 138 |
raise |
| 139 |
|
| 140 |
def create_compressor(self, **kwargs): |
| 141 |
return Compressor(**kwargs) |
| 142 |
|
| 143 |
def compress_files(self, paths): |
| 144 |
extensions = getattr(settings, "WHITENOISE_SKIP_COMPRESS_EXTENSIONS", None) |
| 145 |
self.compressor = self.create_compressor(extensions=extensions, quiet=True) |
| 146 |
|
| 147 |
def _compress_path(path: str) -> list[tuple[str, str]]: |
| 148 |
compressed: list[tuple[str, str]] = [] |
| 149 |
full_path = self.path(path) |
| 150 |
prefix_len = len(full_path) - len(path) |
| 151 |
for compressed_path in self.compressor.compress(full_path): |
| 152 |
compressed_name = compressed_path[prefix_len:] |
| 153 |
compressed.append((path, compressed_name)) |
| 154 |
return compressed |
| 155 |
|
| 156 |
with ThreadPoolExecutor() as executor: |
| 157 |
futures = ( |
| 158 |
executor.submit(_compress_path, path) |
| 159 |
for path in paths |
| 160 |
if self.compressor.should_compress(path) |
| 161 |
) |
| 162 |
for future in as_completed(futures): |
| 163 |
yield from future.result() |
| 164 |
|
| 165 |
def make_helpful_exception(self, exception, name): |
| 166 |
""" |
| 167 |
If a CSS file contains references to images, fonts etc that can't be found |
| 168 |
then Django's `post_process` blows up with a not particularly helpful |
| 169 |
ValueError that leads people to think WhiteNoise is broken. |
| 170 |
|
| 171 |
Here we attempt to intercept such errors and reformat them to be more |
| 172 |
helpful in revealing the source of the problem. |
| 173 |
""" |
| 174 |
if isinstance(exception, ValueError): |
| 175 |
message = exception.args[0] if len(exception.args) else "" |
| 176 |
# Stringly typed exceptions. Yay! |
| 177 |
match = self._error_msg_re.search(message) |
| 178 |
if match: |
| 179 |
extension = os.path.splitext(name)[1].lstrip(".").upper() |
| 180 |
message = self._error_msg.format( |
| 181 |
orig_message=message, |
| 182 |
filename=name, |
| 183 |
missing=match.group(1), |
| 184 |
ext=extension, |
| 185 |
) |
| 186 |
exception = MissingFileError(message) |
| 187 |
return exception |
| 188 |
|
| 189 |
_error_msg_re = re.compile(r"^The file '(.+)' could not be found") |
| 190 |
|
| 191 |
_error_msg = textwrap.dedent( |
| 192 |
"""\ |
| 193 |
{orig_message} |
| 194 |
|
| 195 |
The {ext} file '{filename}' references a file which could not be found: |
| 196 |
{missing} |
| 197 |
|
| 198 |
Please check the URL references in this {ext} file, particularly any |
| 199 |
relative paths which might be pointing to the wrong location. |
| 200 |
""" |
| 201 |
) |