70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
# -*- coding: utf-8 -*-
|
|
#
|
|
import os
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
from .conf import ConfigManager
|
|
|
|
__all__ = ['BASE_DIR', 'PROJECT_DIR', 'VERSION', 'CONFIG', 'CONFIG_SOURCE']
|
|
|
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
LOG_DIR = os.path.join('/', 'opt', 'maxkb', 'logs')
|
|
PROJECT_DIR = os.path.dirname(BASE_DIR)
|
|
VERSION = '2.0.0'
|
|
DEFAULT_CONFIG_ROOT = os.path.abspath('/opt/maxkb/conf')
|
|
CONFIG_FILENAMES = ('config_example.yml', 'config.yaml', 'config.yml')
|
|
|
|
# load environment variables from .env file
|
|
load_dotenv()
|
|
|
|
|
|
def _has_config_file(root_path):
|
|
return any(os.path.isfile(os.path.join(root_path, name)) for name in CONFIG_FILENAMES)
|
|
|
|
|
|
def _resolve_config_target():
|
|
config_path = os.environ.get('MAXKB_CONFIG')
|
|
if config_path:
|
|
config_path = os.path.abspath(config_path)
|
|
if os.path.isfile(config_path):
|
|
return os.path.dirname(config_path), os.path.basename(config_path), config_path
|
|
if os.path.isdir(config_path):
|
|
if _has_config_file(config_path):
|
|
return config_path, None, config_path
|
|
raise ImportError(f'No config file found in MAXKB_CONFIG directory: {config_path}')
|
|
raise ImportError(f'MAXKB_CONFIG path does not exist: {config_path}')
|
|
|
|
for root_path in (DEFAULT_CONFIG_ROOT, PROJECT_DIR):
|
|
if _has_config_file(root_path):
|
|
return root_path, None, root_path
|
|
|
|
return DEFAULT_CONFIG_ROOT, None, DEFAULT_CONFIG_ROOT
|
|
|
|
|
|
def _load_config():
|
|
if os.environ.get('MAXKB_CONFIG_TYPE') == 'ENV':
|
|
root_path, filename, source = _resolve_config_target()
|
|
manager = ConfigManager(root_path=root_path)
|
|
if filename:
|
|
manager.from_yaml(filename)
|
|
source = f'ENV + {source}'
|
|
elif _has_config_file(root_path):
|
|
manager.load_from_yml()
|
|
source = f'ENV + {source}'
|
|
else:
|
|
source = 'ENV'
|
|
manager.load_from_env()
|
|
return manager.config, source
|
|
|
|
root_path, filename, source = _resolve_config_target()
|
|
if filename:
|
|
manager = ConfigManager(root_path=root_path)
|
|
manager.from_yaml(filename)
|
|
return manager.config, source
|
|
|
|
return ConfigManager.load_user_config(root_path=root_path), source
|
|
|
|
|
|
CONFIG, CONFIG_SOURCE = _load_config()
|