Source code for dawsonia.config

"""configuration file parsing utilities."""

from __future__ import annotations

import os
from functools import lru_cache
from pathlib import Path
from typing import Any, Optional

import click
import tomli as tomllib

from .typing import TableFormatFile


[docs] @lru_cache def _read_toml(file_or_path: str | Path, _mtime: int) -> dict: """Read TOML configuration file into a dictionary""" path = Path(file_or_path) if not path.exists(): raise FileNotFoundError(str(path)) with path.open("rb") as fp: config = tomllib.load(fp) return config
[docs] def read_table_formats(config_file: str | Path) -> TableFormatFile: return _read_toml( config_file, os.path.getmtime(config_file) ) # type:ignore[return-value]
[docs] def read_configfile(config_file: str | Path) -> dict[str, dict[str, dict]]: return _read_toml(config_file, os.path.getmtime(config_file))
[docs] def set_default_from_configfile(ctx: click.Context, _, value) -> Optional[str]: """Set / override CLI context's arguments from configfile""" config_file = Path(value) command_name = ctx.command.name print(f"Reading {config_file = }") if config_file.exists() and command_name: config = read_configfile(config_file) if command_name not in config["dawsonia"]: raise KeyError( f"Config provided but section [dawsonia.{command_name}] seems to be" " missing." ) ctx.default_map = config["dawsonia"].get(command_name) return value
config_cli_names = ("-c", "--config") # Default keyword arguments for a subcommand which accepts a configuration file # option. config_kwargs: dict[str, Any] = dict( help="TOML configuration file as an alternative for CLI arguments.", callback=set_default_from_configfile, is_eager=True, expose_value=False, )