Coverage for src/debputy/lsp/config/debputy_config.py: 45%

45 statements  

« prev     ^ index     » next       coverage.py v7.8.2, created at 2025-10-12 15:06 +0000

1import os 

2from typing import Any, Optional, cast, Dict 

3from collections.abc import Mapping 

4 

5from debputy.lsp.config.config_options import ( 

6 DebputyConfigOption, 

7 ALL_DEBPUTY_CONFIG_OPTIONS, 

8) 

9from debputy.lsp.config.parser import DEBPUTY_CONFIG_PARSER 

10from debputy.manifest_parser.util import AttributePath 

11from debputy.util import T 

12from debputy.yaml import MANIFEST_YAML 

13 

14 

15class DebputyConfig: 

16 

17 def __init__(self, config: dict[DebputyConfigOption[Any], Any]) -> None: 

18 self._config = config 

19 

20 def config_value(self, config_option: DebputyConfigOption[T]) -> T | None: 

21 return cast("Optional[T]", self._config.get(config_option)) 

22 

23 

24def _resolve(parsed_config: Mapping[str, Any], config_name: str) -> Any | None: 

25 parts = config_name.split(".") 

26 container = parsed_config 

27 value: Any | None = None 

28 for part in parts: 

29 if isinstance(container, Mapping): 

30 value = container.get(part) 

31 container = value 

32 else: 

33 return None 

34 return value 

35 

36 

37def _read_option( 

38 parsed_config: Mapping[str, Any], 

39 config_option: DebputyConfigOption[T], 

40) -> T | None: 

41 result = _resolve(parsed_config, config_option.config_name) 

42 if result is None: 

43 return config_option.default_value 

44 assert isinstance(result, config_option.value_type) 

45 return result 

46 

47 

48def load_debputy_config() -> DebputyConfig: 

49 config_base = os.environ.get("XDG_CONFIG_DIR", os.path.expanduser("~/.config")) 

50 config_file = os.path.join(config_base, "debputy", "debputy-config.yaml") 

51 try: 

52 with open(config_file) as fd: 

53 parsed_yaml = MANIFEST_YAML.load(fd) 

54 except FileNotFoundError: 

55 parsed_yaml = None 

56 if not parsed_yaml: 56 ↛ 58line 56 didn't jump to line 58 because the condition on line 56 was always true

57 return DebputyConfig({}) 

58 parsed_config = DEBPUTY_CONFIG_PARSER.parse_input( 

59 parsed_yaml, 

60 AttributePath.root_path(config_file), 

61 parser_context=None, 

62 ) 

63 debputy_config = {} 

64 for config_option in ALL_DEBPUTY_CONFIG_OPTIONS: 

65 value = _read_option(parsed_config, config_option) 

66 debputy_config[config_option] = value 

67 return DebputyConfig(debputy_config)