Skip to content

Path

get_directories_with_file(paths, filename, leafs_only=False)

Find all directories in the given paths that contain a file with the specified filename.

Parameters:

Name Type Description Default
paths str | list[str] | None

List of paths.

required
filename str

Name of the file to search for in the directories.

required
leafs_only bool

If True, only return the leaf directories (i.e., those that are not parents of other directories in the list).

False

Returns: List of directory paths where each directory contains the specified filename.

Source code in src/kibad_llm/utils/path.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def get_directories_with_file(
    paths: str | list[str] | None, filename: str, leafs_only: bool = False
) -> list[str]:
    """Find all directories in the given paths that contain a file with the specified filename.

    Args:
        paths: List of paths.
        filename: Name of the file to search for in the directories.
        leafs_only: If True, only return the leaf directories (i.e., those that are not
            parents of other directories in the list).
    Returns:
        List of directory paths where each directory contains the specified filename.
    """
    # this is required so that the resolver does not fail when no input is given (non multirun case)
    if paths is None:
        return []

    if isinstance(paths, str):
        paths = [paths]

    result_paths = []
    for path in paths:
        # raise an error if path contains glob patterns
        if any(char in path for char in "*?[]{}"):
            raise ValueError(
                f"Path '{path}' contains glob patterns. Please provide explicit paths without glob patterns."
            )
        current_paths = Path(path).glob(f"**/{filename}")
        for p in current_paths:
            result_paths.extend([p.parent])

    # deduplicate and sort
    result_paths = sorted(set(result_paths))

    # filter to only keep leaf directories if requested
    if leafs_only:
        result_paths = [
            p
            for p in result_paths
            if not any(other != p and other.is_relative_to(p) for other in result_paths)
        ]

    result = [str(p) for p in result_paths]
    return result