Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
40 changes: 24 additions & 16 deletions packages/syft-datasets/src/syft_datasets/dataset_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,8 @@ def _materialize_version(
exclude_names: frozenset[str] = frozenset(),
) -> Dataset:
"""Copy files + write metadata/config for a single protocol version."""
# Check every source before copying, so a bad path leaves nothing behind.
self._validate_source_files(source)
target_mock_dir = self.public_dataset_dir(ref)
private_dir = self.private_dataset_dir(ref)

Expand Down Expand Up @@ -397,15 +399,33 @@ def _url_for(self, path: Path) -> SyftBoxURL:
path=path, syftbox_folder=self.config.syftbox_folder
)

@staticmethod
def _validate_source_files(source: DatasetSourceFiles) -> None:
"""Raise when a source path is missing or is not a file or directory."""
if not source.mock.exists():
raise FileNotFoundError(f"Could not find mock data at {source.mock}")
if not (source.mock.is_file() or source.mock.is_dir()):
raise ValueError(
f"Mock data path {source.mock} must be an existing file or directory."
)
if source.readme is not None:
if not source.readme.is_file():
raise FileNotFoundError(f"Could not find README at {source.readme}")
if source.readme.suffix.lower() != ".md":
raise ValueError("readme file must be a markdown (.md) file.")
if not (source.private.is_file() or source.private.is_dir()):
raise ValueError(
f"Private data path {source.private} must be an existing file "
"or directory."
)

def _copy_mock_data(
self,
ref: DatasetRef,
src_path: Path,
exclude_names: frozenset[str] = frozenset(),
) -> list[Path]:
target_dir = self.public_dataset_dir(ref)
if not src_path.exists():
raise FileNotFoundError(f"Could not find mock data at {src_path}")
if target_dir.exists() and not is_empty_dir(target_dir):
raise FileExistsError(
f"Mock dir {target_dir} already exists and is not empty."
Expand All @@ -418,11 +438,7 @@ def _copy_mock_data(
exists_ok=True,
exclude_names=exclude_names,
)
if src_path.is_file():
return copy_paths(files=[src_path], dst=target_dir, exists_ok=True)
raise ValueError(
f"Mock data path {src_path} must be an existing file or directory."
)
return copy_paths(files=[src_path], dst=target_dir, exists_ok=True)

def _copy_private_data(
self,
Expand All @@ -440,19 +456,11 @@ def _copy_private_data(
exists_ok=True,
exclude_names=exclude_names,
)
if src_path.is_file():
return copy_paths(files=[src_path], dst=private_target_dir, exists_ok=True)
raise ValueError(
f"Private data path {src_path} must be an existing file or directory."
)
return copy_paths(files=[src_path], dst=private_target_dir, exists_ok=True)

def _copy_readme(self, ref: DatasetRef, src_file: Optional[Path]) -> list[Path]:
if src_file is None:
return []
if not src_file.is_file():
raise FileNotFoundError(f"Could not find README at {src_file}")
if not src_file.suffix.lower() == ".md":
raise ValueError("readme file must be a markdown (.md) file.")
return copy_paths(
files=[src_file], dst=self.public_dataset_dir(ref), exists_ok=True
)
Expand Down
4 changes: 2 additions & 2 deletions packages/syft-datasets/src/syft_datasets/file_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import shutil
from pathlib import Path
from typing import Iterator
from typing import Iterable


def copy_dir_contents(
Expand All @@ -15,7 +15,7 @@ def copy_dir_contents(
return copy_paths(files, dst, exists_ok)


def copy_paths(files: Iterator[Path], dst: Path, exists_ok: bool = False) -> list[Path]:
def copy_paths(files: Iterable[Path], dst: Path, exists_ok: bool = False) -> list[Path]:
"""
Copy a list of files to a destination directory.
If `dst` does not exist, it will be created.
Expand Down
38 changes: 38 additions & 0 deletions packages/syft-datasets/tests/test_create_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""A create with a bad source path copies nothing, so a retry can reuse the name."""

from pathlib import Path

import pytest

from syft_datasets.dataset_manager import SyftDatasetManager


@pytest.mark.parametrize(
"key,bad_name,error",
[
("private_path", "missing.csv", ValueError),
("readme_path", "missing.md", FileNotFoundError),
("readme_path", "README.txt", ValueError),
],
)
def test_bad_source_copies_nothing_and_retry_works(
tmp_path: Path, key: str, bad_name: str, error: type[Exception]
):
source = tmp_path / "source"
source.mkdir()
for name in ("mock.csv", "private.csv", "README.md", "README.txt"):
(source / name).write_text(name)
paths = {
"mock_path": source / "mock.csv",
"private_path": source / "private.csv",
"readme_path": source / "README.md",
}
syftbox = tmp_path / "SyftBox"
manager = SyftDatasetManager(syftbox, "owner@test.org")

with pytest.raises(error):
manager.create(name="demo", **{**paths, key: source / bad_name})
assert not syftbox.exists()

dataset = manager.create(name="demo", **paths)
assert [f.name for f in dataset.private_files] == ["private.csv"]
Loading