Skip to content

Commit

Permalink
fix #61: Minify process break query parameters in links
Browse files Browse the repository at this point in the history
  • Loading branch information
lebouquetin committed Oct 10, 2024
1 parent f44e426 commit bf50d73
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 10 deletions.
55 changes: 46 additions & 9 deletions jssg/management/commands/format-html.py
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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()
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)
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ markdown2[all]==2.4.13
whitenoise==6.7.0
Jinja2==3.1.4
beautifulsoup4==4.12.3
django-jinja-markdown
django-jinja-markdown
minify_html==0.15.0

0 comments on commit bf50d73

Please sign in to comment.