61 lines
1.8 KiB
Python
Executable file
61 lines
1.8 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
import os
|
|
from os import mkdir
|
|
from os.path import isdir, isfile, join
|
|
from typing import Union
|
|
|
|
import yaml
|
|
|
|
|
|
class Config:
|
|
|
|
def __init__(self):
|
|
# Make sure we have config
|
|
self.config_basepath = join(os.environ["HOME"], ".knot")
|
|
self.config_filename = join(self.config_basepath, "config")
|
|
if not isdir(self.config_basepath):
|
|
mkdir(self.config_basepath)
|
|
|
|
def get_config(self) -> Union[None, dict]:
|
|
if not isfile(self.config_filename):
|
|
return None
|
|
with open(self.config_filename, "r") as fh:
|
|
return yaml.safe_load(fh.read())
|
|
|
|
def get_config_data(self) -> dict:
|
|
config_data = self.get_config()
|
|
config_data.pop("password", None)
|
|
return config_data
|
|
|
|
def get_current(self) -> str:
|
|
if os.path.islink(self.config_filename):
|
|
actual_path = os.readlink(self.config_filename)
|
|
return actual_path.split("-")[-1]
|
|
else:
|
|
return "none"
|
|
|
|
def set_context(self, context) -> bool:
|
|
symlink = f"{self.config_filename}-{context}"
|
|
found = os.path.isfile(symlink)
|
|
if os.path.islink(self.config_filename):
|
|
os.remove(self.config_filename)
|
|
elif os.path.isfile(self.config_filename):
|
|
os.rename(self.config_filename, symlink)
|
|
os.symlink(symlink, self.config_filename)
|
|
self.config_filename = symlink
|
|
return found
|
|
|
|
def set_config(
|
|
self,
|
|
baseurl: str,
|
|
username: str,
|
|
password: str,
|
|
):
|
|
config = {
|
|
"baseurl": baseurl,
|
|
"username": username,
|
|
"password": password
|
|
}
|
|
|
|
with open(self.config_filename, "w") as fh:
|
|
fh.write(yaml.dump(config))
|