py-seasonal-hours-clock/seasonal_clock/config.py

46 lines
1.3 KiB
Python
Raw Normal View History

2022-03-24 07:30:57 +00:00
"""Configuration handling for the Seasonal Clock"""
import os
from typing import Dict, Union
import toml
from xdg import xdg_config_home
from .geo import get_country_city, get_lat_long, get_timezone
def load_config() -> Dict[str, Union[str, float]]:
"""Load the configuration from $XDG_CONFIG_HOME/seasonal-clock.toml"""
config_dir = xdg_config_home()
config_filename = os.path.join(config_dir, 'seasonal-clock.toml')
if os.path.exists(config_filename):
loaded_config = toml.load(config_filename) or {}
config: Dict[str, Union[float, str]] = loaded_config.get('seasonal-clock')
else:
config = {}
if (
'city' not in config
and 'country' not in config
and 'latitude' not in config
and 'longitude' not in config
):
raise ValueError('No location configured')
if not config.get('longitude') or not config.get('latitude'):
config['latitude'], config['longitude'] = get_lat_long(
config['country'], config['city']
)
elif not config.get('country') or not config.get('city'):
config['country'], config['city'] = get_country_city(
config['latitude'], config['longitude']
)
if not config.get('timezone'):
config['timezone'] = get_timezone(config['latitude'], config['longitude'])
return config