from pathlib import Path from typing import Optional from dotenv import dotenv_values class DirManager: """Manages directories for the tests and should be used to create and find and use the correct directories. The structures is as follows: tests dir/ session_id-1/ results states status session_id-2/ results ... """ def __init__(self, output_dir: Path | str, session_id: str, recipes_dir: Path | str = ""): if isinstance(output_dir, str): output_dir = Path(output_dir) self.output_dir = output_dir.resolve() self.session_id = session_id if isinstance(recipes_dir, str): recipes_dir = Path(recipes_dir) self.recipes_dir = recipes_dir def create_all_dirs(self) -> None: dirs: list[Path] = [ self.OUTPUT_DIR, self.SESSION, self.STATES, self.ENV_FILES, self.RESULTS, self.HTML, self.STATUS, ] for d in dirs: d.mkdir(exist_ok=True) @property def OUTPUT_DIR(self): return self.output_dir @property def SESSION(self): return self.OUTPUT_DIR / self.session_id @property def STATES(self): return self.SESSION / "states" @property def ENV_FILES(self): return self.STATES / "env_files" @property def RESULTS(self): return self.SESSION / "results" @property def HTML(self): return self.RESULTS / "html" @property def STATUS(self): return self.SESSION / "status" @property def RECIPES(self): return self.recipes_dir def get_config(self, search_string: str) -> dict[str, str]: env_file = next(self.ENV_FILES.glob(f"*{search_string}*")) config: dict[str, str] = dotenv_values(env_file) # type: ignore return config @staticmethod def get_latest_session_id(output_dir: Path) -> Optional[str]: """returns the name of the newest dir inside of output_dir if output_dir does not exists or is empty, None is returned""" if not output_dir.is_dir(): return None all_dirs = [d for d in output_dir.iterdir() if d.is_dir()] if all_dirs: newest_dir: Path = max(all_dirs, key=lambda x: x.stat().st_ctime) return newest_dir.name else: return None