Moved files, refactored calls, added credentials warning

This commit is contained in:
Firq 2024-07-06 00:28:37 +02:00
parent 58aea47921
commit c00aa232fc
Signed by: Firq
GPG key ID: 3ACC61C8CEC83C20
5 changed files with 23 additions and 24 deletions
dockge_cli/service

1
dockge_cli/service/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
.storage/*

View file

@ -3,18 +3,18 @@ import pathlib
import base64
import yaml
_storagepath = pathlib.Path(__file__).parents[1] / ".temp"
_storagepath = pathlib.Path(__file__).parent / ".storage"
_storagepath.mkdir(exist_ok=True, parents=True)
_file = _storagepath / "storage.yaml"
_storagepath.mkdir(exist_ok=True, parents=True)
def fileexists():
def create_file_when_missing():
"""
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)
if _file.exists():
return
with open(_file, 'a', encoding="utf-8"):
os.utime(_file, None)
def exists(key: str) -> bool:
"""
@ -34,10 +34,13 @@ 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:
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)
@ -45,10 +48,13 @@ def remove(key: str):
"""
Removed a given key from the storage file
"""
fileexists()
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)
@ -60,9 +66,11 @@ def get(key: str, encoded=False):
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
@ -71,4 +79,6 @@ def clear():
"""
Deletes the storage file
"""
if not _file.exists():
return
_file.unlink()