From 45e10a608015ce232c26a1c558600fadcbf9ec6b Mon Sep 17 00:00:00 2001 From: Kevin Flores Date: Tue, 1 Dec 2026 16:16:26 -0500 Subject: [PATCH 1/2] Only create handle_user_provided_file temp dest when it is used --- CHANGELOG.md | 4 ++++ src/zimscraperlib/inputs.py | 16 +++++++++------- tests/inputs/test_inputs.py | 19 +++++++++++++++++++ 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77dcde7..ee229da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### 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 (#414) + ## [5.6.0] - 2026-11-20 ### Added diff --git a/src/zimscraperlib/inputs.py b/src/zimscraperlib/inputs.py index 49f36ac..c3d1640 100644 --- a/src/zimscraperlib/inputs.py +++ b/src/zimscraperlib/inputs.py @@ -32,6 +32,14 @@ def handle_user_provided_file( if not source or not str(source).strip(): return None + 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 + if not dest: dest = pathlib.Path( tempfile.NamedTemporaryFile( @@ -39,19 +47,13 @@ def handle_user_provided_file( ).name ) - if str(source).startswith("http"): + 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: - 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) diff --git a/tests/inputs/test_inputs.py b/tests/inputs/test_inputs.py index f768481..079ca30 100644 --- a/tests/inputs/test_inputs.py +++ b/tests/inputs/test_inputs.py @@ -84,6 +84,25 @@ 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()) == [] + + def test_remote_default_user_agent( valid_http_url: str, monkeypatch: pytest.MonkeyPatch ): From e4b3eb7d59701822419f28e64895c2bcbd28b5b9 Mon Sep 17 00:00:00 2001 From: Kevin Flores Date: Thu, 3 Dec 2026 08:57:14 -0500 Subject: [PATCH 2/2] Remove the generated temp dest when the download or copy fails --- CHANGELOG.md | 6 ++++- src/zimscraperlib/inputs.py | 29 +++++++++++++++-------- tests/inputs/test_inputs.py | 46 +++++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee229da..6ea4c8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,13 @@ 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 (#414) +- `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 diff --git a/src/zimscraperlib/inputs.py b/src/zimscraperlib/inputs.py index c3d1640..9c13eb4 100644 --- a/src/zimscraperlib/inputs.py +++ b/src/zimscraperlib/inputs.py @@ -40,22 +40,31 @@ def handle_user_provided_file( if nocopy: return source + generated_dest = False if not dest: dest = pathlib.Path( tempfile.NamedTemporaryFile( suffix=pathlib.Path(source).suffix, dir=in_dir, delete=False ).name ) - - 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) + 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 diff --git a/tests/inputs/test_inputs.py b/tests/inputs/test_inputs.py index 079ca30..106143e 100644 --- a/tests/inputs/test_inputs.py +++ b/tests/inputs/test_inputs.py @@ -103,6 +103,52 @@ def test_local_indir_no_leftover_temp_file( 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 ):