Coverage for src/twofas/cli_settings.py: 100%
37 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-22 21:52 +0100
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-22 21:52 +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
20 auto_verbose: bool = False
22 def add_file(self, filename: str | None, _config_file: str | Path = DEFAULT_SETTINGS) -> None:
23 if not filename:
24 return
26 files = self.files or []
27 if filename not in files:
28 files.append(filename)
29 set_cli_setting("files", files, _config_file)
32def load_cli_settings(input_file: str | Path = DEFAULT_SETTINGS, **overwrite: Any) -> CliSettings:
33 return CliSettings.load([input_file, overwrite], key=CONFIG_KEY)
36def get_cli_setting(key: str, filename: str | Path = DEFAULT_SETTINGS) -> typing.Any:
37 key = convert_key(key)
38 settings = load_cli_settings(filename)
39 return getattr(settings, key)
42def set_cli_setting(key: str, value: typing.Any, filename: str | Path = DEFAULT_SETTINGS) -> None:
43 filepath = Path(filename)
44 key = convert_key(key)
46 settings = load_cli_settings(filepath)
47 settings.update(**{key: value}, _convert_types=True)
49 inner_data = asdict(
50 settings,
51 with_top_level_key=False,
52 )
54 # toml can't deal with None, so skip those:
55 inner_data = {k: v for k, v in inner_data.items() if v is not None}
57 outer_data = {"tool": {"2fas": inner_data}}
59 filepath.write_text(tomli_w.dumps(outer_data))