Skip to content

Commit cfc0a14

Browse files
committed
🚧 ensure a valid python identifier for report_manger.py streamlit file
save subsection are also referenced as Page instances, therefore they need a valid Python variable name. This would not be catched at build time, but only when report is being run.
1 parent 84b0ce7 commit cfc0a14

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/vuegen/streamlit_reportview.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import re
23
import subprocess
34
import sys
45
from pathlib import Path
@@ -11,6 +12,17 @@
1112
from .utils import create_folder, generate_footer, is_url
1213

1314

15+
def make_valid_identifier(name: str) -> str:
16+
"""Create a valid Python identifier from a given name.
17+
18+
Used in streamlit report sections to build structure (pages).
19+
"""
20+
ret = re.sub(r"[^a-zA-Z0-9]", "_", name)
21+
if not ret[0].isalpha():
22+
ret = "_" + ret
23+
return ret
24+
25+
1426
class StreamlitReportView(r.WebAppReportView):
1527
"""
1628
A Streamlit-based implementation of the WebAppReportView abstract base class.
@@ -114,7 +126,15 @@ def generate_report(
114126
)
115127

116128
for subsection in section.subsections:
117-
subsection_name_var = subsection.title.replace(" ", "_")
129+
# ! could add a non-integer to ensure it's a valid identifier
130+
subsection_name_var = make_valid_identifier(subsection.title)
131+
if not subsection_name_var.isidentifier():
132+
self.report.logger.warning(
133+
f"Subsection name '{subsection_name_var}' is not a valid identifier."
134+
)
135+
raise ValueError(
136+
f"Subsection name is not a valid Python identifier: {subsection_name_var}"
137+
)
118138
subsection_file_path = (
119139
Path(section_name_var) / f"{subsection_name_var}.py"
120140
).as_posix() # Make sure it's Posix Paths
@@ -336,10 +356,11 @@ def _generate_sections(self, output_dir: str, static_dir: str) -> None:
336356
)
337357
try:
338358
# Create subsection file
359+
_subsection_name = make_valid_identifier(subsection.title)
339360
subsection_file_path = (
340361
Path(output_dir)
341362
/ section_name_var
342-
/ f"{subsection.title.replace(' ', '_')}.py"
363+
/ f"{_subsection_name}.py"
343364
)
344365

345366
# Generate content and imports for the subsection

0 commit comments

Comments
 (0)