Skip to content

Commit e347d11

Browse files
authored
Merge pull request #2325 from gitpython-developers/fix/current-directory-file-parent
fix/current directory file parent
2 parents ec12459 + afbbabf commit e347d11

2 files changed

Lines changed: 45 additions & 1 deletion

File tree

‎git/util.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ def assure_directory_exists(path: PathLike, is_file: bool = False) -> bool:
402402
``True`` if the directory was created, ``False`` if it already existed.
403403
"""
404404
if is_file:
405-
path = osp.dirname(path)
405+
path = osp.dirname(path) or osp.curdir
406406
# END handle file
407407
if not osp.isdir(path):
408408
os.makedirs(path, exist_ok=True)

‎test/test_assure_directory.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from pathlib import Path
2+
3+
import pytest
4+
5+
from git.util import assure_directory_exists
6+
from test.lib.fixtures import writable_fixture
7+
8+
9+
@pytest.fixture
10+
def directory_fixture(monkeypatch):
11+
with writable_fixture("empty.sh") as temporary:
12+
directory = temporary.path().resolve()
13+
with monkeypatch.context() as context:
14+
context.chdir(directory)
15+
yield directory
16+
17+
18+
@pytest.mark.parametrize("path_type", [str, Path])
19+
def test_file_in_current_directory_already_has_parent(directory_fixture, path_type):
20+
assert assure_directory_exists(path_type("notes.txt"), is_file=True) is False
21+
assert not (directory_fixture / "notes.txt").exists()
22+
23+
24+
@pytest.mark.parametrize("path_type", [str, Path])
25+
def test_nested_file_creates_only_missing_parent_directories(directory_fixture, path_type):
26+
filename = path_type("new/nested/notes.txt")
27+
assert assure_directory_exists(filename, is_file=True) is True
28+
assert (directory_fixture / "new/nested").is_dir()
29+
assert not (directory_fixture / "new/nested/notes.txt").exists()
30+
assert assure_directory_exists(filename, is_file=True) is False
31+
32+
33+
@pytest.mark.parametrize("path_type", [str, Path])
34+
def test_existing_directory_is_unchanged(directory_fixture, path_type):
35+
(directory_fixture / "existing").mkdir()
36+
assert assure_directory_exists(path_type("existing")) is False
37+
38+
39+
@pytest.mark.parametrize("path_type", [str, Path])
40+
def test_file_cannot_be_used_as_parent_directory(directory_fixture, path_type):
41+
(directory_fixture / "blocked").write_text("occupied\n")
42+
with pytest.raises(FileExistsError):
43+
assure_directory_exists(path_type("blocked/notes.txt"), is_file=True)
44+
assert (directory_fixture / "blocked").read_text() == "occupied\n"

0 commit comments

Comments
 (0)