Skip to content

Commit ee795b6

Browse files
committed
add util.ensure_dir for quick and easy creation of work directories
1 parent 3a04029 commit ee795b6

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

openeo/util.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import re
66
from datetime import datetime, date
77
from typing import Any, Union, Tuple, Callable
8+
from pathlib import Path
89

910
_rfc3339_date_format = re.compile(r'\d{4}-\d{2}-\d{2}')
1011

@@ -34,6 +35,15 @@ def first_not_none(*args):
3435
raise ValueError("No not-None values given.")
3536

3637

38+
def ensure_dir(path: Union[str, Path]) -> Path:
39+
"""Create directory if it doesn't exist."""
40+
path = Path(path)
41+
if not path.exists():
42+
path.mkdir(parents=True, exist_ok=True)
43+
assert path.is_dir()
44+
return path
45+
46+
3747
def ensure_list(x):
3848
"""Convert given data structure to a list."""
3949
try:

tests/test_util.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import logging
2+
import os
3+
import pathlib
24
import re
35
from datetime import datetime
46

57
import pytest
68

7-
from openeo.util import first_not_none, get_temporal_extent, TimingLogger, ensure_list
9+
from openeo.util import first_not_none, get_temporal_extent, TimingLogger, ensure_list, ensure_dir
810

911

1012
@pytest.mark.parametrize(['input', 'expected'], [
@@ -43,6 +45,27 @@ def test_ensure_list(input, expected):
4345
assert ensure_list(input) == expected
4446

4547

48+
def test_ensure_dir_str(tmp_path):
49+
work_dir = str(tmp_path / "work/data/foo")
50+
assert not os.path.exists(work_dir)
51+
p = ensure_dir(work_dir)
52+
assert os.path.exists(work_dir)
53+
assert isinstance(p, pathlib.Path)
54+
assert p.exists()
55+
assert str(p) == str(work_dir)
56+
57+
58+
def test_ensure_dir_pathlib(tmp_path):
59+
# Note: tmp_path might be pathlib2
60+
work_dir = pathlib.Path(str(tmp_path / "work/data/foo"))
61+
assert not work_dir.exists()
62+
p = ensure_dir(work_dir)
63+
assert work_dir.exists()
64+
assert isinstance(p, pathlib.Path)
65+
assert p.exists()
66+
assert str(p) == str(work_dir)
67+
68+
4669
def test_get_temporal_extent():
4770
assert get_temporal_extent("2019-03-15") == ("2019-03-15", None)
4871
assert get_temporal_extent("2019-03-15", "2019-10-11") == ("2019-03-15", "2019-10-11")

0 commit comments

Comments
 (0)