dockge-cli/dockge_cli/service/storage.py
Firq c00aa232fc
All checks were successful
/ pylint (push) Successful in 11s
/ mypy (push) Successful in 12s
/ build-artifacts (push) Successful in 7s
/ lint-and-typing (push) Successful in 14s
/ publish-artifacts (push) Successful in 9s
Moved files, refactored calls, added credentials warning
2024-07-06 00:28:37 +02:00

85 lines
2.4 KiB
Python

import os
import pathlib
import base64
import yaml
_storagepath = pathlib.Path(__file__).parent / ".storage"
_storagepath.mkdir(exist_ok=True, parents=True)
_file = _storagepath / "storage.yaml"
def create_file_when_missing():
"""
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)
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
"""
if not _file.exists():
create_file_when_missing()
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
"""
if not _file.exists():
create_file_when_missing()
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
"""
if not _file.exists():
return
_file.unlink()