From a9b648f0292992a2face2c8d3622a75660561247 Mon Sep 17 00:00:00 2001 From: Daniel Langbein Date: Thu, 5 Oct 2023 18:15:36 +0200 Subject: [PATCH] feat: include configuration files in package --- setup.cfg | 8 ++++++-- src/de/p1st/monitor/cfg/singleton.py | 20 +++++++++++++++---- {cfg => src/de/p1st/monitor/data}/yodaNas.ini | 0 {cfg => src/de/p1st/monitor/data}/yodaTux.ini | 0 4 files changed, 22 insertions(+), 6 deletions(-) rename {cfg => src/de/p1st/monitor/data}/yodaNas.ini (100%) rename {cfg => src/de/p1st/monitor/data}/yodaTux.ini (100%) diff --git a/setup.cfg b/setup.cfg index a005559..87a0a42 100644 --- a/setup.cfg +++ b/setup.cfg @@ -21,14 +21,18 @@ classifiers = Operating System :: Unix [options] +packages = find: package_dir = = src -packages = find: -python_requires = >=3.6.9 +include_package_data = True +python_requires = >=3.10.0 [options.packages.find] where = src +[options.package_data] +de.p1st.monitor = data/*.ini + [options.entry_points] ; https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html console_scripts= diff --git a/src/de/p1st/monitor/cfg/singleton.py b/src/de/p1st/monitor/cfg/singleton.py index c20d4a1..94a8fd1 100644 --- a/src/de/p1st/monitor/cfg/singleton.py +++ b/src/de/p1st/monitor/cfg/singleton.py @@ -2,22 +2,34 @@ # -*- coding: utf-8 -*- import configparser from pathlib import Path +import importlib.resources as importlib_resources _cfg: configparser.ConfigParser | None = None def init_cfg(config_file: Path = None): global _cfg - if _cfg is not None: - raise ValueError('already initialized') + raise ValueError('Already initialized.') + # Use the given config file. + + # Otherwise, use config file from /etc/de-p1st-monitor/. if config_file is None: import socket - hostname = socket.gethostname() + hostname: str = socket.gethostname() config_file = Path(f'/etc/de-p1st-monitor/{hostname}.ini') + if not config_file.is_file(): + config_file = None - if not config_file.exists(): + # Otherwise, use packaged config file. + if config_file is None: + pkg = importlib_resources.files('de.p1st.monitor') + config_file = pkg / 'data' / f'{hostname}.ini' + if not config_file.is_file(): + config_file = None + + if config_file is None or not config_file.is_file(): raise Exception(f'Configuration file does not exist! {config_file}') _cfg = configparser.ConfigParser() diff --git a/cfg/yodaNas.ini b/src/de/p1st/monitor/data/yodaNas.ini similarity index 100% rename from cfg/yodaNas.ini rename to src/de/p1st/monitor/data/yodaNas.ini diff --git a/cfg/yodaTux.ini b/src/de/p1st/monitor/data/yodaTux.ini similarity index 100% rename from cfg/yodaTux.ini rename to src/de/p1st/monitor/data/yodaTux.ini