tzk/tzk/config.py

72 lines
1.9 KiB
Python
Raw Normal View History

2021-08-27 15:06:52 +00:00
"""
2021-09-20 17:16:38 +00:00
config.py - read and manage the tzk config file
2021-08-27 15:06:52 +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
from typing import Any
from tzk.util import fail
2021-08-25 20:06:42 +00:00
DEFAULT_INIT_OPTS = {
'wiki_name': 'wiki',
'tw_version_spec': '^5.1.23',
'author': None,
}
2021-08-25 20:25:50 +00:00
class ConfigurationManager:
def __init__(self):
2021-08-27 17:52:58 +00:00
self.initialize_cm()
def __getattr__(self, attr):
if self.conf_mod is None:
return None
else:
return getattr(self.conf_mod, attr, None)
def initialize_cm(self):
self.config_path = Path.cwd()
2021-08-25 20:25:50 +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)
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:
# no config file
self.conf_mod = None
2021-08-25 20:25:50 +00:00
def has_config(self) -> bool:
return self.conf_mod is not None
def require_config(self) -> None:
"""
Quit with exit status 1 if no config file was found.
"""
if not self.has_config():
fail(f"No tzk_config.py found in the current directory. "
f"(Try 'tzk init' if you want to create a new one.)")
2021-08-26 19:04:09 +00:00
def cm(cache=[]):
2021-08-27 15:06:52 +00:00
"""
Call this function to retrieve the singleton ConfigurationManager object,
reading and initializing it if necessary.
Since so much happens when the ConfigurationManager is initialized,
this has to go in a function so that autodoc doesn't blow up
when it tries to import the module.
"""
if not cache:
cache.append(ConfigurationManager())
return cache[0]