caching.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. stacklevel=2,
  39. )
  40. raise TypeError
  41. return data
  42. except Exception: # pylint: disable=broad-except
  43. # There's an issue with the cache but we just continue as if it isn't there
  44. return None
  45. def save_results(
  46. results: LinterStats, base: str | Path, pylint_home: str | Path = PYLINT_HOME
  47. ) -> None:
  48. base = Path(base)
  49. pylint_home = Path(pylint_home)
  50. try:
  51. pylint_home.mkdir(parents=True, exist_ok=True)
  52. except OSError: # pragma: no cover
  53. print(f"Unable to create directory {pylint_home}", file=sys.stderr)
  54. data_file = _get_pdata_path(base, 1)
  55. try:
  56. with open(data_file, "wb") as stream:
  57. pickle.dump(results, stream)
  58. except OSError as ex: # pragma: no cover
  59. print(f"Unable to create file {data_file}: {ex}", file=sys.stderr)