From 812c4aa57207b4feab3b5b589ac19714f6bec076 Mon Sep 17 00:00:00 2001 From: Daniel Rojas Date: Sat, 1 Mar 2025 18:49:29 +0100 Subject: [PATCH] Avoid reading diagram file to embed unless used (#371) Add local replacement_if_used() that call function to read the file only when needed and append the return value as replacement. Co-authored-by: kvid --- src/wireviz/wv_output.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/wireviz/wv_output.py b/src/wireviz/wv_output.py index f01ee97..57ce2ad 100644 --- a/src/wireviz/wv_output.py +++ b/src/wireviz/wv_output.py @@ -3,7 +3,7 @@ import base64 import re from pathlib import Path -from typing import Dict, List, Union +from typing import Callable, Dict, List, Union import wireviz # for doing wireviz.__file__ from wireviz import APP_NAME, APP_URL, __version__ @@ -97,12 +97,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, ) @@ -139,8 +139,6 @@ def generate_html_output( "": f"{APP_NAME} {__version__} - {APP_URL}", "": options.fontname, "": options.bgcolor.html, - "": svgdata, - "": data_URI_base64(f"{filename}.png"), "": str(filename), "": Path(filename).stem, "": bom_html, @@ -149,6 +147,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():