Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def load_template_file(file_path: str | os.PathLike, *, path_ctx: str | os.PathL
elif not file_path_obj.is_absolute():
raise ValueError("Provided path must be absolute if no path_ctx is provided")

return load_file(file_path_obj.absolute())
return load_file(file_path_obj.absolute(), strict=True)


# TODO: TBH this utility really doesn't add anything, probably better to just remove it
Expand Down
21 changes: 19 additions & 2 deletions localstack-core/localstack/utils/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,26 @@ def _opener(path, flags):
f.flush()


def load_file(file_path: str, default=None, mode=None):
def load_file(
file_path: str | os.PathLike,
default: str | bytes | None = None,
mode: str | None = None,
strict: bool = False,
) -> str | bytes | None:
"""
Return file contents

:param file_path: path of the file
:param default: if strict=False then return this value if the file does not exist
:param mode: mode to open the file with (e.g. `r`, `rw`)
:param strict: raise an error if the file path is not a file
:return: the file contents
"""
if not os.path.isfile(file_path):
return default
if strict:
raise FileNotFoundError(file_path)
else:
return default
if not mode:
mode = "r"
with open(file_path, mode) as f:
Expand Down
9 changes: 9 additions & 0 deletions tests/unit/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,15 @@ def test_save_load_file(tmp_path):
assert content + more_content == load_file(file_name)


def test_load_file_strict(tmp_path):
file_name = tmp_path / short_uid()
assert not os.path.isfile(file_name)

assert load_file(file_name) is None
with pytest.raises(FileNotFoundError):
load_file(file_name, strict=True)


def test_save_load_file_with_permissions(tmp_path):
file_name = tmp_path / (f"special_permissions_{short_uid()}")
content = f"some_content_{short_uid()}"
Expand Down
Loading