Skip to content

Commit

Permalink
wip: add assert_file_is_appendable()
Browse files Browse the repository at this point in the history
  • Loading branch information
msto committed Mar 25, 2024
1 parent 72af12b commit 4c04d23
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions dataclass_io/_lib/assertions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
from os import R_OK
from os import W_OK
from os import access
from os import stat
from pathlib import Path

from dataclass_io._lib.dataclass_extensions import DataclassInstance
from dataclass_io._lib.dataclass_extensions import fieldnames
from dataclass_io._lib.file import get_header


def assert_file_is_readable(path: Path) -> None:
Expand Down Expand Up @@ -65,6 +68,40 @@ def assert_file_is_writable(path: Path, overwrite: bool = True) -> None:
)


def assert_file_is_appendable(path: Path, dataclass_type: type[DataclassInstance]) -> None:
if not path.exists():
raise FileNotFoundError(f"The specified output file does not exist: {path}")

if not path.is_file():
raise IsADirectoryError(f"The specified output file path is a directory: {path}")

if not access(path, W_OK):
raise PermissionError(f"The specified output file is not writable: {path}")

if stat(path).st_size == 0:
raise ValueError(f"The specified output file is empty: {path}")

if not access(path, R_OK):
raise PermissionError(
f"The specified output file is not readable: {path}\n"
"The output file must be readable to append to it. "
"The header of the existing output file is checked for consistency with the provided "
"dataclass before appending to it."
)

# TODO: pass delimiter and header_comment_char to get_header
with path.open("r") as f:
header = get_header(f)
if header is None:
raise ValueError(f"Could not find a header in the specified output file: {path}")

if header.fieldnames != fieldnames(dataclass_type):
raise ValueError(
"The specified output file does not have the same field names as the provided "
f"dataclass {path}"
)


def assert_dataclass_is_valid(dataclass_type: type[DataclassInstance]) -> None:
"""
Check that the input type is a parseable dataclass.
Expand Down

0 comments on commit 4c04d23

Please sign in to comment.