Skip to content

Only create handle_user_provided_file temp dest when it is used - #419

Open
kevincommits wants to merge 2 commits into
openzim:mainfrom
kevincommits:fix/user-provided-file-empty-temp
Open

kevincommits wants to merge 2 commits into
openzim:mainfrom
kevincommits:fix/user-provided-file-empty-temp

Conversation

@kevincommits

Copy link
Copy Markdown

Fixes #414

When dest is not given, handle_user_provided_file() created a NamedTemporaryFile(delete=False) before checking the source. For a local path used with nocopy=True, or a local path that does not exist, the function returns or raises without using it, leaving an empty tmp* file in in_dir (or the system temp directory).

The local-path resolution, existence check and nocopy return now happen first; the temporary dest is only created when the file is actually downloaded or copied. Behaviour is otherwise unchanged.

Changes:

  • src/zimscraperlib/inputs.py: create the temp dest after the local-path checks.
  • tests/inputs/test_inputs.py: test_local_indir_no_leftover_temp_file, parametrized for the nocopy=True and missing-path cases, asserts in_dir stays empty (fails before the change, passes after).
  • CHANGELOG.md: entry under Unreleased / Fixed.

Tested locally (macOS arm64, Python 3.14):

  • pytest tests/inputs/test_inputs.py: 26 passed. libmagic and cairo are not installed on this machine, so magic and cairosvg were replaced by empty stand-in modules for this run; the tested code does not use them.
  • ruff check, ruff format --check and pyright on the two touched Python files: clean.
  • The full test suite was not run.

@benoit74 benoit74 left a comment

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.

The fix is correct for the reported case: the temp dest is no longer created before the local-path checks, so nocopy=True and the missing-path error no longer leave an empty tmp* file behind. URL handling, caller-supplied dest, the OSError message and the return values are unchanged, and the new test covers both early-exit paths.

Two things before merging: a side-effect on the generated temp file's suffix that is fine but should be documented, and a remaining case of the very same leftover-file bug that should be fixed here.

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.

Comment thread src/zimscraperlib/inputs.py Outdated

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)

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.

The leftover-temp-file bug from #414 still happens here: if stream_file() raises (network error, HTTP error) — or shutil.copy() below raises (permission denied, disk full) — the NamedTemporaryFile(delete=False) dest stays behind in in_dir, empty or partial. Same symptom as the cases this PR fixes, just via the failure path instead of an early return.

Could you wrap the download/copy so the generated dest is removed on failure and the exception re-raised? Something like keeping a flag for "dest was generated here" (don't delete a caller-supplied dest) and, on exception, dest.unlink(missing_ok=True) before re-raising. A test with a stream_file that raises, asserting in_dir is empty, would round out the new parametrized test nicely.

@kevincommits

Copy link
Copy Markdown
Author

Both points are handled in e4b3eb7. The download and copy are now wrapped so that a dest generated by this function is removed and the exception re-raised when either one fails, while a caller-supplied dest is left alone. I added a test for each failure path that checks in_dir ends up empty, and one that checks a caller-supplied dest is kept. The suffix change is in the CHANGELOG under Changed, and I extended the Fixed line to mention the failure case. Locally I ran tests/inputs/test_inputs.py, ruff and pyright on the two changed Python files, not the full suite.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

handle_user_provided_file leaves an empty temp file

2 participants