Coverage for src/twofas/cli_settings.py: 100%
29 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-22 17:32 +0100
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-22 17:32 +0100
1import typing
2from pathlib import Path
3from typing import Any
5import tomli_w
6from configuraptor import TypedConfig, asdict
7from configuraptor.core import convert_key
9config = Path("~/.config").expanduser()
10config.mkdir(exist_ok=True)
11DEFAULT_SETTINGS = config / "2fas.toml"
12DEFAULT_SETTINGS.touch(exist_ok=True)
14CONFIG_KEY = "tool.2fas"
17class CliSettings(TypedConfig):
18 files: list[str] | None
19 default_file: str | None
22def load_cli_settings(input_file: str | Path = DEFAULT_SETTINGS, **overwrite: Any) -> CliSettings:
23 return CliSettings.load([input_file, overwrite], key=CONFIG_KEY)
26def get_cli_setting(key: str, filename: str | Path = DEFAULT_SETTINGS) -> typing.Any:
27 key = convert_key(key)
28 settings = load_cli_settings(filename)
29 return getattr(settings, key)
32def set_cli_setting(key: str, value: typing.Any, filename: str | Path = DEFAULT_SETTINGS) -> None:
33 filepath = Path(filename)
34 key = convert_key(key)
36 settings = load_cli_settings(filepath)
37 settings.update(**{key: value})
39 inner_data = asdict(
40 settings,
41 with_top_level_key=False,
42 )
44 # toml can't deal with None, so skip those:
45 inner_data = {k: v for k, v in inner_data.items() if v is not None}
47 outer_data = {"tool": {"2fas": inner_data}}
49 filepath.write_text(tomli_w.dumps(outer_data))