Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
ini.py76 linesDownload Raw Back to config
1from __future__ import annotations2 3import logging4import os5from configparser import ConfigParser6from pathlib import Path7from typing import ClassVar8 9from platformdirs import user_config_dir10 11from .convert import convert12 13 14class IniConfig:15    VIRTUALENV_CONFIG_FILE_ENV_VAR: ClassVar[str] = "VIRTUALENV_CONFIG_FILE"16    STATE: ClassVar[dict[bool | None, str]] = {None: "failed to parse", True: "active", False: "missing"}17 18    section = "virtualenv"19 20    def __init__(self, env=None) -> None:21        env = os.environ if env is None else env22        config_file = env.get(self.VIRTUALENV_CONFIG_FILE_ENV_VAR, None)23        self.is_env_var = config_file is not None24        if config_file is None:25            config_file = Path(user_config_dir(appname="virtualenv", appauthor="pypa")) / "virtualenv.ini"26        else:27            config_file = Path(config_file)28        self.config_file = config_file29        self._cache = {}30 31        exception = None32        self.has_config_file = None33        try:34            self.has_config_file = self.config_file.exists()35        except OSError as exc:36            exception = exc37        else:38            if self.has_config_file:39                self.config_file = self.config_file.resolve()40                self.config_parser = ConfigParser()41                try:42                    self._load()43                    self.has_virtualenv_section = self.config_parser.has_section(self.section)44                except Exception as exc:  # noqa: BLE00145                    exception = exc46        if exception is not None:47            logging.error("failed to read config file %s because %r", config_file, exception)48 49    def _load(self):50        with self.config_file.open("rt", encoding="utf-8") as file_handler:51            return self.config_parser.read_file(file_handler)52 53    def get(self, key, as_type):54        cache_key = key, as_type55        if cache_key in self._cache:56            return self._cache[cache_key]57        try:58            source = "file"59            raw_value = self.config_parser.get(self.section, key.lower())60            value = convert(raw_value, as_type, source)61            result = value, source62        except Exception:  # noqa: BLE00163            result = None64        self._cache[cache_key] = result65        return result66 67    def __bool__(self) -> bool:68        return bool(self.has_config_file) and bool(self.has_virtualenv_section)69 70    @property71    def epilog(self):72        return (73            f"\nconfig file {self.config_file} {self.STATE[self.has_config_file]} "74            f"(change{'d' if self.is_env_var else ''} via env var {self.VIRTUALENV_CONFIG_FILE_ENV_VAR})"75        )76 
codekingpro/portable-devtools · Team Ai