import os
import shutil
import json
_CONFIG_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config')
_CONFIG_SAMPLE = os.path.join(_CONFIG_DIR, 'tinydb-emcipi-config.json.sample')
_CONFIG_WORKING = os.path.join(_CONFIG_DIR, 'tinydb-emcipi-config.json')
def ensure_config():
"""
Ensure the working config file exists. If not, copy from the sample.
If working config exists, log warnings for inconsistencies with the sample config.
"""
import logging
if not os.path.exists(_CONFIG_WORKING):
if os.path.exists(_CONFIG_SAMPLE):
shutil.copy(_CONFIG_SAMPLE, _CONFIG_WORKING)
logging.warning(f"Created working config from sample: {_CONFIG_WORKING}")
else:
raise FileNotFoundError(f"Sample config not found: {_CONFIG_SAMPLE}")
else:
print(f"Config file exists: {_CONFIG_WORKING}")
# Compare working and sample config for inconsistencies
try:
with open(_CONFIG_WORKING, 'r', encoding='utf-8') as wf:
working = json.load(wf)
with open(_CONFIG_SAMPLE, 'r', encoding='utf-8') as sf:
sample = json.load(sf)
# Check for keys in sample missing from working
missing_keys = [k for k in sample.keys() if k not in working]
extra_keys = [k for k in working.keys() if k not in sample]
if missing_keys:
logging.warning(f"Working config missing keys from sample: {missing_keys}")
if extra_keys:
logging.warning(f"Working config has extra keys not in sample: {extra_keys}")
except Exception as e:
logging.warning(f"Could not compare configs: {e}")
def get_config(key=None, default=None):
"""
Canonically get a config value by key (dot notation supported, e.g. 'logging.logfile').
Returns default if not found.
"""
ensure_config()
with open(_CONFIG_WORKING, 'r', encoding='utf-8') as f:
config = json.load(f)
if not key:
return config
parts = key.split('.')
value = config
for part in parts:
if isinstance(value, dict) and part in value:
value = value[part]
else:
return default
return value
if __name__ == "__main__":
ensure_config()
print(json.dumps(get_config(None), indent=2))