add option to return inclusive path for iterative search, closes #1

This commit is contained in:
Florian Förster 2025-04-03 13:42:36 +02:00
parent 23dc0a9fdd
commit d79683b8b2
2 changed files with 18 additions and 7 deletions

View File

@ -178,17 +178,23 @@ def search_file_iterative(
def search_folder_path(
starting_path: Path,
stop_folder_name: str | None = None,
stop_folder_name: str,
return_inclusive: bool = False,
) -> Path | None:
"""Iteratively searches the parent directories of the starting path
and look for folders matching the given name. If a match is encountered,
the parent path will be returned.
the parent path will be returned, if ``return_inclusive`` = False (default).
Otherwise the path contains the given stop folder name.
Example:
``return_inclusive`` = False
starting_path = path/to/start/folder
stop_folder_name = 'to'
returned path = 'path/'
``return_inclusive`` = True
returned path = 'path/to'
Parameters
----------
starting_path : Path
@ -204,13 +210,15 @@ def search_folder_path(
stop_folder_path: Path | None = None
base_path: Path | None = None
for search_path in starting_path.parents:
if stop_folder_name is not None and search_path.name == stop_folder_name:
if search_path.name == stop_folder_name:
# library is placed inside a whole python installation for deployment
# only look up to this folder
stop_folder_path = search_path
break
if stop_folder_path is not None:
if stop_folder_path is not None and return_inclusive:
base_path = stop_folder_path
elif stop_folder_path is not None:
base_path = stop_folder_path.parent
return base_path

View File

@ -263,6 +263,9 @@ def test_search_folder_path(base_folder):
found = io.search_folder_path(base_folder, stop_folder_name=stop_folder)
assert found is not None
assert found.name == "path"
stop_folder = None
found = io.search_folder_path(base_folder, stop_folder_name=stop_folder)
assert found is None
found = io.search_folder_path(
base_folder, stop_folder_name=stop_folder, return_inclusive=True
)
assert found is not None
assert found.name == "to"
assert found.parent.name == "path"