Skip to content

Commit

Permalink
Avoid reading diagram file to embed unless used
Browse files Browse the repository at this point in the history
Add local replacement_if_used() that call function to read the file
only when needed and append the return value as replacement.
  • Loading branch information
kvid committed May 31, 2024
1 parent 957bb22 commit 7b0b893
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/wireviz/wv_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)

Expand Down Expand Up @@ -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,
Expand All @@ -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():
Expand Down

0 comments on commit 7b0b893

Please sign in to comment.