added dj-libs tag; do not overwrite input files by default again

This commit is contained in:
truePhilipp committed 2024-05-05 21:10:51 +02:00
1 parent 29f79c881a
commit 2cb63251ff
1 file changed
+15 -2
+15 -2
View File
@@ -5,10 +5,22 @@ from glob import glob
from .formatters import formatters from .formatters import formatters
def get_required_libraries(soup: bs4.BeautifulSoup) -> list[str]:
if html := soup.find("html"):
if isinstance(html, bs4.Tag):
if html.has_attr("dj-libs"):
dj_libs = html["dj-libs"]
if isinstance(dj_libs, str):
return dj_libs.split(";")
return []
def convert_file(path: str, overwrite: bool = False) -> None: def convert_file(path: str, overwrite: bool = False) -> None:
with open(path, "r") as file: with open(path, "r") as file:
soup = bs4.BeautifulSoup(file, "html.parser") soup = bs4.BeautifulSoup(file, "html.parser")
required_libraries = get_required_libraries(soup)
for formatter in formatters: for formatter in formatters:
formatter.format(soup) formatter.format(soup)
@@ -17,7 +29,8 @@ def convert_file(path: str, overwrite: bool = False) -> None:
else: else:
out_path = path.replace(".html", ".n.html") out_path = path.replace(".html", ".n.html")
with open(out_path, "w") as file: with open(out_path, "w") as file:
file.write("{% load static %}\n") for lib in required_libraries:
file.write(f"{{% load {lib} %}}\n")
file.write(soup file.write(soup
.prettify(formatter=bs4.formatter.HTMLFormatter(indent=4)) .prettify(formatter=bs4.formatter.HTMLFormatter(indent=4))
.replace(""", '"')) # Could this cause any issues? (maybe in attributes) .replace(""", '"')) # Could this cause any issues? (maybe in attributes)
@@ -31,6 +44,6 @@ def convert_dir(path: str, overwrite: bool = False) -> None:
def command_entry() -> None: def command_entry() -> None:
path = os.path.abspath(sys.argv[1]) path = os.path.abspath(sys.argv[1])
if os.path.isdir(path): if os.path.isdir(path):
convert_dir(path, True) convert_dir(path)
elif os.path.isfile(path): elif os.path.isfile(path):
convert_file(path) convert_file(path)