From d79683b8b238061130767fb5469de6e0eed8d589 Mon Sep 17 00:00:00 2001 From: foefl Date: Thu, 3 Apr 2025 13:42:36 +0200 Subject: [PATCH] add option to return inclusive path for iterative search, closes #1 --- src/dopt_basics/io.py | 16 ++++++++++++---- tests/test_io.py | 9 ++++++--- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/dopt_basics/io.py b/src/dopt_basics/io.py index ef1d573..94af8b1 100644 --- a/src/dopt_basics/io.py +++ b/src/dopt_basics/io.py @@ -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 diff --git a/tests/test_io.py b/tests/test_io.py index a9fb3b3..5b716d2 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -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"