Skip to content

Commit

Permalink
enh: delete legacy cache if it exists
Browse files Browse the repository at this point in the history
  • Loading branch information
aanghelidi committed Aug 26, 2024
1 parent e69ce50 commit f67e9cc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
15 changes: 15 additions & 0 deletions pip_audit/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import logging
import os
import shutil
import subprocess
import sys
from pathlib import Path
Expand All @@ -29,6 +30,8 @@

_PIP_VERSION = Version(str(pip_api.PIP_VERSION))

_PIP_AUDIT_LEGACY_INTERNAL_CACHE = Path.home() / ".pip-audit-cache"


def _get_pip_cache() -> Path:
# Unless the cache directory is specifically set by the `--cache-dir` option, we try to share
Expand All @@ -45,6 +48,14 @@ def _get_pip_cache() -> Path:
return http_cache_dir


def _delete_legacy_cache_dir(current_cache_dir: Path, legacy_cache_dir: Path) -> None:
"""
Deletes the legacy `pip-audit` if it exists.
"""
if current_cache_dir != legacy_cache_dir:
shutil.rmtree(legacy_cache_dir)


def _get_cache_dir(custom_cache_dir: Path | None, *, use_pip: bool = True) -> Path:
"""
Returns a directory path suitable for HTTP caching.
Expand All @@ -62,6 +73,10 @@ def _get_cache_dir(custom_cache_dir: Path | None, *, use_pip: bool = True) -> Pa
# Retrieve pip-audit's default internal cache using `platformdirs`.
pip_audit_cache_dir = user_cache_path("pip-audit", appauthor=False, ensure_exists=True)

# If the retrieved cache isn't the legacy one, try to delete it.
if _PIP_AUDIT_LEGACY_INTERNAL_CACHE.exists():
_delete_legacy_cache_dir(pip_audit_cache_dir, _PIP_AUDIT_LEGACY_INTERNAL_CACHE)

# Respect pip's PIP_NO_CACHE_DIR environment setting.
if use_pip and not os.getenv("PIP_NO_CACHE_DIR"):
pip_cache_dir = _get_pip_cache() if _PIP_VERSION >= _MINIMUM_PIP_VERSION else None
Expand Down
12 changes: 11 additions & 1 deletion test/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from pytest import MonkeyPatch

import pip_audit._cache as cache
from pip_audit._cache import _get_cache_dir, _get_pip_cache
from pip_audit._cache import _delete_legacy_cache_dir, _get_cache_dir, _get_pip_cache


def _patch_platformdirs(monkeypatch: MonkeyPatch, sys_platform: str) -> None:
Expand Down Expand Up @@ -150,3 +150,13 @@ def test_cache_warns_about_old_pip(monkeypatch, cache_dir):
# have an old `pip`, then we should expect a warning to be logged
_get_cache_dir(None)
assert len(logger.warning.calls) == 1


def test_delete_legacy_cache_dir(tmp_path):
legacy = tmp_path / "pip-audit-cache"
legacy.mkdir()
assert legacy.exists()

current = _get_cache_dir(None, use_pip=False)
_delete_legacy_cache_dir(current, legacy)
assert not legacy.exists()

0 comments on commit f67e9cc

Please sign in to comment.