AutoFramework/venv/Lib/site-packages/pip/_internal/commands/cache.py

224 lines
7.3 KiB
Python
Raw Normal View History

2022-07-17 01:48:29 +08:00
import os
import textwrap
from optparse import Values
from typing import Any, List
import pip._internal.utils.filesystem as filesystem
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.exceptions import CommandError, PipError
2022-07-21 08:44:10 +08:00
from pip._internal.utils.logging import getLogger
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
logger = getLogger(__name__)
2022-07-17 01:48:29 +08:00
class CacheCommand(Command):
"""
Inspect and manage pip's wheel cache.
Subcommands:
- dir: Show the cache directory.
- info: Show information about the cache.
- list: List filenames of packages stored in the cache.
- remove: Remove one or more package from the cache.
- purge: Remove all items from the cache.
``<pattern>`` can be a glob expression or a package name.
"""
ignore_require_venv = True
usage = """
%prog dir
%prog info
%prog list [<pattern>] [--format=[human, abspath]]
%prog remove <pattern>
%prog purge
"""
2022-07-21 08:44:10 +08:00
def add_options(self) -> None:
2022-07-17 01:48:29 +08:00
self.cmd_opts.add_option(
2022-07-21 08:44:10 +08:00
"--format",
action="store",
dest="list_format",
2022-07-17 01:48:29 +08:00
default="human",
2022-07-21 08:44:10 +08:00
choices=("human", "abspath"),
help="Select the output format among: human (default) or abspath",
2022-07-17 01:48:29 +08:00
)
self.parser.insert_option_group(0, self.cmd_opts)
2022-07-21 08:44:10 +08:00
def run(self, options: Values, args: List[str]) -> int:
2022-07-17 01:48:29 +08:00
handlers = {
"dir": self.get_cache_dir,
"info": self.get_cache_info,
"list": self.list_cache_items,
"remove": self.remove_cache_items,
"purge": self.purge_cache,
}
if not options.cache_dir:
2022-07-21 08:44:10 +08:00
logger.error("pip cache commands can not function since cache is disabled.")
2022-07-17 01:48:29 +08:00
return ERROR
# Determine action
if not args or args[0] not in handlers:
logger.error(
"Need an action (%s) to perform.",
", ".join(sorted(handlers)),
)
return ERROR
action = args[0]
# Error handling happens here, not in the action-handlers.
try:
handlers[action](options, args[1:])
except PipError as e:
logger.error(e.args[0])
return ERROR
return SUCCESS
2022-07-21 08:44:10 +08:00
def get_cache_dir(self, options: Values, args: List[Any]) -> None:
2022-07-17 01:48:29 +08:00
if args:
2022-07-21 08:44:10 +08:00
raise CommandError("Too many arguments")
2022-07-17 01:48:29 +08:00
logger.info(options.cache_dir)
2022-07-21 08:44:10 +08:00
def get_cache_info(self, options: Values, args: List[Any]) -> None:
2022-07-17 01:48:29 +08:00
if args:
2022-07-21 08:44:10 +08:00
raise CommandError("Too many arguments")
2022-07-17 01:48:29 +08:00
num_http_files = len(self._find_http_files(options))
2022-07-21 08:44:10 +08:00
num_packages = len(self._find_wheels(options, "*"))
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
http_cache_location = self._cache_dir(options, "http")
wheels_cache_location = self._cache_dir(options, "wheels")
2022-07-17 01:48:29 +08:00
http_cache_size = filesystem.format_directory_size(http_cache_location)
2022-07-21 08:44:10 +08:00
wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)
message = (
textwrap.dedent(
"""
Package index page cache location: {http_cache_location}
Package index page cache size: {http_cache_size}
Number of HTTP files: {num_http_files}
Wheels location: {wheels_cache_location}
Wheels size: {wheels_cache_size}
Number of wheels: {package_count}
"""
)
.format(
http_cache_location=http_cache_location,
http_cache_size=http_cache_size,
num_http_files=num_http_files,
wheels_cache_location=wheels_cache_location,
package_count=num_packages,
wheels_cache_size=wheels_cache_size,
)
.strip()
2022-07-17 01:48:29 +08:00
)
logger.info(message)
2022-07-21 08:44:10 +08:00
def list_cache_items(self, options: Values, args: List[Any]) -> None:
2022-07-17 01:48:29 +08:00
if len(args) > 1:
2022-07-21 08:44:10 +08:00
raise CommandError("Too many arguments")
2022-07-17 01:48:29 +08:00
if args:
pattern = args[0]
else:
2022-07-21 08:44:10 +08:00
pattern = "*"
2022-07-17 01:48:29 +08:00
files = self._find_wheels(options, pattern)
2022-07-21 08:44:10 +08:00
if options.list_format == "human":
2022-07-17 01:48:29 +08:00
self.format_for_human(files)
else:
self.format_for_abspath(files)
2022-07-21 08:44:10 +08:00
def format_for_human(self, files: List[str]) -> None:
2022-07-17 01:48:29 +08:00
if not files:
2022-07-21 08:44:10 +08:00
logger.info("Nothing cached.")
2022-07-17 01:48:29 +08:00
return
results = []
for filename in files:
wheel = os.path.basename(filename)
size = filesystem.format_file_size(filename)
2022-07-21 08:44:10 +08:00
results.append(f" - {wheel} ({size})")
logger.info("Cache contents:\n")
logger.info("\n".join(sorted(results)))
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
def format_for_abspath(self, files: List[str]) -> None:
2022-07-17 01:48:29 +08:00
if not files:
return
results = []
for filename in files:
results.append(filename)
2022-07-21 08:44:10 +08:00
logger.info("\n".join(sorted(results)))
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
def remove_cache_items(self, options: Values, args: List[Any]) -> None:
2022-07-17 01:48:29 +08:00
if len(args) > 1:
2022-07-21 08:44:10 +08:00
raise CommandError("Too many arguments")
2022-07-17 01:48:29 +08:00
if not args:
2022-07-21 08:44:10 +08:00
raise CommandError("Please provide a pattern")
2022-07-17 01:48:29 +08:00
files = self._find_wheels(options, args[0])
2022-07-21 08:44:10 +08:00
no_matching_msg = "No matching packages"
if args[0] == "*":
# Only fetch http files if no specific pattern given
2022-07-17 01:48:29 +08:00
files += self._find_http_files(options)
2022-07-21 08:44:10 +08:00
else:
# Add the pattern to the log message
no_matching_msg += ' for pattern "{}"'.format(args[0])
2022-07-17 01:48:29 +08:00
if not files:
2022-07-21 08:44:10 +08:00
logger.warning(no_matching_msg)
2022-07-17 01:48:29 +08:00
for filename in files:
os.unlink(filename)
2022-07-21 08:44:10 +08:00
logger.verbose("Removed %s", filename)
logger.info("Files removed: %s", len(files))
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
def purge_cache(self, options: Values, args: List[Any]) -> None:
2022-07-17 01:48:29 +08:00
if args:
2022-07-21 08:44:10 +08:00
raise CommandError("Too many arguments")
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
return self.remove_cache_items(options, ["*"])
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
def _cache_dir(self, options: Values, subdir: str) -> str:
2022-07-17 01:48:29 +08:00
return os.path.join(options.cache_dir, subdir)
2022-07-21 08:44:10 +08:00
def _find_http_files(self, options: Values) -> List[str]:
http_dir = self._cache_dir(options, "http")
return filesystem.find_files(http_dir, "*")
2022-07-17 01:48:29 +08:00
2022-07-21 08:44:10 +08:00
def _find_wheels(self, options: Values, pattern: str) -> List[str]:
wheel_dir = self._cache_dir(options, "wheels")
2022-07-17 01:48:29 +08:00
# The wheel filename format, as specified in PEP 427, is:
# {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
#
# Additionally, non-alphanumeric values in the distribution are
# normalized to underscores (_), meaning hyphens can never occur
# before `-{version}`.
#
# Given that information:
# - If the pattern we're given contains a hyphen (-), the user is
# providing at least the version. Thus, we can just append `*.whl`
# to match the rest of it.
# - If the pattern we're given doesn't contain a hyphen (-), the
# user is only providing the name. Thus, we append `-*.whl` to
# match the hyphen before the version, followed by anything else.
#
# PEP 427: https://www.python.org/dev/peps/pep-0427/
pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
return filesystem.find_files(wheel_dir, pattern)