dockge-cli/dockge_cli/components/storage.py

45 lines
1.4 KiB
Python
Raw Normal View History

2024-06-29 15:41:09 +00:00
import os
2024-06-29 12:14:18 +00:00
import pathlib
import base64
import yaml
2024-07-02 16:09:56 +00:00
_storagepath = pathlib.Path(__file__).parents[1] / ".temp"
2024-06-29 12:14:18 +00:00
_file = _storagepath / "storage.yaml"
_storagepath.mkdir(exist_ok=True, parents=True)
2024-06-29 15:41:09 +00:00
def fileexists():
if not _file.exists():
2024-07-02 16:09:56 +00:00
with open(_file, 'a', encoding="utf-8"):
2024-06-29 15:41:09 +00:00
os.utime(_file, None)
2024-07-02 16:09:56 +00:00
def put(key: str, value: str, encoded=False):
2024-06-29 15:41:09 +00:00
fileexists()
2024-07-02 16:09:56 +00:00
with open(_file, "r+", encoding="utf-8") as file:
2024-06-29 15:41:09 +00:00
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader) or {}
content.update({ key: base64.b64encode(value.encode()) if encoded else value })
2024-07-02 16:09:56 +00:00
with open(_file, "w+", encoding="utf-8") as file:
2024-06-29 15:41:09 +00:00
yaml.dump(content, file, Dumper=yaml.SafeDumper)
def remove(key: str):
fileexists()
2024-07-02 16:09:56 +00:00
with open(_file, "r", encoding="utf-8") as file:
2024-06-29 12:14:18 +00:00
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader) or {}
2024-06-29 15:41:09 +00:00
content.pop(key, None)
2024-07-02 16:09:56 +00:00
with open(_file, "w+", encoding="utf-8") as file:
2024-06-29 12:14:18 +00:00
yaml.dump(content, file, Dumper=yaml.SafeDumper)
2024-06-29 15:41:09 +00:00
def get(key: str, encoded=False):
2024-06-29 12:14:18 +00:00
value: str = None
if not _file.exists():
return None
2024-07-02 16:09:56 +00:00
with open(_file, "r", encoding="utf-8") as file:
2024-06-29 12:14:18 +00:00
content: dict[str, str] = yaml.load(file, Loader=yaml.SafeLoader)
value = content.get(key, None)
2024-06-29 15:41:09 +00:00
if value is None:
return None
return base64.b64decode(value).decode() if encoded else value
2024-06-29 12:14:18 +00:00
def clear():
_file.unlink()