|
| 1 | +import argparse |
| 2 | +from hashlib import sha256 |
| 3 | +import json |
| 4 | +import os |
| 5 | +import pathlib |
| 6 | +import shutil |
| 7 | +import sys |
| 8 | +import typing |
| 9 | + |
| 10 | +from starlette.responses import FileResponse |
| 11 | +from starlette.staticfiles import StaticFiles |
| 12 | +from typing_extensions import override |
| 13 | + |
| 14 | + |
| 15 | +def compile_static_files(*, destination: pathlib.Path, sources: typing.Sequence[pathlib.Path]): |
| 16 | + """Compile a static directory from one or more source directories.""" |
| 17 | + # This function is designed to write the static files, could be useful for serving static |
| 18 | + # files via apache/nginx/etc. |
| 19 | + manifest = generate_manifest(sources) |
| 20 | + file_map = {'file-map': {}} |
| 21 | + |
| 22 | + for input_filename, (hashed_relpath, source_path) in manifest.items(): |
| 23 | + target = destination / hashed_relpath |
| 24 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 25 | + shutil.copy(source_path, target) |
| 26 | + file_map['file-map'][str(input_filename)] = str(target) |
| 27 | + |
| 28 | + json.dump(file_map, (destination / '.manifest.json').open('w'), indent=2) |
| 29 | + (destination / '.gitignore').write_text('*') |
| 30 | + |
| 31 | + |
| 32 | +def generate_manifest(sources: typing.Sequence[pathlib.Path]) -> dict[str, tuple[str, pathlib.Path]]: |
| 33 | + """ |
| 34 | + Generate a manifest which maps template_rel_path to a (hashed_relpath, full_path) tuple. |
| 35 | + """ |
| 36 | + manifest: dict[str, tuple[str, str]] = {} |
| 37 | + files_to_compile = {} |
| 38 | + for source in sources: |
| 39 | + assert source.exists() |
| 40 | + for path in sorted(source.glob('**/*')): |
| 41 | + if not path.is_file(): |
| 42 | + continue |
| 43 | + if path.name.startswith('.'): |
| 44 | + continue |
| 45 | + rel = path.relative_to(source) |
| 46 | + files_to_compile[rel] = path |
| 47 | + |
| 48 | + for rel, source_path in files_to_compile.items(): |
| 49 | + file_hash = sha256(source_path.read_bytes()).hexdigest()[:12] |
| 50 | + name = f'{source_path.stem}.{file_hash}{source_path.suffix}' |
| 51 | + manifest[str(rel)] = (str(rel.parent / name), source_path) |
| 52 | + |
| 53 | + return manifest |
| 54 | + |
| 55 | + |
| 56 | +class HashedStaticFileHandler(StaticFiles): |
| 57 | + def __init__(self, *, manifest, **kwargs): |
| 58 | + super().__init__(**kwargs) |
| 59 | + self.manifest = manifest |
| 60 | + self._inverted_manifest = {src: path for src, path in manifest.values()} |
| 61 | + |
| 62 | + @override |
| 63 | + def lookup_path(self, path: str) -> tuple[str, os.stat_result | None]: |
| 64 | + actual_path = self._inverted_manifest.get(path) |
| 65 | + if actual_path is None: |
| 66 | + super.lookup_path(path) |
| 67 | + return actual_path, os.stat(actual_path) |
| 68 | + |
| 69 | + @override |
| 70 | + async def get_response(self, path: str, scope): |
| 71 | + response: FileResponse = await super().get_response(path, scope) |
| 72 | + if response.status_code in [200, 304]: |
| 73 | + response.headers["Cache-Control"] = "public, max-age=31536000, immutable" |
| 74 | + return response |
| 75 | + |
| 76 | + |
| 77 | +def main(argv: typing.Sequence[str]) -> int: |
| 78 | + parser = argparse.ArgumentParser(prog='simple_repository_browser.static') |
| 79 | + |
| 80 | + subparsers = parser.add_subparsers() |
| 81 | + |
| 82 | + parser_compile_static = subparsers.add_parser('compile', help='Compile the static files into a directory') |
| 83 | + parser_compile_static.add_argument('destination', type=pathlib.Path, help='Where to write the static files') |
| 84 | + parser_compile_static.add_argument( |
| 85 | + 'source', |
| 86 | + type=pathlib.Path, |
| 87 | + help='The source of static files to combine (may be provided multiple times)', |
| 88 | + nargs='+', |
| 89 | + ) |
| 90 | + parser_compile_static.set_defaults(handler=handle_compile) |
| 91 | + |
| 92 | + args = parser.parse_args(argv) |
| 93 | + args.handler(args) |
| 94 | + |
| 95 | + |
| 96 | +def handle_compile(args: argparse.Namespace): |
| 97 | + print(f'Writing static files to {args.destination}') |
| 98 | + compile_static_files(destination=args.destination, sources=args.source) |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == '__main__': |
| 102 | + # Enable simple_repository_browser.static_files CLI. |
| 103 | + main(sys.argv[1:]) |
0 commit comments