config: support yaml

This commit is contained in:
Evgeny Zinoviev 2022-05-31 23:53:38 +03:00
parent e863761a32
commit 2aa2f96872
2 changed files with 28 additions and 7 deletions

View File

@ -11,6 +11,7 @@ inverterd~=1.0.2
requests~=2.26.0 requests~=2.26.0
aiohttp~=3.8.1 aiohttp~=3.8.1
pytz~=2021.3 pytz~=2021.3
PyYAML~=6.0
# following can be installed from debian repositories # following can be installed from debian repositories
# matplotlib~=3.5.0 # matplotlib~=3.5.0

View File

@ -1,4 +1,5 @@
import toml import toml
import yaml
import logging import logging
import os import os
@ -8,14 +9,25 @@ from argparse import ArgumentParser
def _get_config_path(name: str) -> str: def _get_config_path(name: str) -> str:
formats = ['toml', 'yaml']
dirname = join(os.environ['HOME'], '.config', name) dirname = join(os.environ['HOME'], '.config', name)
filename = join(os.environ['HOME'], '.config', f'{name}.toml')
if isdir(dirname): if isdir(dirname):
return join(dirname, 'config.toml') for fmt in formats:
elif isfile(filename): filename = join(dirname, f'config.{fmt}')
return filename if isfile(filename):
return filename
raise IOError(f'config not found in {dirname}')
else: else:
raise IOError(f'configuration file not found (tried {dirname}/config.toml and {filename})') filenames = [join(os.environ['HOME'], '.config', f'{name}.{format}') for format in formats]
for file in filenames:
if isfile(file):
return file
raise IOError(f'config not found')
class ConfigStore: class ConfigStore:
@ -64,7 +76,15 @@ class ConfigStore:
if not no_config and path is None: if not no_config and path is None:
path = _get_config_path(name) path = _get_config_path(name)
self.data = {} if no_config else toml.load(path) if no_config:
self.data = {}
else:
if path.endswith('.toml'):
self.data = toml.load(path)
elif path.endswith('.yaml'):
with open(path, 'r') as fd:
self.data = yaml.safe_load(fd)
print('loaded yaml config:', self.data)
if 'logging' in self: if 'logging' in self:
if not log_file and 'file' in self['logging']: if not log_file and 'file' in self['logging']:
@ -109,5 +129,5 @@ def setup_logging(verbose=False, log_file=None, default_fmt=False):
if log_file is not None: if log_file is not None:
log_config['filename'] = log_file log_config['filename'] = log_file
log_config['encoding'] = 'utf-8' log_config['encoding'] = 'utf-8'
logging.basicConfig(**log_config) logging.basicConfig(**log_config)