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

44 statements  

« prev     ^ index     » next       coverage.py v7.8.2, created at 2025-09-07 09:27 +0000

1import os 

2from typing import Mapping, Any, Optional, cast, Dict 

3 

4from debputy.lsp.config.config_options import ( 

5 DebputyConfigOption, 

6 ALL_DEBPUTY_CONFIG_OPTIONS, 

7) 

8from debputy.lsp.config.parser import DEBPUTY_CONFIG_PARSER 

9from debputy.manifest_parser.util import AttributePath 

10from debputy.util import T 

11from debputy.yaml import MANIFEST_YAML 

12 

13 

14class DebputyConfig: 

15 

16 def __init__(self, config: Dict[DebputyConfigOption[Any], Any]) -> None: 

17 self._config = config 

18 

19 def config_value(self, config_option: DebputyConfigOption[T]) -> Optional[T]: 

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

21 

22 

23def _resolve(parsed_config: Mapping[str, Any], config_name: str) -> Optional[Any]: 

24 parts = config_name.split(".") 

25 container = parsed_config 

26 value: Optional[Any] = None 

27 for part in parts: 

28 if isinstance(container, Mapping): 

29 value = container.get(part) 

30 container = value 

31 else: 

32 return None 

33 return value 

34 

35 

36def _read_option( 

37 parsed_config: Mapping[str, Any], 

38 config_option: DebputyConfigOption[T], 

39) -> Optional[T]: 

40 result = _resolve(parsed_config, config_option.config_name) 

41 if result is None: 

42 return config_option.default_value 

43 assert isinstance(result, config_option.value_type) 

44 return result 

45 

46 

47def load_debputy_config() -> DebputyConfig: 

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

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

50 try: 

51 with open(config_file) as fd: 

52 parsed_yaml = MANIFEST_YAML.load(fd) 

53 except FileNotFoundError: 

54 parsed_yaml = None 

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

56 return DebputyConfig({}) 

57 parsed_config = DEBPUTY_CONFIG_PARSER.parse_input( 

58 parsed_yaml, 

59 AttributePath.root_path(config_file), 

60 parser_context=None, 

61 ) 

62 debputy_config = {} 

63 for config_option in ALL_DEBPUTY_CONFIG_OPTIONS: 

64 value = _read_option(parsed_config, config_option) 

65 debputy_config[config_option] = value 

66 return DebputyConfig(debputy_config)