diff --git a/jssg/management/commands/format-html.py b/jssg/management/commands/format-html.py index 28bbe71..226d16c 100644 --- a/jssg/management/commands/format-html.py +++ b/jssg/management/commands/format-html.py @@ -1,7 +1,10 @@ +import os from django.core.management.base import BaseCommand from pathlib import Path from bs4 import BeautifulSoup from django.conf import settings +import minify_html + class Command(BaseCommand): help = "Format (beautify or minify) the html files in dist content" @@ -22,12 +25,46 @@ def add_arguments(self, parser): ) def handle(self, *args, **options) : - for path in Path(options["distpath"]).rglob("*.html") : - with open(path, "r+") as file : - soup = BeautifulSoup(file.read(), 'html.parser') - file.seek(0) - if options["mode"] == "minify" : - file.write(str(soup).replace('\n', '')) - else : - file.write(soup.prettify()) - file.truncate() \ No newline at end of file + if options["mode"] == "minify": + for path in Path(options["distpath"]).rglob("*.html"): + self.__minify_file(path) + else: + for path in Path(options["distpath"]).rglob("*.html"): + self.__beautify_file(path) + + def __minify_file(self, file_path: Path, display_downsize_ratio: bool=True) -> None: + size_before = os.stat(file_path).st_size + with open(file_path, "r+") as file: + minified = minify_html.minify( + file.read(), + do_not_minify_doctype=True, + ensure_spec_compliant_unquoted_attribute_values=True, + keep_closing_tags=True, + keep_spaces_between_attributes=True, + minify_css=True, + minify_js=True, + ) + file.seek(0) + file.write(minified) + file.truncate() + + size_after = os.stat(file_path).st_size + if display_downsize_ratio: + message = f"[-{1 - size_after / size_before:.1%}] {file_path}" # shows -xx.x% ration + print(message) + + def __beautify_file(self, file_path: Path, display_upsize_ratio: bool=True) -> None: + """ + beautify a HTML file + """ + size_before = os.stat(file_path).st_size + with open(file_path, "r+") as file: + soup = BeautifulSoup(file.read(), 'html.parser') + file.seek(0) + file.write(soup.prettify()) + file.truncate() + + size_after = os.stat(file_path).st_size + if display_upsize_ratio: + message = f"[+{size_after / size_before - 1:.1%}] {file_path}" # shows +xx.x% ration + print(message) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 11a21bb..2c164fc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,5 @@ markdown2[all]==2.4.13 whitenoise==6.7.0 Jinja2==3.1.4 beautifulsoup4==4.12.3 -django-jinja-markdown \ No newline at end of file +django-jinja-markdown +minify_html==0.15.0