dockge-cli/dockge_cli/service/storage.py

62 lines
1.9 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():
2024-07-05 14:05:35 +00:00
"""
Checks if storage file does exist, creates it when necessary
"""
2024-06-29 15:41:09 +00:00
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-07-05 14:05:35 +00:00
"""
Puts a given value with a given key into the storage file
Encodes the data as base64 when encoded is set to true
"""
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: str(base64.b64encode(value.encode()), "utf-8") 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):
2024-07-05 14:05:35 +00:00
"""
Removed a given key from the storage file
"""
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 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-07-05 14:05:35 +00:00
"""
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
2024-06-29 12:14:18 +00:00
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.encode()).decode() if encoded else value
2024-06-29 12:14:18 +00:00
def clear():
2024-07-05 14:05:35 +00:00
"""
Deletes the storage file
"""
2024-06-29 12:14:18 +00:00
_file.unlink()