| 1 |
import pathlib |
| 2 |
from collections.abc import Iterable, Sequence |
| 3 |
from typing import Any |
| 4 |
|
| 5 |
from attrs import field |
| 6 |
|
| 7 |
from cyclopts.utils import frozen, to_tuple_converter |
| 8 |
|
| 9 |
|
| 10 |
def ext_converter(value: str | Iterable[str] | None) -> tuple[str, ...]: |
| 11 |
return tuple(e.lower().lstrip(".") for e in to_tuple_converter(value)) |
| 12 |
|
| 13 |
|
| 14 |
@frozen(kw_only=True) |
| 15 |
class Path: |
| 16 |
"""Assertions on properties of :class:`pathlib.Path`. |
| 17 |
|
| 18 |
Example Usage: |
| 19 |
|
| 20 |
.. code-block:: python |
| 21 |
|
| 22 |
from cyclopts import App, Parameter, validators |
| 23 |
from pathlib import Path |
| 24 |
from typing import Annotated |
| 25 |
|
| 26 |
app = App() |
| 27 |
|
| 28 |
|
| 29 |
@app.default |
| 30 |
def main( |
| 31 |
# ``src`` must be a file that exists. |
| 32 |
src: Annotated[Path, Parameter(validator=validators.Path(exists=True, dir_okay=False))], |
| 33 |
# ``dst`` must be a path that does **not** exist. |
| 34 |
dst: Annotated[Path, Parameter(validator=validators.Path(dir_okay=False, file_okay=False))], |
| 35 |
): |
| 36 |
"Copies src->dst." |
| 37 |
dst.write_bytes(src.read_bytes()) |
| 38 |
|
| 39 |
|
| 40 |
app() |
| 41 |
|
| 42 |
.. code-block:: console |
| 43 |
|
| 44 |
$ my-script foo.bin bar.bin # if foo.bin does not exist |
| 45 |
╭─ Error ───────────────────────────────────────────────────────╮ |
| 46 |
│ Invalid value "foo.bin" for "SRC". "foo.bin" does not exist. │ |
| 47 |
╰───────────────────────────────────────────────────────────────╯ |
| 48 |
|
| 49 |
$ my-script foo.bin bar.bin # if bar.bin exists |
| 50 |
╭─ Error ───────────────────────────────────────────────────────╮ |
| 51 |
│ Invalid value "bar.bin" for "DST". "bar.bin" already exists. │ |
| 52 |
╰───────────────────────────────────────────────────────────────╯ |
| 53 |
""" |
| 54 |
|
| 55 |
exists: bool = False |
| 56 |
"""If :obj:`True`, specified path **must** exist. Defaults to :obj:`False`.""" |
| 57 |
|
| 58 |
file_okay: bool = True |
| 59 |
""" |
| 60 |
If path exists, check it's type: |
| 61 |
|
| 62 |
* If :obj:`True`, specified path may be an **existing** file. |
| 63 |
|
| 64 |
* If :obj:`False`, then **existing** files are not allowed. |
| 65 |
|
| 66 |
Defaults to :obj:`True`. |
| 67 |
""" |
| 68 |
|
| 69 |
dir_okay: bool = True |
| 70 |
""" |
| 71 |
If path exists, check it's type: |
| 72 |
|
| 73 |
* If :obj:`True`, specified path may be an **existing** directory. |
| 74 |
|
| 75 |
* If :obj:`False`, then **existing** directories are not allowed. |
| 76 |
|
| 77 |
Defaults to :obj:`True`. |
| 78 |
""" |
| 79 |
|
| 80 |
|
| 81 |
ext: str | Sequence[str] = field(default=None, converter=ext_converter) |
| 82 |
""" |
| 83 |
Supplied path must have this extension (case insensitive). |
| 84 |
May or may not include the ".". |
| 85 |
""" |
| 86 |
|
| 87 |
def __attrs_post_init__(self): |
| 88 |
if self.exists and not self.file_okay and not self.dir_okay: |
| 89 |
raise ValueError("(exists=True, file_okay=False, dir_okay=False) is an invalid configuration.") |
| 90 |
|
| 91 |
def __call__(self, type_: Any, path: Any): |
| 92 |
if isinstance(path, Sequence): |
| 93 |
if isinstance(path, str): |
| 94 |
raise TypeError |
| 95 |
|
| 96 |
for p in path: |
| 97 |
self(type_, p) |
| 98 |
else: |
| 99 |
if not isinstance(path, pathlib.Path): |
| 100 |
return |
| 101 |
|
| 102 |
if self.ext and path.suffix.lower().lstrip(".") not in self.ext: |
| 103 |
if len(self.ext) == 1: |
| 104 |
raise ValueError(f'"{path}" must have extension "{self.ext[0]}".') |
| 105 |
else: |
| 106 |
pretty_ext = "{" + ", ".join(f'"{x}"' for x in self.ext) + "}" |
| 107 |
raise ValueError(f'"{path}" does not match one of supported extensions {pretty_ext}.') |
| 108 |
|
| 109 |
if path.exists(): |
| 110 |
if not self.file_okay and path.is_file(): |
| 111 |
if self.dir_okay: |
| 112 |
raise ValueError(f'Only directory is allowed, but "{path}" is a file.') |
| 113 |
else: |
| 114 |
raise ValueError(f'"{path}" already exists.') |
| 115 |
|
| 116 |
if not self.dir_okay and path.is_dir(): |
| 117 |
if self.file_okay: |
| 118 |
raise ValueError(f'Only file is allowed, but "{path}" is a directory.') |
| 119 |
else: |
| 120 |
raise ValueError(f'"{path}" already exists.') |
| 121 |
elif self.exists: |
| 122 |
raise ValueError(f'"{path}" does not exist.') |