pyenv_cfg.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. from collections import OrderedDict
  5. LOGGER = logging.getLogger(__name__)
  6. class PyEnvCfg:
  7. def __init__(self, content, path) -> None:
  8. self.content = content
  9. self.path = path
  10. @classmethod
  11. def from_folder(cls, folder):
  12. return cls.from_file(folder / "pyvenv.cfg")
  13. @classmethod
  14. def from_file(cls, path):
  15. content = cls._read_values(path) if path.exists() else OrderedDict()
  16. return PyEnvCfg(content, path)
  17. @staticmethod
  18. def _read_values(path):
  19. content = OrderedDict()
  20. for line in path.read_text(encoding="utf-8").splitlines():
  21. equals_at = line.index("=")
  22. key = line[:equals_at].strip()
  23. value = line[equals_at + 1 :].strip()
  24. content[key] = value
  25. return content
  26. def write(self):
  27. LOGGER.debug("write %s", self.path)
  28. text = ""
  29. for key, value in self.content.items():
  30. normalized_value = os.path.realpath(value) if value and os.path.exists(value) else value
  31. line = f"{key} = {normalized_value}"
  32. LOGGER.debug("\t%s", line)
  33. text += line
  34. text += "\n"
  35. self.path.write_text(text, encoding="utf-8")
  36. def refresh(self):
  37. self.content = self._read_values(self.path)
  38. return self.content
  39. def __setitem__(self, key, value) -> None:
  40. self.content[key] = value
  41. def __getitem__(self, key):
  42. return self.content[key]
  43. def __contains__(self, item) -> bool:
  44. return item in self.content
  45. def update(self, other):
  46. self.content.update(other)
  47. return self
  48. def __repr__(self) -> str:
  49. return f"{self.__class__.__name__}(path={self.path})"
  50. __all__ = [
  51. "PyEnvCfg",
  52. ]