#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import Self, Any, Optional, Sequence from os.path import exists as path_exists, isfile as is_file, isdir as is_directory, dirname as directory_name, abspath as absolute_path from io import FileIO from json import loads as json_decode from Interfaces.Application.AIChatInterface import AIChatInterface from Utils.Patterns import RE class FilesDriver: ROOT:str = directory_name(absolute_path(__file__)) SLASH:str = "/" if "/" in ROOT else "\\\\" def __init__(self:Self, aichat:AIChatInterface) -> None: self.aichat:AIChatInterface = aichat self.__root_paths:list[str] = ["", self.ROOT] for _ in range(2): self.__root_paths.append(RE.PARENT_DIRECTORY.sub(r'\1', self.__root_paths[-1])) @classmethod def fix_path(cls:type[Self], path:str) -> str: return RE.SLASHES.sub(cls.SLASH, path) def get_absolute_path(self:Self, path:str) -> str|None: root:str for root in self.__root_paths: absolute:str = self.fix_path((root + self.slash if root else "") + path) if path_exists(absolute): return absolute return None def exists(self:Self, path:str) -> bool: return self.get_absolute_path(path) is not None def is_file(self:Self, path:str) -> bool: absolute:str = self.get_absolute_path(path) return is_file(absolute) if absolute else False def is_directory(self:Self, path:str) -> bool: absolute:str = self.get_absolute_path(path) return is_directory(absolute) if absolute else False def load(self:Self, path:str, mode:str = "r") -> str|bytes|None: absolute:str = self.get_absolute_path(path) if absolute and is_file(absolute): file:FileIO try: with open(absolute, mode) as file: return file.read() except Exception as exception: pass return None def load_json(self:Self, path:str) -> str|bytes|None: json:Sequence[Any]|dict[str, Any|None]|None try: json = json_decode(path) if json != None: return json except Exception as exception: pass data:str|None = self.load(path) if data: try: return json_decode(data) except Exception as exception: pass return None def save(self:Self, path:str, content:str|bytes, mode:str = "w") -> bool: try: file:FileIO with open(self.fix_path(path), mode) as file: file.write(content) return True except Exception as exception: pass return False