Skip to content

Commit ceca708

Browse files
authored
Merge pull request #35 from sgaisser/gaisser_filestore_create_folders
Create folders if they do not exist
2 parents 6a557f7 + 4ae0f69 commit ceca708

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1212

1313
- Added `RestrictedFilestore` to limit the file access of the `NativeFilestore` to a specific
1414
directory.
15+
- `Filestore` creates a directory if it does not exist when creating a new file.
1516

1617
## Fixed
1718

src/cfdppy/filestore.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,8 @@ def create_file(self, file: Path) -> FilestoreResponseStatusCode:
238238
_LOGGER.warning("File already exists")
239239
return FilestoreResponseStatusCode.CREATE_NOT_ALLOWED
240240
try:
241+
# Creates subfolders if they do not exist
242+
file.parent.mkdir(exist_ok=True, parents=True)
241243
with open(file, "x"):
242244
pass
243245
return FilestoreResponseStatusCode.CREATE_SUCCESS

tests/test_restricted_filestore.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,27 @@ def test_handle_files(self):
4343
self.assertEqual(result, FilestoreResponseStatusCode.DELETE_SUCCESS)
4444
self.assertFalse(Path(tempdir).joinpath("renamed_file.txt").exists())
4545

46+
def test_create_folder_with_file(self):
47+
with tempfile.TemporaryDirectory() as tempdir:
48+
filestore = RestrictedFilestore(restricted_path=Path(tempdir))
49+
new_dir = Path(tempdir).joinpath("new_dir")
50+
self.assertFalse(new_dir.exists())
51+
result = filestore.create_file(new_dir.joinpath("a_file.txt"))
52+
self.assertEqual(FilestoreResponseStatusCode.CREATE_SUCCESS, result)
53+
self.assertTrue(new_dir.exists())
54+
self.assertTrue(new_dir.joinpath("a_file.txt").exists())
55+
56+
# Create more than one folder
57+
first_folder = Path(tempdir).joinpath("first_folder")
58+
second_folder = first_folder.joinpath("second_folder")
59+
self.assertFalse(first_folder.exists())
60+
self.assertFalse(second_folder.exists())
61+
result = filestore.create_file(second_folder.joinpath("a_file.txt"))
62+
self.assertEqual(FilestoreResponseStatusCode.CREATE_SUCCESS, result)
63+
self.assertTrue(first_folder.exists())
64+
self.assertTrue(second_folder.exists())
65+
self.assertTrue(second_folder.joinpath("a_file.txt").exists())
66+
4667
def test_handle_directories(self):
4768
with tempfile.TemporaryDirectory() as tempdir:
4869
filestore = RestrictedFilestore(restricted_path=Path(tempdir))

0 commit comments

Comments
 (0)