97 lines
3.2 KiB
Python
97 lines
3.2 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
from typing import Self
|
|
from os.path import isfile as is_file, isdir as is_directory, exists as path_exists
|
|
from os import unlink as delete_path, mkdir as make_directory
|
|
from Abstracts.FilesAbstract import FilesAbstract
|
|
from Abstracts.ModelAbstract import ModelAbstract
|
|
from Utils.Checks import Check
|
|
|
|
class FilesDriver(FilesAbstract, ModelAbstract):
|
|
|
|
def get_absolute_path(self:Self, path:str) -> str|None:
|
|
|
|
root_path:str
|
|
|
|
for root_path in self._root_paths:
|
|
|
|
absolute_path:str = self.fix_path((root_path + self._slash + path) if root_path else path)
|
|
|
|
if path_exists(absolute_path):
|
|
return absolute_path
|
|
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_path:str|None = self.get_absolute_path(path)
|
|
|
|
return is_file(absolute_path) if absolute_path else False
|
|
|
|
def is_directory(self:Self, path:str) -> bool:
|
|
|
|
absolute_path:str|None = self.get_absolute_path(path)
|
|
|
|
return is_directory(absolute_path) if absolute_path else False
|
|
|
|
def load(self:Self, path:str, mode:str = "r") -> str|bytes|None:
|
|
|
|
absolute_path:str|None = self.get_absolute_path(path)
|
|
|
|
if absolute_path:
|
|
try:
|
|
with open(absolute_path, mode) as file:
|
|
return file.read()
|
|
except Exception as exception:
|
|
self.anp.exception(exception, "anp_files_driver_load_exception", {
|
|
"path" : path,
|
|
"absolute_path" : absolute_path,
|
|
"mode" : mode
|
|
})
|
|
return None
|
|
|
|
def make_directory(self:Self, path:str) -> bool:
|
|
try:
|
|
make_directory(path)
|
|
return True
|
|
except Exception as exception:
|
|
self.anp.exception(exception, "anp_files_driver_make_directory_exception", {
|
|
"path" : path
|
|
})
|
|
return False
|
|
|
|
def save(self:Self, path:str, content:str|bytes) -> bool:
|
|
|
|
directory:str = self.get_parent(path)
|
|
|
|
if self.exists(directory) or self.make_directory(directory):
|
|
try:
|
|
with open(self.fix_path(path), (
|
|
"wb" if Check.is_binary(content) else
|
|
"w")) as file:
|
|
file.write(content)
|
|
return True
|
|
except Exception as exception:
|
|
self.anp.exception(exception, "anp_files_driver_save_exception", {
|
|
"path" : path,
|
|
"mode" : "wb" if Check.is_binary(content) else "w"
|
|
})
|
|
return False
|
|
|
|
def delete(self:Self, path:str) -> bool:
|
|
|
|
absolute_path:str|None = self.get_absolute_path(path)
|
|
|
|
if absolute_path:
|
|
try:
|
|
delete_path(absolute_path)
|
|
return True
|
|
except Exception as exception:
|
|
self.anp.exception(exception, "anp_files_driver_delete_exception", {
|
|
"path" : path,
|
|
"absolute_path" : absolute_path
|
|
})
|
|
return False |