1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
import os
from typing import Any, Optional, cast, Dict
from collections.abc import Mapping
from debputy.lsp.config.config_options import (
DebputyConfigOption,
ALL_DEBPUTY_CONFIG_OPTIONS,
)
from debputy.lsp.config.parser import DEBPUTY_CONFIG_PARSER
from debputy.manifest_parser.util import AttributePath
from debputy.util import T
from debputy.yaml import MANIFEST_YAML
class DebputyConfig:
def __init__(self, config: dict[DebputyConfigOption[Any], Any]) -> None:
self._config = config
def config_value(self, config_option: DebputyConfigOption[T]) -> T | None:
return cast("Optional[T]", self._config.get(config_option))
def _resolve(parsed_config: Mapping[str, Any], config_name: str) -> Any | None:
parts = config_name.split(".")
container = parsed_config
value: Any | None = None
for part in parts:
if isinstance(container, Mapping):
value = container.get(part)
container = value
else:
return None
return value
def _read_option(
parsed_config: Mapping[str, Any],
config_option: DebputyConfigOption[T],
) -> T | None:
result = _resolve(parsed_config, config_option.config_name)
if result is None:
return config_option.default_value
assert isinstance(result, config_option.value_type)
return result
def load_debputy_config() -> DebputyConfig:
config_base = os.environ.get("XDG_CONFIG_DIR", os.path.expanduser("~/.config"))
config_file = os.path.join(config_base, "debputy", "debputy-config.yaml")
try:
with open(config_file) as fd:
parsed_yaml = MANIFEST_YAML.load(fd)
except FileNotFoundError:
parsed_yaml = None
if not parsed_yaml:
return DebputyConfig({})
parsed_config = DEBPUTY_CONFIG_PARSER.parse_input(
parsed_yaml,
AttributePath.root_path(config_file),
parser_context=None,
)
debputy_config = {}
for config_option in ALL_DEBPUTY_CONFIG_OPTIONS:
value = _read_option(parsed_config, config_option)
debputy_config[config_option] = value
return DebputyConfig(debputy_config)
|