dockge-cli/dockge_cli/service/storage.py

75 lines
2.2 KiB
Python

import os
import pathlib
import base64
import yaml
_storagepath = pathlib.Path(__file__).parents[1] / ".temp"
_file = _storagepath / "storage.yaml"
_storagepath.mkdir(exist_ok=True, parents=True)
def fileexists():
"""
Checks if storage file does exist, creates it when necessary
"""
if not _file.exists():
with open(_file, 'a', encoding="utf-8"):
os.utime(_file, None)
def exists(key: str) -> bool:
"""
Checks if a given key exists in the storage file
"""
if not _file.exists():
return False
with open(_file, "r", encoding="utf-8") as file:
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader)
return key in content
def put(key: str, value: str, encoded=False):
"""
Puts a given value with a given key into the storage file
Encodes the data as base64 when encoded is set to true
"""
fileexists()
with open(_file, "r+", encoding="utf-8") as file:
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader) or {}
content.update({ key: str(base64.b64encode(value.encode()), "utf-8") if encoded else value })
with open(_file, "w+", encoding="utf-8") as file:
yaml.dump(content, file, Dumper=yaml.SafeDumper)
def remove(key: str):
"""
Removed a given key from the storage file
"""
fileexists()
with open(_file, "r", encoding="utf-8") as file:
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader) or {}
content.pop(key, None)
with open(_file, "w+", encoding="utf-8") as file:
yaml.dump(content, file, Dumper=yaml.SafeDumper)
def get(key: str, encoded=False):
"""
Retrieves a value for a given key from the storage file
If the value was encoded, encoded needs to be set True to decode it again
"""
value: str | None = None
if not _file.exists():
return None
with open(_file, "r", encoding="utf-8") as file:
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader)
value = content.get(key, None)
if value is None:
return None
return base64.b64decode(value.encode()).decode() if encoded else value
def clear():
"""
Deletes the storage file
"""
_file.unlink()