caching.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. from __future__ import annotations
  5. import pickle
  6. import sys
  7. import warnings
  8. from pathlib import Path
  9. from pylint.constants import PYLINT_HOME
  10. from pylint.utils import LinterStats
  11. PYLINT_HOME_AS_PATH = Path(PYLINT_HOME)
  12. def _get_pdata_path(
  13. base_name: Path, recurs: int, pylint_home: Path = PYLINT_HOME_AS_PATH
  14. ) -> Path:
  15. # We strip all characters that can't be used in a filename. Also strip '/' and
  16. # '\\' because we want to create a single file, not sub-directories.
  17. underscored_name = "_".join(
  18. str(p.replace(":", "_").replace("/", "_").replace("\\", "_"))
  19. for p in base_name.parts
  20. )
  21. return pylint_home / f"{underscored_name}_{recurs}.stats"
  22. def load_results(
  23. base: str | Path, pylint_home: str | Path = PYLINT_HOME
  24. ) -> LinterStats | None:
  25. base = Path(base)
  26. pylint_home = Path(pylint_home)
  27. data_file = _get_pdata_path(base, 1, pylint_home)
  28. if not data_file.exists():
  29. return None
  30. try:
  31. with open(data_file, "rb") as stream:
  32. data = pickle.load(stream)
  33. if not isinstance(data, LinterStats):
  34. warnings.warn(
  35. "You're using an old pylint cache with invalid data following "
  36. f"an upgrade, please delete '{data_file}'.",
  37. UserWarning,
  38. )
  39. raise TypeError
  40. return data
  41. except Exception: # pylint: disable=broad-except
  42. # There's an issue with the cache but we just continue as if it isn't there
  43. return None
  44. def save_results(
  45. results: LinterStats, base: str | Path, pylint_home: str | Path = PYLINT_HOME
  46. ) -> None:
  47. base = Path(base)
  48. pylint_home = Path(pylint_home)
  49. try:
  50. pylint_home.mkdir(parents=True, exist_ok=True)
  51. except OSError: # pragma: no cover
  52. print(f"Unable to create directory {pylint_home}", file=sys.stderr)
  53. data_file = _get_pdata_path(base, 1)
  54. try:
  55. with open(data_file, "wb") as stream:
  56. pickle.dump(results, stream)
  57. except OSError as ex: # pragma: no cover
  58. print(f"Unable to create file {data_file}: {ex}", file=sys.stderr)