diff options
Diffstat (limited to 'common.py')
-rw-r--r-- | common.py | 18 |
1 files changed, 11 insertions, 7 deletions
@@ -26,7 +26,7 @@ from pathlib import Path, PosixPath from stat import S_ISDIR import math import logging -from typing import Any, Iterator, Optional, Never +from typing import Any, Iterator, Optional, Never, TextIO from hashlib import sha256 from xdg.BaseDirectory import xdg_config_home @@ -64,8 +64,8 @@ class BadConfiguration(Exception): message = str(config_path) + ': ' + message super().__init__(message) -def find_config(filename : str = 'config.yml', appname : str = 'webmap') -> Path: - """Return the configuration file path""" +def open_config(filename : str = 'config.yml', appname : str = 'webmap') -> TextIO: + """Open the configuration file""" dirs = [ Path(), Path(xdg_config_home).joinpath(appname), @@ -73,15 +73,19 @@ def find_config(filename : str = 'config.yml', appname : str = 'webmap') -> Path ] for d in dirs: p = d.joinpath(filename) - if p.exists(): - return p + try: + return p.open(mode='r', encoding='utf-8') + except (FileNotFoundError, PermissionError) as e: + logging.debug('Ignoring exception %s', str(e)) raise MissingConfiguration(filename) def load_config(path : Optional[Path] = None) -> dict[str, Any]: """Load configuration file""" - config_path = find_config() if path is None else path - with config_path.open(mode='r', encoding='utf-8') as fp: + fp = open_config() if path is None else path.open(mode='r', encoding='utf-8') + try: return yaml.safe_load(fp) + finally: + fp.close() def layers_in_group(groupname : str, patterns : str|list[str], layernames : set[str]) -> Iterator[str]: |