Skip to content

RecipeLibrary

🛈 DocStrings

A folder of .datacookrecipe files (the app uses <user data dir>/recipes).

Source code in src/datacook/engine/recipes.py
class RecipeLibrary:
    """A folder of `.datacookrecipe` files (the app uses `<user data dir>/recipes`)."""

    def __init__(self, folder: str | pathlib.Path, registry: Registry[type[Op]] | None = None):
        self.folder = pathlib.Path(folder)
        self.registry = registry

    def entries(self) -> list[LibraryEntry]:
        """Every recipe file, sorted by name; unreadable files carry `error`."""
        if not self.folder.is_dir():
            return []
        out = []
        for path in sorted(self.folder.glob(f"*{SUFFIX}")):
            try:
                out.append(LibraryEntry(path, load(path, self.registry)))
            except (RecipeError, OSError, UnicodeDecodeError) as e:
                out.append(LibraryEntry(path, None, str(e)))
        return sorted(out, key=lambda e: e.name.casefold())

    def _free_path(self, name: str, keep: pathlib.Path | None = None) -> pathlib.Path:
        base = _slug(name)
        path = self.folder / f"{base}{SUFFIX}"
        n = 2
        while path.exists() and path != keep:
            path = self.folder / f"{base}-{n}{SUFFIX}"
            n += 1
        return path

    def save(self, recipe: Recipe) -> pathlib.Path:
        """Store a new recipe (a free file name from its name)."""
        self.folder.mkdir(parents=True, exist_ok=True)
        path = self._free_path(recipe.name)
        recipe.save(path)
        return path

    def update(
        self,
        path: str | pathlib.Path,
        *,
        name: str | None = None,
        description: str | None = None,
    ) -> pathlib.Path:
        """Rename / re-describe a recipe; the file follows the name. Returns the new path."""
        path = pathlib.Path(path)
        recipe = load(path, self.registry)
        changes: dict[str, Any] = {}
        if name is not None:
            if not name.strip():
                raise RecipeError(str(_("A recipe needs a name.")))
            changes["name"] = name.strip()
        if description is not None:
            changes["description"] = description
        recipe = replace(recipe, **changes)
        new_path = self._free_path(recipe.name, keep=path) if name is not None else path
        recipe.save(new_path)
        if new_path != path:
            path.unlink()
        return new_path

    def delete(self, path: str | pathlib.Path) -> None:
        pathlib.Path(path).unlink(missing_ok=True)

    def merge(
        self, paths: Sequence[str | pathlib.Path], *, name: str | None = None
    ) -> pathlib.Path:
        """A new recipe: the given recipes one after the other (originals are kept)."""
        if len(paths) < 2:  # noqa: PLR2004
            raise RecipeError(str(_("Select at least two recipes to merge.")))
        recipes = [load(p, self.registry) for p in paths]
        result = recipes[0]
        for other in recipes[1:]:
            result = merge(result, other)
        if name:
            result = replace(result, name=name)
        return self.save(replace(result, created=_now()))

    def import_file(self, path: str | pathlib.Path) -> pathlib.Path:
        """Copy a recipe file into the library (validated first)."""
        return self.save(load(path, self.registry))

entries

entries() -> list[LibraryEntry]

Every recipe file, sorted by name; unreadable files carry error.

Source code in src/datacook/engine/recipes.py
def entries(self) -> list[LibraryEntry]:
    """Every recipe file, sorted by name; unreadable files carry `error`."""
    if not self.folder.is_dir():
        return []
    out = []
    for path in sorted(self.folder.glob(f"*{SUFFIX}")):
        try:
            out.append(LibraryEntry(path, load(path, self.registry)))
        except (RecipeError, OSError, UnicodeDecodeError) as e:
            out.append(LibraryEntry(path, None, str(e)))
    return sorted(out, key=lambda e: e.name.casefold())

import_file

import_file(path: str | Path) -> Path

Copy a recipe file into the library (validated first).

Source code in src/datacook/engine/recipes.py
def import_file(self, path: str | pathlib.Path) -> pathlib.Path:
    """Copy a recipe file into the library (validated first)."""
    return self.save(load(path, self.registry))

merge

merge(paths: Sequence[str | Path], *, name: str | None = None) -> Path

A new recipe: the given recipes one after the other (originals are kept).

Source code in src/datacook/engine/recipes.py
def merge(
    self, paths: Sequence[str | pathlib.Path], *, name: str | None = None
) -> pathlib.Path:
    """A new recipe: the given recipes one after the other (originals are kept)."""
    if len(paths) < 2:  # noqa: PLR2004
        raise RecipeError(str(_("Select at least two recipes to merge.")))
    recipes = [load(p, self.registry) for p in paths]
    result = recipes[0]
    for other in recipes[1:]:
        result = merge(result, other)
    if name:
        result = replace(result, name=name)
    return self.save(replace(result, created=_now()))

save

save(recipe: Recipe) -> Path

Store a new recipe (a free file name from its name).

Source code in src/datacook/engine/recipes.py
def save(self, recipe: Recipe) -> pathlib.Path:
    """Store a new recipe (a free file name from its name)."""
    self.folder.mkdir(parents=True, exist_ok=True)
    path = self._free_path(recipe.name)
    recipe.save(path)
    return path

update

update(path: str | Path, *, name: str | None = None, description: str | None = None) -> Path

Rename / re-describe a recipe; the file follows the name. Returns the new path.

Source code in src/datacook/engine/recipes.py
def update(
    self,
    path: str | pathlib.Path,
    *,
    name: str | None = None,
    description: str | None = None,
) -> pathlib.Path:
    """Rename / re-describe a recipe; the file follows the name. Returns the new path."""
    path = pathlib.Path(path)
    recipe = load(path, self.registry)
    changes: dict[str, Any] = {}
    if name is not None:
        if not name.strip():
            raise RecipeError(str(_("A recipe needs a name.")))
        changes["name"] = name.strip()
    if description is not None:
        changes["description"] = description
    recipe = replace(recipe, **changes)
    new_path = self._free_path(recipe.name, keep=path) if name is not None else path
    recipe.save(new_path)
    if new_path != path:
        path.unlink()
    return new_path

:fa-brands-github: Show source on GitHub