Skip to content

Commit

Permalink
delete file or directory-tree
Browse files Browse the repository at this point in the history
  • Loading branch information
d-chris committed Jan 2, 2024
1 parent 82fd5dd commit 6671371
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
- `Path().size()` to get size in bytes of a file or directory
- `Path().read_lines()` to yield over all lines from a file until EOF
- `contextmanager` to change current working directory with `with` statement

- `Path().copy()` copy a file or directory to a new path destination
- `Path().delete()` delete a file or directory-tree

## Installation

```bash
Expand Down
18 changes: 18 additions & 0 deletions pathlibutil/path.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import errno
import hashlib
import os
import pathlib
Expand Down Expand Up @@ -117,3 +118,20 @@ def copy(self, dst: str, exist_ok: bool = True, **kwargs) -> 'Path':
)

return Path(_path)

def delete(self, *, recursive: bool = False, missing_ok: bool = False, **kwargs) -> None:
"""
Deletes the file or directory.
"""
try:
self.rmdir()
except NotADirectoryError:
self.unlink(missing_ok)
except FileNotFoundError as e:
if not missing_ok:
raise e
except OSError as e:
if not recursive or e.errno != errno.ENOTEMPTY:
raise e

shutil.rmtree(self, **kwargs)
34 changes: 34 additions & 0 deletions tests/test_shutil.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import pytest
import shutil
import pathlib

from pathlibutil import Path


@pytest.fixture
def tmp_dirpath(file: Path, cls: Path, tmp_path: pathlib.Path):

shutil.copy(file, tmp_path)

yield cls(tmp_path)


def test_copy_file(file: Path, tmp_path: pathlib.Path):
assert hasattr(Path, 'copy')

Expand Down Expand Up @@ -51,3 +60,28 @@ def test_copy_raises(file: Path, tmp_path: pathlib.Path):
def test_copy_mkdir(file: Path, tmp_path: pathlib.Path):
with pytest.raises(FileNotFoundError):
file.copy(tmp_path / 'not-exists')


def test_delete(file: Path, tmp_path: pathlib.Path):
assert hasattr(Path, 'delete')

p = file.copy(tmp_path)

p.delete()
assert not p.exists()

with pytest.raises(FileNotFoundError):
p.delete()


def test_delete_directory(tmp_dirpath: Path):

with pytest.raises(OSError):
tmp_dirpath.delete()

with pytest.raises(TypeError):
tmp_dirpath.delete(True)

tmp_dirpath.delete(recursive=True)

assert not tmp_dirpath.exists()

0 comments on commit 6671371

Please sign in to comment.