OpoTests/Python/Drivers/FilesDriver.py

61 lines
1.8 KiB
Python

#!/usr/bin/env python3
from typing import Self
from Interfaces.OpoTestsInterface import OpoTestsInterface
from os.path import dirname as directory_name
from os.path import abspath as path_absolute
from os.path import exists as path_exists
from os.path import isfile as is_file
from Utils.Patterns import RE
import mimetypes
class FilesDriver:
def __init__(self:Self, ot:OpoTestsInterface) -> None:
self.ot:OpoTestsInterface = ot
self.__root_paths:tuple[str] = ("", directory_name(path_absolute(__file__)))
self.__slash:str = "/" if "/" in self.__root_paths[1] else "\\"
for _ in range(3):
self.__root_paths += (self.__root_paths[-1] + self.__slash + "..",)
mimetypes.init()
def fix_path(self:Self, path:str) -> str:
return RE.SLASHES.sub(self.__slash, path)
def get_absolute_path(self:Self, path:str) -> str|None:
root:str
path = self.fix_path(path)
for root in self.__root_paths:
absolute_path:str = self.fix_path(root + self.__slash + path)
if path_exists(absolute_path):
return absolute_path
return None
def load(self:Self, path:str) -> bytes|None:
absolute:str = self.get_absolute_path(path)
if absolute and is_file(absolute):
try:
with open(absolute, "rb") as file:
return file.read()
except Exception as exception:
print(["files_load", exception])
return None
def get_mime(self:Self, path:str) -> str|None:
absolute:str|None = self.get_absolute_path(path) or path
mime:str|None = None
if absolute and is_file(absolute):
mime = mimetypes.guess_type(absolute)[0]
if mime is None:
mime = "application/octet-stream"
return mime