Skip to content

Commit e0f94d0

Browse files
committed
Add path_from helper context manager
1 parent 1a9990a commit e0f94d0

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

src/zimscraperlib/filesystem.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
import os
66
import pathlib
7+
from contextlib import contextmanager
8+
from tempfile import TemporaryDirectory
9+
from typing import Any
710

811
import magic
912

@@ -41,3 +44,20 @@ def delete_callback(fpath: str | pathlib.Path):
4144
"""helper deleting passed filepath"""
4245

4346
os.unlink(fpath)
47+
48+
49+
@contextmanager
50+
def path_from(path: pathlib.Path | TemporaryDirectory[Any] | str):
51+
"""Context manager to get a Path from a path as string, Path or TemporaryDirectory
52+
53+
Since scraperlib wants to manipulate only Path, scrapers might often needs this
54+
to create a path from what they have, especially since TemporaryDirectory context
55+
manager returns a string which is not really handy.
56+
"""
57+
if isinstance(path, pathlib.Path):
58+
yield path
59+
elif isinstance(path, TemporaryDirectory):
60+
with path as pathname:
61+
yield pathlib.Path(pathname)
62+
else:
63+
yield pathlib.Path(path)

tests/filesystem/test_filesystem.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import pathlib
2+
from tempfile import TemporaryDirectory
23
from typing import Any
34

45
import magic
@@ -8,6 +9,7 @@
89
delete_callback,
910
get_content_mimetype,
1011
get_file_mimetype,
12+
path_from,
1113
)
1214

1315

@@ -54,3 +56,42 @@ def test_delete_callback(tmp_path: pathlib.Path):
5456
delete_callback(fpath)
5557

5658
assert not fpath.exists()
59+
60+
61+
def test_path_from_tmp_dir():
62+
tempdir = TemporaryDirectory()
63+
with path_from(tempdir) as tmp_dir:
64+
file = tmp_dir / "file.txt"
65+
file.touch()
66+
assert file.exists()
67+
assert pathlib.Path(tempdir.name).exists()
68+
69+
assert not pathlib.Path(tempdir.name).exists()
70+
71+
72+
def test_path_from_path():
73+
tempdir = TemporaryDirectory()
74+
tempdir_path = pathlib.Path(tempdir.name)
75+
with path_from(tempdir_path) as tmp_dir:
76+
file = tmp_dir / "file.txt"
77+
file.touch()
78+
assert file.exists()
79+
assert pathlib.Path(tempdir.name).exists()
80+
81+
assert pathlib.Path(tempdir.name).exists()
82+
tempdir.cleanup()
83+
assert not pathlib.Path(tempdir.name).exists()
84+
85+
86+
def test_path_from_str():
87+
tempdir = TemporaryDirectory()
88+
tempdir_path = pathlib.Path(tempdir.name)
89+
with path_from(str(tempdir_path)) as tmp_dir:
90+
file = tmp_dir / "file.txt"
91+
file.touch()
92+
assert file.exists()
93+
assert pathlib.Path(tempdir.name).exists()
94+
95+
assert pathlib.Path(tempdir.name).exists()
96+
tempdir.cleanup()
97+
assert not pathlib.Path(tempdir.name).exists()

0 commit comments

Comments
 (0)