2021-08-26 14:46:24 +00:00
|
|
|
import datetime
|
2021-08-26 19:04:09 +00:00
|
|
|
import functools
|
2021-08-25 20:06:42 +00:00
|
|
|
import importlib
|
|
|
|
import os
|
|
|
|
from pathlib import Path
|
|
|
|
import sys
|
2021-08-26 14:46:24 +00:00
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
from util import fail
|
2021-08-25 20:06:42 +00:00
|
|
|
|
|
|
|
|
2021-08-25 20:25:50 +00:00
|
|
|
class ConfigurationManager:
|
|
|
|
def __init__(self):
|
2021-08-26 14:46:24 +00:00
|
|
|
self.config_path = Path.cwd()
|
2021-08-25 20:25:50 +00:00
|
|
|
|
2021-08-26 14:46:24 +00:00
|
|
|
for child in sorted(self.config_path.iterdir()):
|
2021-08-25 20:25:50 +00:00
|
|
|
if child.is_file() and child.name.endswith('.py'):
|
|
|
|
mod_name = child.name.rsplit('.', 1)[0]
|
|
|
|
if mod_name == 'tzk_config':
|
2021-08-26 16:51:11 +00:00
|
|
|
sys.path.insert(0, Path("__file__").parent)
|
2021-08-26 14:46:24 +00:00
|
|
|
sys.path.insert(0, str(self.config_path))
|
2021-08-25 20:25:50 +00:00
|
|
|
self.conf_mod = importlib.import_module(mod_name)
|
2021-08-26 16:51:11 +00:00
|
|
|
del sys.path[0:1]
|
2021-08-25 20:25:50 +00:00
|
|
|
break
|
|
|
|
else:
|
2021-08-26 14:46:24 +00:00
|
|
|
fail(
|
2021-08-25 20:25:50 +00:00
|
|
|
f"Your TZK config file could not be found. "
|
|
|
|
f"Please ensure there is a file called tzk_config.py "
|
2021-08-26 14:46:24 +00:00
|
|
|
f"in the current directory.")
|
2021-08-25 20:25:50 +00:00
|
|
|
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
return getattr(self.conf_mod, attr, None)
|
2021-08-26 14:46:24 +00:00
|
|
|
|
|
|
|
def write_attr(self, attr: str, value: str) -> bool:
|
|
|
|
"""
|
|
|
|
Try to add a simple attribute = string value config parameter to the
|
|
|
|
config file, if it doesn't already exist. More complicated data types
|
|
|
|
are not supported.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
False if the attribute already has a value.
|
|
|
|
True if successful.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
File access errors if the config file is inaccessible.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if hasattr(self.conf_mod, attr):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
setattr(self.conf_mod, attr, value)
|
|
|
|
with open(self.config_path / "tzk_config.py", "a") as f:
|
|
|
|
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
f.write(f"\n# Added automatically by tzk at {now}\n")
|
|
|
|
f.write(f'{attr} = "{value}"\n')
|
|
|
|
return True
|
|
|
|
|
2021-08-26 19:04:09 +00:00
|
|
|
|
2021-08-26 14:46:24 +00:00
|
|
|
cm = ConfigurationManager()
|