Skip to content

Commit 94f2c36

Browse files
committed
Move only-item logic to a separate function _get_only_item_in_dir()
Signed-off-by: Bram Stoeller <bram.stoeller@alliander.com>
1 parent d5daa30 commit 94f2c36

File tree

1 file changed

+30
-10
lines changed
  • src/power_grid_model_io/utils

1 file changed

+30
-10
lines changed

src/power_grid_model_io/utils/zip.py

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,17 +63,37 @@ def extract(src_file_path: Path, dst_dir_path: Optional[Path] = None, skip_if_ex
6363

6464
# Zip files often contain a single directory with the same name as the zip file.
6565
# In that case, return the dir to that directory instead of the root dir
66-
only_item: Optional[Path] = None
67-
for item in dst_dir_path.iterdir():
68-
# If only_item is None, this is the first iteration, so item may be the only item
69-
if only_item is None:
70-
only_item = item
71-
# Else, if only_item is not None, there are more than one items in the root of the directory.
72-
# This means that there is no 'only_item' and we can stop the loop
73-
else:
74-
only_item = None
75-
break
66+
only_item = _get_only_item_in_dir(dst_dir_path)
7667
if only_item and only_item.is_dir() and only_item.name == src_file_path.stem:
7768
dst_dir_path = only_item
7869

7970
return dst_dir_path.resolve()
71+
72+
73+
def _get_only_item_in_dir(dir_path: Path) -> Optional[Path]:
74+
"""
75+
If dir path contains only a single item, return that item.
76+
Return None otherwise (if there are no items at all, or more than one item).
77+
78+
Args:
79+
dir_path: The path tho the directory
80+
81+
Returns:
82+
A path to the only item (dir or file) in the directory
83+
"""
84+
85+
only_item: Optional[Path] = None
86+
for item in dir_path.iterdir():
87+
88+
# If only_item is not None at this point, it must have been set in the first iteration, i.e. there are more
89+
# than one items in the directory, so return None.
90+
if only_item is not None:
91+
return None
92+
93+
# Else, if only_item is None, we are in the first iteration, i.e. the first item in the dir. This item may be
94+
# the only item in the dir, so let's remember it.
95+
only_item = item
96+
97+
# If we have come to this point, there were zero or one items in the directory. Return the path to that item (or
98+
# None, the initial value).
99+
return only_item

0 commit comments

Comments
 (0)