dockge-cli/dockge_cli/service/storage.py

85 lines
2.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
_storagepath = pathlib.Path(__file__).parent / ".storage"
2024-06-29 12:14:18 +00:00
_storagepath.mkdir(exist_ok=True, parents=True)
_file = _storagepath / "storage.yaml"
2024-06-29 12:14:18 +00:00
def create_file_when_missing():
2024-07-05 14:05:35 +00:00
"""
Checks if storage file does exist, creates it when necessary
"""
if _file.exists():
return
with open(_file, 'a', encoding="utf-8"):
os.utime(_file, None)
2024-06-29 15:41:09 +00:00
2024-07-05 22:16:41 +00:00
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
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
"""
if not _file.exists():
create_file_when_missing()
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
"""
if not _file.exists():
create_file_when_missing()
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
"""
if not _file.exists():
return
2024-06-29 12:14:18 +00:00
_file.unlink()