Skip to content

Commit a808217

Browse files
committed
🎨 line lenght, lazy logging and raising exceptions from exception
1 parent 732e1fe commit a808217

File tree

1 file changed

+42
-25
lines changed

1 file changed

+42
-25
lines changed

src/vuegen/utils/__init__.py

Lines changed: 42 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
"""File system utilities, file conversion functions,
2+
graph related utilities, config file writing, and
3+
command line parser and logging messages (completion).
4+
5+
streamlit report footer is also in this file.
6+
"""
7+
18
from __future__ import annotations
29

310
import argparse
@@ -72,14 +79,16 @@ def assert_enum_value(
7279
"""
7380
try:
7481
return enum_class[value.upper()]
75-
except KeyError:
82+
except KeyError as e:
7683
expected_values = ", ".join([str(e.value) for e in enum_class])
7784
logger.error(
78-
f"Invalid value for {enum_class.__name__}: '{value}'. Expected values are: {expected_values}"
85+
f"Invalid value for {enum_class.__name__}: '{value}'."
86+
f"Expected values are: {expected_values}"
7987
)
8088
raise ValueError(
81-
f"Invalid {enum_class.__name__}: {value}. Expected values are: {expected_values}"
82-
)
89+
f"Invalid {enum_class.__name__}: {value}. "
90+
f"Expected values are: {expected_values}"
91+
) from e
8392

8493

8594
def is_url(filepath: Path) -> bool:
@@ -138,17 +147,19 @@ def is_pyvis_html(filepath: str) -> bool:
138147
return pyvis_identifier_valid and body_structure_valid
139148

140149

141-
## FILE_SYSTEM
150+
# FILE_SYSTEM
142151
def create_folder(directory_path: str, is_nested: bool = False) -> bool:
143152
"""
144-
Create a folder. Optionally create nested directories if the specified path includes subdirectories.
153+
Create a folder. Optionally create nested directories if the specified path includes
154+
subdirectories.
145155
146156
Parameters
147157
----------
148158
directory_path : str
149159
The path of the directory to create.
150160
is_nested : bool
151-
A flag indicating whether to create nested directories (True uses os.makedirs, False uses os.mkdir).
161+
A flag indicating whether to create nested directories.
162+
True uses os.makedirs, False uses os.mkdir.
152163
153164
Returns
154165
-------
@@ -173,7 +184,7 @@ def create_folder(directory_path: str, is_nested: bool = False) -> bool:
173184
else:
174185
return False
175186
except OSError as e:
176-
raise OSError(f"Error creating directory '{directory_path}': {e}")
187+
raise OSError(f"Error creating directory '{directory_path}'.") from e
177188

178189

179190
def get_relative_file_path(
@@ -268,7 +279,10 @@ def get_parser(prog_name: str, others: Optional[dict] = None) -> argparse.Namesp
268279
"--report_type",
269280
type=str,
270281
default="streamlit",
271-
help="Type of the report to generate (streamlit, html, pdf, docx, odt, revealjs, pptx, or jupyter).",
282+
help=(
283+
"Type of the report to generate: streamlit, html, pdf, docx, odt, revealjs,"
284+
" pptx, or jupyter."
285+
),
272286
)
273287
parser.add_argument(
274288
"-output_dir",
@@ -338,9 +352,8 @@ def fetch_file_stream(file_path: str, timeout: int = TIMEOUT) -> StringIO:
338352
response.raise_for_status() # Raise an exception for HTTP errors
339353
return StringIO(response.text)
340354
except requests.exceptions.RequestException as e:
341-
raise ValueError(
342-
f"Error fetching content from URL: {file_path}. Error: {str(e)}"
343-
)
355+
raise ValueError(f"Error fetching content from URL: {file_path}.") from e
356+
344357
else:
345358
# Handle local file input
346359
if not os.path.exists(file_path):
@@ -351,12 +364,13 @@ def fetch_file_stream(file_path: str, timeout: int = TIMEOUT) -> StringIO:
351364
return StringIO(file.read())
352365

353366

354-
## FILE_CONVERSION
367+
# FILE_CONVERSION
355368
def cyjs_to_networkx(file_path: str, name: str = "name", ident: str = "id") -> nx.Graph:
356369
"""
357-
Create a NetworkX graph from a `.cyjs` file in Cytoscape format, including all attributes present in the JSON data.
358-
This function is modified from the `cytoscape_graph` networkx function to handle the 'value' key explicitly and to include
359-
all additional attributes found in the JSON data for both nodes and edges.
370+
Create a NetworkX graph from a `.cyjs` file in Cytoscape format, including all
371+
attributes present in the JSON data. This function is modified from the
372+
`cytoscape_graph` networkx function to handle the 'value' key explicitly and to
373+
include all additional attributes found in the JSON data for both nodes and edges.
360374
361375
Parameters
362376
----------
@@ -371,14 +385,16 @@ def cyjs_to_networkx(file_path: str, name: str = "name", ident: str = "id") -> n
371385
Returns
372386
-------
373387
graph : networkx.Graph
374-
The graph created from the Cytoscape JSON data, including all node and edge attributes.
388+
The graph created from the Cytoscape JSON data, including all node and edge
389+
attributes.
375390
376391
Raises
377392
------
378393
NetworkXError
379394
If the `name` and `ident` attributes are identical.
380395
ValueError
381-
If the data format is invalid or missing required elements, such as 'id' or 'name' for nodes.
396+
If the data format is invalid or missing required elements, such as 'id'
397+
or 'name' for nodes.
382398
"""
383399
try:
384400
# If file_path is a file-like object (e.g., StringIO), read from it
@@ -438,7 +454,7 @@ def cyjs_to_networkx(file_path: str, name: str = "name", ident: str = "id") -> n
438454
return graph
439455

440456
except KeyError as e:
441-
raise ValueError(f"Missing required key in data: {e}")
457+
raise ValueError("Missing required key in data.") from e
442458

443459

444460
def pyvishtml_to_networkx(html_file: str) -> nx.Graph:
@@ -458,7 +474,8 @@ def pyvishtml_to_networkx(html_file: str) -> nx.Graph:
458474
Raises
459475
------
460476
ValueError
461-
If the HTML file does not contain the expected network data, or if nodes lack 'id' attribute.
477+
If the HTML file does not contain the expected network data,
478+
or if nodes lack 'id' attribute.
462479
"""
463480
# Load the HTML file
464481
if isinstance(html_file, StringIO):
@@ -519,7 +536,7 @@ def pyvishtml_to_networkx(html_file: str) -> nx.Graph:
519536
return graph
520537

521538

522-
## CONFIG
539+
# CONFIG
523540
def load_yaml_config(file_path: str) -> dict:
524541
"""
525542
Load a YAML configuration file and return its contents as a dictionary.
@@ -550,7 +567,7 @@ def load_yaml_config(file_path: str) -> dict:
550567
try:
551568
config = yaml.safe_load(file)
552569
except yaml.YAMLError as exc:
553-
raise ValueError(f"Error parsing YAML file: {exc}")
570+
raise ValueError("Error parsing YAML file.") from exc
554571

555572
return config
556573

@@ -590,7 +607,7 @@ def write_yaml_config(yaml_data: dict, directory_path: Path) -> Path:
590607
return output_yaml
591608

592609

593-
## LOGGING
610+
# LOGGING
594611
def get_basename(fname: None | str = None) -> str:
595612
"""
596613
- For a given filename, returns basename WITHOUT file extension
@@ -700,7 +717,7 @@ def generate_log_filename(folder: str = "logs", suffix: str = "") -> str:
700717
# PRECONDITIONS
701718
create_folder(folder) # ? Path(folder).mkdir(parents=True, exist_ok=True)
702719
except OSError as e:
703-
raise OSError(f"Error creating directory '{folder}': {e}")
720+
raise OSError(f"Error creating directory '{folder}'") from e
704721
# MAIN FUNCTION
705722
log_filename = get_time(incl_timezone=False) + "_" + suffix + ".log"
706723
log_filepath = os.path.join(folder, log_filename)
@@ -794,7 +811,7 @@ def get_logger(
794811
logger = init_log(log_file, display=display, logger_id=logger_id)
795812

796813
# Log the path to the log file
797-
logger.info(f"Path to log file: {log_file}")
814+
logger.info("Path to log file: %s", log_file)
798815

799816
return logger, log_file
800817

0 commit comments

Comments
 (0)