Skip to content

Commit 039cfee

Browse files
committed
Add 'pip cache' command.
1 parent 3596ad5 commit 039cfee

File tree

4 files changed

+184
-0
lines changed

4 files changed

+184
-0
lines changed

src/pip/_internal/commands/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44
from __future__ import absolute_import
55

6+
from pip._internal.commands.cache import CacheCommand
67
from pip._internal.commands.completion import CompletionCommand
78
from pip._internal.commands.configuration import ConfigurationCommand
89
from pip._internal.commands.download import DownloadCommand
@@ -33,6 +34,7 @@
3334
CheckCommand,
3435
ConfigurationCommand,
3536
SearchCommand,
37+
CacheCommand,
3638
WheelCommand,
3739
HashCommand,
3840
CompletionCommand,

src/pip/_internal/commands/cache.py

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
from __future__ import absolute_import
2+
3+
import logging
4+
import os
5+
import textwrap
6+
7+
from pip._internal.cli.base_command import Command
8+
from pip._internal.exceptions import CommandError
9+
from pip._internal.utils.filesystem import find_files
10+
11+
12+
logger = logging.getLogger(__name__)
13+
14+
15+
class CacheCommand(Command):
16+
"""
17+
Inspect and manage pip's caches.
18+
19+
Subcommands:
20+
info:
21+
Show information about the caches.
22+
list [name]:
23+
List filenames of packages stored in the cache.
24+
remove <pattern>:
25+
Remove one or more package from the cache.
26+
`pattern` can be a glob expression or a package name.
27+
purge:
28+
Remove all items from the cache.
29+
"""
30+
actions = ['info', 'list', 'remove', 'purge']
31+
name = 'cache'
32+
usage = """
33+
%prog <command>"""
34+
summary = "View and manage which packages are available in pip's caches."
35+
36+
def __init__(self, *args, **kw):
37+
super(CacheCommand, self).__init__(*args, **kw)
38+
39+
def run(self, options, args):
40+
if not args:
41+
raise CommandError('Please provide a subcommand.')
42+
43+
if args[0] not in self.actions:
44+
raise CommandError('Invalid subcommand: %s' % args[0])
45+
46+
self.wheel_dir = os.path.join(options.cache_dir, 'wheels')
47+
48+
method = getattr(self, 'action_%s' % args[0])
49+
return method(options, args[1:])
50+
51+
def action_info(self, options, args):
52+
format_args = (options.cache_dir, len(self.find_wheels('*.whl')))
53+
result = textwrap.dedent(
54+
"""\
55+
Cache info:
56+
Location: %s
57+
Packages: %s""" % format_args
58+
)
59+
logger.info(result)
60+
61+
def action_list(self, options, args):
62+
if args and args[0]:
63+
pattern = args[0]
64+
else:
65+
pattern = '*'
66+
67+
files = self.find_wheels(pattern)
68+
wheels = map(self._wheel_info, files)
69+
wheels = sorted(set(wheels))
70+
71+
if not wheels:
72+
logger.info('Nothing is currently cached.')
73+
return
74+
75+
result = 'Current cache contents:\n'
76+
for wheel in wheels:
77+
result += ' - %s\n' % wheel
78+
logger.info(result.strip())
79+
80+
def action_remove(self, options, args):
81+
if not args:
82+
raise CommandError('Please provide a pattern')
83+
84+
files = self.find_wheels(args[0])
85+
if not files:
86+
raise CommandError('No matching packages')
87+
88+
wheels = map(self._wheel_info, files)
89+
result = 'Removing cached wheels for:\n'
90+
for wheel in wheels:
91+
result += '- %s\n' % wheel
92+
93+
for filename in files:
94+
os.unlink(filename)
95+
logger.info(result.strip())
96+
97+
def action_purge(self, options, args):
98+
return self.action_remove(options, '*')
99+
100+
def _wheel_info(self, path):
101+
filename = os.path.splitext(os.path.basename(path))[0]
102+
name, version = filename.split('-')[0:2]
103+
return '%s-%s' % (name, version)
104+
105+
def find_wheels(self, pattern):
106+
return find_files(self.wheel_dir, pattern + '-*.whl')

src/pip/_internal/utils/filesystem.py

+16
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1+
import fnmatch
12
import os
23
import os.path
34

45
from pip._internal.utils.compat import get_path_uid
6+
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
7+
8+
if MYPY_CHECK_RUNNING:
9+
from typing import List
510

611

712
def check_path_owner(path):
@@ -28,3 +33,14 @@ def check_path_owner(path):
2833
else:
2934
previous, path = path, os.path.dirname(path)
3035
return False # assume we don't own the path
36+
37+
38+
def find_files(path, pattern):
39+
# type: (str, str) -> List[str]
40+
"""Returns a list of absolute paths of files beneath path, recursively,
41+
with filenames which match the UNIX-style shell glob pattern."""
42+
result = [] # type: List[str]
43+
for root, dirs, files in os.walk(path):
44+
matches = fnmatch.filter(files, pattern)
45+
result.extend(os.path.join(root, f) for f in matches)
46+
return result

tests/functional/test_cache.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import os
2+
import shutil
3+
4+
from pip._internal.utils import appdirs
5+
6+
7+
def test_cache_info(script, monkeypatch):
8+
result = script.pip('cache', 'info')
9+
10+
cache_dir = appdirs.user_cache_dir('pip')
11+
12+
assert 'Location: %s' % cache_dir in result.stdout
13+
assert 'Packages: ' in result.stdout
14+
15+
16+
def test_cache_list(script, monkeypatch):
17+
cache_dir = appdirs.user_cache_dir('pip')
18+
wheel_cache_dir = os.path.join(cache_dir, 'wheels')
19+
destination = os.path.join(wheel_cache_dir, 'arbitrary', 'pathname')
20+
os.makedirs(destination)
21+
with open(os.path.join(destination, 'yyy-1.2.3.whl'), 'w'):
22+
pass
23+
with open(os.path.join(destination, 'zzz-4.5.6.whl'), 'w'):
24+
pass
25+
result = script.pip('cache', 'list')
26+
assert 'yyy-1.2.3' in result.stdout
27+
assert 'zzz-4.5.6' in result.stdout
28+
shutil.rmtree(os.path.join(wheel_cache_dir, 'arbitrary'))
29+
30+
31+
def test_cache_list_with_pattern(script, monkeypatch):
32+
cache_dir = appdirs.user_cache_dir('pip')
33+
wheel_cache_dir = os.path.join(cache_dir, 'wheels')
34+
destination = os.path.join(wheel_cache_dir, 'arbitrary', 'pathname')
35+
os.makedirs(destination)
36+
with open(os.path.join(destination, 'yyy-1.2.3.whl'), 'w'):
37+
pass
38+
with open(os.path.join(destination, 'zzz-4.5.6.whl'), 'w'):
39+
pass
40+
result = script.pip('cache', 'list', 'zzz')
41+
assert 'yyy-1.2.3' not in result.stdout
42+
assert 'zzz-4.5.6' in result.stdout
43+
shutil.rmtree(os.path.join(wheel_cache_dir, 'arbitrary'))
44+
45+
46+
def test_cache_remove(script, monkeypatch):
47+
cache_dir = appdirs.user_cache_dir("pip")
48+
wheel_cache_dir = os.path.join(cache_dir, "wheels")
49+
destination = os.path.join(wheel_cache_dir, 'arbitrary', 'pathname')
50+
os.makedirs(destination)
51+
with open(os.path.join(wheel_cache_dir, "yyy-1.2.3.whl"), "w"):
52+
pass
53+
with open(os.path.join(wheel_cache_dir, "zzz-4.5.6.whl"), "w"):
54+
pass
55+
56+
script.pip("cache", "remove", expect_error=True)
57+
result = script.pip("cache", "remove", "zzz")
58+
assert 'yyy-1.2.3' not in result.stdout
59+
assert '- zzz-4.5.6' in result.stdout
60+
shutil.rmtree(os.path.join(wheel_cache_dir, 'arbitrary'))

0 commit comments

Comments
 (0)