Coverage for /home/runner/work/coxbuild/coxbuild/src/coxbuild/configurations/__init__.py: 82%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

50 statements  

1import os 

2from pathlib import Path 

3from typing import Any 

4 

5 

6class Configuration: 

7 """Build configuration, entry key is case-insensitive.""" 

8 

9 def __init__(self, name: str = "", data: dict[str, Any] | None = None) -> None: 

10 """ 

11 Create configuration. 

12 

13 name: section name 

14 data: data source 

15 """ 

16 self.name = name 

17 self.data: dict[str, Any] = data if data is not None else {} 

18 self.cache: dict[str, Configuration] = {} 

19 

20 def copy(self) -> "Configuration": 

21 """Copy configuration.""" 

22 return Configuration(self.name, self.data.copy()) 

23 

24 def _getid(self, attr: str) -> str: 

25 return (self.name + ":" + attr if self.name else attr).lower() 

26 

27 def __iter__(self): 

28 pre = "" 

29 if self.name: 

30 pre = f"{self.name}:" 

31 return (key.removeprefix(pre) for key in self.data if key.startswith(pre)) 

32 

33 def get(self, key: str) -> Any | None: 

34 id = self._getid(key) 

35 return self.data.get(id) 

36 

37 def __getitem__(self, key: str) -> Any: 

38 id = self._getid(key) 

39 return self.data[id] 

40 

41 def __setitem__(self, key: str, value: Any) -> None: 

42 id = self._getid(key) 

43 self.data[id] = value 

44 

45 def __delitem__(self, key: str) -> None: 

46 id = self._getid(key) 

47 del self.data[id] 

48 

49 def section(self, name: str): 

50 """ 

51 Get sub-section. 

52 

53 name: sub-section name 

54 """ 

55 name = name.lower() 

56 if name not in self.cache: 

57 self.cache[name] = Configuration(self._getid(name), self.data) 

58 return self.cache[name] 

59 

60 def env(self): 

61 return self.section("env") 

62 

63 

64class ConfigurationAccessor: 

65 """Configuration accessor.""" 

66 

67 __configname__ = "" 

68 

69 def __init__(self, config: Configuration) -> None: 

70 self.rootConfig = config 

71 if self.__configname__: 

72 self.config = config.section(self.__configname__) 

73 else: 

74 self.config = config 

75 

76 def get(self, key: str) -> Any: 

77 """Get configuration value.""" 

78 return self.config.get(key) 

79 

80 def getPath(self, key: str) -> Path | None: 

81 """Get configuration value as Path.""" 

82 value: Path | None | str = self.get(key) 

83 if isinstance(value, str): 

84 value = Path(value) 

85 return value