dockge-cli/dockge_cli/service/storage.py
Firq d79a01cfb1
All checks were successful
/ pylint (push) Successful in 11s
/ mypy (push) Successful in 12s
/ lint-and-typing (push) Successful in 16s
/ build-artifacts (push) Successful in 8s
/ publish-artifacts (push) Successful in 9s
Fixed issue with bytes when saving credentials
2024-07-05 16:36:51 +02:00

62 lines
1.9 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 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()