Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic ensure #43

Merged
merged 11 commits into from
Jul 1, 2022
Merged
Changes from 2 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
39 changes: 38 additions & 1 deletion src/pystow/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import zipfile
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence, Union
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Sequence, Union

from . import utils
from .constants import JSON, Opener
Expand Down Expand Up @@ -178,6 +178,43 @@ def ensure(
)
return path

def ensure_custom(
self,
*subkeys: str,
name: str,
force: bool = False,
provider: Callable[..., None],
**kwargs,
) -> Path:
"""Ensure a file is present, and run a custom create function otherwise.

:param subkeys:
A sequence of additional strings to join. If none are given,
returns the directory for this module.
:param name:
The file name.
:param force:
Should the file be re-created, even if the path already exists?
:param provider:
The file provider. Will be run with the path as the first positional argument,
if the file needs to be generated.
:param kwargs:
Additional keyword-based parameters passed to the provider.

:raises ValueError:
If the provider was called but the file was not created by it.

:return:
The path of the file that has been created (or already exists)
"""
path = self.join(*subkeys, name=name, ensure_exists=True)
if path.is_file() and not force:
return path
provider(path, **kwargs)
if not path.is_file():
raise ValueError(f"Provider {provider} did not create the file at {path}!")
cthoyt marked this conversation as resolved.
Show resolved Hide resolved
return path

def ensure_untar(
self,
*subkeys: str,
Expand Down