diff --git a/lib/spack/spack/llnl/util/filesystem.py b/lib/spack/spack/llnl/util/filesystem.py index eba14481a01caf..1ddfa6a093c30a 100644 --- a/lib/spack/spack/llnl/util/filesystem.py +++ b/lib/spack/spack/llnl/util/filesystem.py @@ -1812,6 +1812,15 @@ def _dedupe_files(paths: List[str]) -> List[str]: return unique_files +def _is_root_directory(curr_dir: str): + """ + Check if the given directory is the top-level root directory. + Works on Windows, macOS, and Linux. + """ + path = pathlib.Path(curr_dir).resolve() + return path == path.anchor or path.parent == path + + def _find_max_depth( roots: Sequence[Path], globs: Sequence[str], max_depth: int = sys.maxsize ) -> List[str]: @@ -1846,6 +1855,9 @@ def _find_max_depth( while dir_queue: depth, curr_dir = dir_queue.pop() + # Never traverse root recursively + if _is_root_directory(curr_dir): + continue try: dir_iter = os.scandir(curr_dir) except OSError as e: