Avoid reading diagram file to embed unless used

Add local replacement_if_used() that call function to read the file
only when needed and append the return value as replacement.
This commit is contained in:
KV 2024-05-31 23:03:42 +02:00
parent 493a1ff7db
commit 4b4ddbdb37

View File

@ -2,7 +2,7 @@
import re
from pathlib import Path
from typing import Dict, List, Union
from typing import Callable, Dict, List, Union
from wireviz import APP_NAME, APP_URL, __version__, wv_colors
from wireviz.DataClasses import Metadata, Options
@ -37,12 +37,12 @@ def generate_html_output(
html = open_file_read(templatefile).read()
# embed SVG diagram
with open_file_read(f"{filename}.tmp.svg") as file:
svgdata = re.sub(
# embed SVG diagram (only if used)
def svgdata() -> str:
return re.sub(
"^<[?]xml [^?>]*[?]>[^<]*<!DOCTYPE [^>]*>",
"<!-- XML and DOCTYPE declarations from SVG file removed -->",
file.read(),
open_file_read(f"{filename}.tmp.svg").read(),
1,
)
@ -81,8 +81,6 @@ def generate_html_output(
"<!-- %generator% -->": f"{APP_NAME} {__version__} - {APP_URL}",
"<!-- %fontname% -->": options.fontname,
"<!-- %bgcolor% -->": wv_colors.translate_color(options.bgcolor, "hex"),
"<!-- %diagram% -->": svgdata,
"<!-- %diagram_png_base64% -->": data_URI_base64(f"{filename}.png"),
"<!-- %filename% -->": str(filename),
"<!-- %filename_stem% -->": Path(filename).stem,
"<!-- %bom% -->": bom_html,
@ -91,6 +89,16 @@ def generate_html_output(
"<!-- %sheet_total% -->": "1", # TODO: handle multi-page documents
}
def replacement_if_used(key: str, func: Callable[[], str]) -> None:
"""Append replacement only if used in html."""
if key in html:
replacements[key] = func()
replacement_if_used("<!-- %diagram% -->", svgdata)
replacement_if_used(
"<!-- %diagram_png_base64% -->", lambda: data_URI_base64(f"{filename}.png")
)
# prepare metadata replacements
if metadata:
for item, contents in metadata.items():