diff --git a/CHANGELOG.md b/CHANGELOG.md index 77dcde7..6ea4c8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/zimscraperlib/inputs.py b/src/zimscraperlib/inputs.py index 49f36ac..9c13eb4 100644 --- a/src/zimscraperlib/inputs.py +++ b/src/zimscraperlib/inputs.py @@ -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 + ).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 diff --git a/tests/inputs/test_inputs.py b/tests/inputs/test_inputs.py index f768481..106143e 100644 --- a/tests/inputs/test_inputs.py +++ b/tests/inputs/test_inputs.py @@ -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 ):