File size: 2,210 Bytes
44459bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""Helper methods for handling paths."""

from pathlib import Path
from typing import Iterable


def extract_files(paths: list[Path]) -> list[Path]:
    """Extract all the files paths from a list of file or directory paths.

    If a directory path is in the list, all its files are extracted.

    Args:
        paths (list[Path]): List of custom file path or directory containing custom files.

    Returns:
        list[Path]: List of extracted path.
    """
    extracted_paths: list[Path] = []
    for path in paths:
        if path.is_dir():
            extracted_paths += [file for file in path.iterdir() if file.is_file()]
        else:
            extracted_paths.append(path)
    return extracted_paths


def validate_path(
    path: str | Path,
    is_file: bool = False,
    is_dir: bool = False,
    file_suffix: Iterable[str] | None = None,
) -> Path:
    """Helper method to check a path existence and other constraints.

    By defaut, a path existence check will be made and the path must point to either a file or a directory.

    Args:
        path (str | Path): Path to check.
        is_file (bool, optional): Validate path leads to a file. Defaults to False.
        is_dir (bool, optional): Validate path leads to a directory. Defaults to False.
        file_suffix (Iterable[str] | None, optional): Validate file suffix must be in specified list. Defaults to None.
    """
    path = Path(path)

    if not path.exists():
        raise FileNotFoundError(f"The path {path} does not exist.")

    if not (path.is_file() or path.is_dir()):
        raise ValueError(f"The path {path} is neither a file or a directory.")

    if is_file:
        if not path.is_file():
            raise FileNotFoundError(f"The path {path} is not a file.")
        if file_suffix is not None and not (
            (path.suffix in file_suffix) or ("".join(path.suffixes) in file_suffix)
        ):
            raise ValueError(
                f"Unsupported suffix '{''.join(path.suffixes)}' for path {path}. "
                f"Supported are {tuple(file_suffix)}."
            )
    elif is_dir and not path.is_dir():
        raise NotADirectoryError(f"The path {path} is not a directory.")
    return path