From 7b0b89396bd3e65594b599a423ee4b82cd71e7b2 Mon Sep 17 00:00:00 2001 From: KV Date: Fri, 31 May 2024 23:03:42 +0200 Subject: [PATCH] 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. --- src/wireviz/wv_html.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/wireviz/wv_html.py b/src/wireviz/wv_html.py index e939c6f2..176d2303 100644 --- a/src/wireviz/wv_html.py +++ b/src/wireviz/wv_html.py @@ -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 [^?>]*[?]>[^<]*]*>", "", - file.read(), + open_file_read(f"{filename}.tmp.svg").read(), 1, ) @@ -81,8 +81,6 @@ def generate_html_output( "": f"{APP_NAME} {__version__} - {APP_URL}", "": options.fontname, "": wv_colors.translate_color(options.bgcolor, "hex"), - "": svgdata, - "": data_URI_base64(f"{filename}.png"), "": str(filename), "": Path(filename).stem, "": bom_html, @@ -91,6 +89,16 @@ def generate_html_output( "": "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("", svgdata) + replacement_if_used( + "", lambda: data_URI_base64(f"{filename}.png") + ) + # prepare metadata replacements if metadata: for item, contents in metadata.items():