Source code for SDF.config
"""Settings accessible to the user (via a config file)"""
import dataclasses
import json
import logging
import os
import platform
logger = logging.getLogger(__name__)
[docs]@dataclasses.dataclass
class SDFConfig:
"""Representation of the config file"""
use_system_jpkfile: bool = False
"""if True: don't import jpkfile from SDF.extern"""
use_system_oiffile: bool = False
"""if True: don't import offile from SDF.extern"""
use_system_mfpfile: bool = False
"""if True: don't import mfpfile from SDF.extern"""
use_system_tifffile: bool = False
"""if True: don't import tifffile from SDF.extern"""
[docs]def determine_config_dir() -> str:
"""Returns the absolute path of the sdf configuration directory. Creates the directory if it did not exist."""
# determine config file path
if platform.system() == "Linux":
if "XDG_CONFIG_HOME" in os.environ.keys():
config_dir = os.environ["XDG_CONFIG_HOME"] + "/sdf"
else:
config_dir = os.path.expanduser("~/.config/sdf")
elif platform.system() == "Windows":
config_dir = os.path.expandvars("%APPDATA%/sdf")
elif platform.system() == "Darwin": # MacOS
config_dir = os.path.expanduser("~/Library/Preferences/sdf")
else:
config_dir = os.path.expanduser("~/.sdf")
# generate config directory
if not os.path.isdir(config_dir):
os.makedirs(config_dir)
return config_dir
[docs]def load_config(config_file) -> SDFConfig:
"""Load configuration from `config_file`"""
# load config, generate file if necessary
default_config = SDFConfig()
default_config_dict = dataclasses.asdict(default_config)
if not os.path.isfile(config_file):
with open(config_file, 'w') as fp:
json.dump(dataclasses.asdict(default_config), fp)
return default_config
else:
with open(config_file, 'rt') as fh:
config_dict: dict = json.load(fh)
# check if entries are missing
outdated = False
for key in default_config_dict.keys() - config_dict.keys():
config_dict[key] = default_config_dict[key]
outdated = True
if outdated:
logger.info(f"Updating config file at {config_file}")
with open(config_file, 'w') as fp:
json.dump(config_dict, fp)
# warn about unknown keys
for key in config_dict.keys() - default_config_dict.keys():
logger.info(f"Unknown key '{key}' found in config file {config_file}. Ignoring.")
config_dict.pop(key)
return SDFConfig(**config_dict)
CONFIG_DIR = determine_config_dir()
CONFIG = load_config(os.path.join(CONFIG_DIR, "config.json"))