Skip to content
Open
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- `handle_user_provided_file` now takes the suffix of the temporary file it generates from the resolved local path rather than from the path as given, so the two differ when the source is a symlink (#414)

### Fixed

- `handle_user_provided_file` no longer leaves an empty temporary file behind when a local path is used with `nocopy=True` or does not exist, nor an empty or partial one when the download or copy fails (#414)

## [5.6.0] - 2026-11-20

### Added
Expand Down
43 changes: 27 additions & 16 deletions src/zimscraperlib/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,39 @@ def handle_user_provided_file(
if not source or not str(source).strip():
return None

if not dest:
dest = pathlib.Path(
tempfile.NamedTemporaryFile(
suffix=pathlib.Path(source).suffix, dir=in_dir, delete=False
).name
)

if str(source).startswith("http"):
from zimscraperlib.download import stream_file # noqa: PLC0415

logger.debug(f"download {source} -> {dest}")
headers = {"User-Agent": user_agent} if user_agent else None
stream_file(url=str(source), fpath=dest, headers=headers)
else:
is_url = str(source).startswith("http")
if not is_url:
source = pathlib.Path(source).expanduser().resolve()
if not source.exists():
raise OSError(f"{source} could not be found.")
if nocopy:
return source

logger.debug(f"copy {source} -> {dest}")
shutil.copy(source, dest)
generated_dest = False
if not dest:
dest = pathlib.Path(
tempfile.NamedTemporaryFile(
suffix=pathlib.Path(source).suffix, dir=in_dir, delete=False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side-effect worth documenting: source is now reassigned to the resolved path before this line, so the temp dest's suffix is taken from the resolved target instead of the user-supplied path.

For a symlink the two differ: handle_user_provided_file(source="pic.png", in_dir=...) where pic.png is a symlink to an extension-less file used to return a temp file ending in .png and now returns a suffix-less one (Path("pic.png").suffix == ".png" vs Path(Path("pic.png").resolve()).suffix == ""); the reverse happens too. That matters for callers that detect the format from the returned file's extension (format_for(..., from_suffix=True), PIL/shutil by extension).

The new behaviour is arguably the more correct one, so no need to change the code — but please add a CHANGELOG entry under ### Changed so downstream scrapers aren't surprised.

).name
)
generated_dest = True

try:
if is_url:
from zimscraperlib.download import stream_file # noqa: PLC0415

logger.debug(f"download {source} -> {dest}")
headers = {"User-Agent": user_agent} if user_agent else None
stream_file(url=str(source), fpath=dest, headers=headers)
else:
logger.debug(f"copy {source} -> {dest}")
shutil.copy(source, dest)
except Exception:
# do not leave the temp file generated above behind; a caller-supplied
# dest is left untouched
if generated_dest:
dest.unlink(missing_ok=True)
raise

return dest

Expand Down
65 changes: 65 additions & 0 deletions tests/inputs/test_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,71 @@ def test_remote_indir(tmp_path: pathlib.Path, valid_http_url: str):
assert fpath.parent == tmp_path


@pytest.mark.parametrize("missing", [False, True])
def test_local_indir_no_leftover_temp_file(
tmp_path: pathlib.Path, png_image: pathlib.Path, *, missing: bool
):
in_dir = tmp_path / "in_dir"
in_dir.mkdir()
if missing:
with pytest.raises(IOError):
handle_user_provided_file(
source=str(tmp_path / "missing.png"), in_dir=in_dir
)
else:
fpath = handle_user_provided_file(
source=str(png_image), in_dir=in_dir, nocopy=True
)
assert fpath == png_image
assert list(in_dir.iterdir()) == []


@pytest.mark.parametrize("remote", [False, True])
def test_indir_no_leftover_temp_file_on_failure(
tmp_path: pathlib.Path,
png_image: pathlib.Path,
valid_http_url: str,
monkeypatch: pytest.MonkeyPatch,
*,
remote: bool,
):
in_dir = tmp_path / "in_dir"
in_dir.mkdir()

if remote:

def failing_stream_file(**_kwargs: Any):
raise OSError("download failed")

monkeypatch.setattr(zimscraperlib.download, "stream_file", failing_stream_file)
with pytest.raises(OSError):
handle_user_provided_file(source=valid_http_url, in_dir=in_dir)
else:

def failing_copy(*_args: Any, **_kwargs: Any):
raise PermissionError("copy failed")

monkeypatch.setattr("zimscraperlib.inputs.shutil.copy", failing_copy)
with pytest.raises(PermissionError):
handle_user_provided_file(source=str(png_image), in_dir=in_dir)
assert list(in_dir.iterdir()) == []


def test_caller_dest_kept_on_failure(
tmp_path: pathlib.Path, valid_http_url: str, monkeypatch: pytest.MonkeyPatch
):
dest = tmp_path / "dest.png"
dest.write_bytes(b"existing")

def failing_stream_file(**_kwargs: Any):
raise OSError("download failed")

monkeypatch.setattr(zimscraperlib.download, "stream_file", failing_stream_file)
with pytest.raises(OSError):
handle_user_provided_file(source=valid_http_url, dest=dest)
assert dest.read_bytes() == b"existing"


def test_remote_default_user_agent(
valid_http_url: str, monkeypatch: pytest.MonkeyPatch
):
Expand Down