|
| 1 | +# Copyright (c) 2025 Nordic Semiconductor ASA |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +"""Implementation for a configuration file reader.""" |
| 6 | + |
| 7 | +import logging |
| 8 | +import os |
| 9 | +import re |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +__tracebackhide__ = True |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class ConfigReader: |
| 19 | + """Reads configuration from a config file.""" |
| 20 | + |
| 21 | + def __init__(self, config_file: Path | str) -> None: |
| 22 | + """Initialize. |
| 23 | +
|
| 24 | + :param config_file: path to a configuration file |
| 25 | + """ |
| 26 | + assert os.path.exists(config_file), f"Path does not exist: {config_file}" |
| 27 | + assert os.path.isfile(config_file), f"It is not a file: {config_file}" |
| 28 | + self.config_file = config_file |
| 29 | + self.config: dict[str, str] = {} |
| 30 | + self.parse() |
| 31 | + |
| 32 | + def parse(self) -> dict[str, str]: |
| 33 | + """Parse a config file.""" |
| 34 | + pattern = re.compile(r"^(?P<key>.+)=(?P<value>.+)$") |
| 35 | + with open(self.config_file) as file: |
| 36 | + for line in file: |
| 37 | + if match := pattern.match(line): |
| 38 | + key, value = match.group("key"), match.group("value") |
| 39 | + self.config[key] = value.strip("\"'") |
| 40 | + return self.config |
| 41 | + |
| 42 | + def read(self, config_key: str, default: Any = None, *, silent=False) -> str | None: |
| 43 | + """Find key in config file. |
| 44 | +
|
| 45 | + :param config_key: key to read |
| 46 | + :param default: default value to return if key not found |
| 47 | + :param silent: do not raise an exception when key not found |
| 48 | + :raises ValueError: if key not found |
| 49 | + """ |
| 50 | + try: |
| 51 | + value = self.config[config_key] |
| 52 | + except KeyError: |
| 53 | + if default is not None: |
| 54 | + return default |
| 55 | + logger.debug("Not found key: %s", config_key) |
| 56 | + if silent: |
| 57 | + return None |
| 58 | + raise ValueError(f"Could not find key: {config_key}") from None |
| 59 | + logger.debug("Found matching key: %s=%s", config_key, value) |
| 60 | + return value |
| 61 | + |
| 62 | + def read_int(self, config_key: str, default: int | None = None) -> int: |
| 63 | + """Find key in config file and return int. |
| 64 | +
|
| 65 | + :param config_key: key to read |
| 66 | + :param default: default value to return if key not found |
| 67 | + """ |
| 68 | + if default is not None and not isinstance(default, int): |
| 69 | + raise TypeError(f"default value must be type of int, but was {type(default)}") |
| 70 | + if default is not None: |
| 71 | + default = hex(default) # type: ignore |
| 72 | + if value := self.read(config_key, default): |
| 73 | + try: |
| 74 | + return int(value) |
| 75 | + except ValueError: |
| 76 | + return int(value, 16) |
| 77 | + raise Exception("Non reachable code") # pragma: no cover |
| 78 | + |
| 79 | + def read_bool(self, config_key: str, default: bool | None = None) -> bool: |
| 80 | + """Find key in config file and return bool. |
| 81 | +
|
| 82 | + :param config_key: key to read |
| 83 | + :param default: default value to return if key not found |
| 84 | + """ |
| 85 | + value = self.read(config_key, default) |
| 86 | + if isinstance(value, str): |
| 87 | + if value.lower() == "y": |
| 88 | + return True |
| 89 | + if value.lower() == "n": |
| 90 | + return False |
| 91 | + return bool(value) |
| 92 | + |
| 93 | + def read_hex(self, config_key: str, default: int | None = None) -> str: |
| 94 | + """Find key in config file and return hex. |
| 95 | +
|
| 96 | + :param config_key: key to read |
| 97 | + :param default: default value to return if key not found |
| 98 | + :return: hex value as string |
| 99 | + """ |
| 100 | + if default is not None and not isinstance(default, int): |
| 101 | + raise TypeError(f"default value must be type of int, but was {type(default)}") |
| 102 | + value = self.read_int(config_key, default) |
| 103 | + return hex(value) |
0 commit comments