cache.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import os
  2. import textwrap
  3. from optparse import Values
  4. from typing import Any, List
  5. import pip._internal.utils.filesystem as filesystem
  6. from pip._internal.cli.base_command import Command
  7. from pip._internal.cli.status_codes import ERROR, SUCCESS
  8. from pip._internal.exceptions import CommandError, PipError
  9. from pip._internal.utils.logging import getLogger
  10. logger = getLogger(__name__)
  11. class CacheCommand(Command):
  12. """
  13. Inspect and manage pip's wheel cache.
  14. Subcommands:
  15. - dir: Show the cache directory.
  16. - info: Show information about the cache.
  17. - list: List filenames of packages stored in the cache.
  18. - remove: Remove one or more package from the cache.
  19. - purge: Remove all items from the cache.
  20. ``<pattern>`` can be a glob expression or a package name.
  21. """
  22. ignore_require_venv = True
  23. usage = """
  24. %prog dir
  25. %prog info
  26. %prog list [<pattern>] [--format=[human, abspath]]
  27. %prog remove <pattern>
  28. %prog purge
  29. """
  30. def add_options(self) -> None:
  31. self.cmd_opts.add_option(
  32. "--format",
  33. action="store",
  34. dest="list_format",
  35. default="human",
  36. choices=("human", "abspath"),
  37. help="Select the output format among: human (default) or abspath",
  38. )
  39. self.parser.insert_option_group(0, self.cmd_opts)
  40. def run(self, options: Values, args: List[str]) -> int:
  41. handlers = {
  42. "dir": self.get_cache_dir,
  43. "info": self.get_cache_info,
  44. "list": self.list_cache_items,
  45. "remove": self.remove_cache_items,
  46. "purge": self.purge_cache,
  47. }
  48. if not options.cache_dir:
  49. logger.error("pip cache commands can not function since cache is disabled.")
  50. return ERROR
  51. # Determine action
  52. if not args or args[0] not in handlers:
  53. logger.error(
  54. "Need an action (%s) to perform.",
  55. ", ".join(sorted(handlers)),
  56. )
  57. return ERROR
  58. action = args[0]
  59. # Error handling happens here, not in the action-handlers.
  60. try:
  61. handlers[action](options, args[1:])
  62. except PipError as e:
  63. logger.error(e.args[0])
  64. return ERROR
  65. return SUCCESS
  66. def get_cache_dir(self, options: Values, args: List[Any]) -> None:
  67. if args:
  68. raise CommandError("Too many arguments")
  69. logger.info(options.cache_dir)
  70. def get_cache_info(self, options: Values, args: List[Any]) -> None:
  71. if args:
  72. raise CommandError("Too many arguments")
  73. num_http_files = len(self._find_http_files(options))
  74. num_packages = len(self._find_wheels(options, "*"))
  75. http_cache_location = self._cache_dir(options, "http")
  76. wheels_cache_location = self._cache_dir(options, "wheels")
  77. http_cache_size = filesystem.format_directory_size(http_cache_location)
  78. wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)
  79. message = (
  80. textwrap.dedent(
  81. """
  82. Package index page cache location: {http_cache_location}
  83. Package index page cache size: {http_cache_size}
  84. Number of HTTP files: {num_http_files}
  85. Locally built wheels location: {wheels_cache_location}
  86. Locally built wheels size: {wheels_cache_size}
  87. Number of locally built wheels: {package_count}
  88. """
  89. )
  90. .format(
  91. http_cache_location=http_cache_location,
  92. http_cache_size=http_cache_size,
  93. num_http_files=num_http_files,
  94. wheels_cache_location=wheels_cache_location,
  95. package_count=num_packages,
  96. wheels_cache_size=wheels_cache_size,
  97. )
  98. .strip()
  99. )
  100. logger.info(message)
  101. def list_cache_items(self, options: Values, args: List[Any]) -> None:
  102. if len(args) > 1:
  103. raise CommandError("Too many arguments")
  104. if args:
  105. pattern = args[0]
  106. else:
  107. pattern = "*"
  108. files = self._find_wheels(options, pattern)
  109. if options.list_format == "human":
  110. self.format_for_human(files)
  111. else:
  112. self.format_for_abspath(files)
  113. def format_for_human(self, files: List[str]) -> None:
  114. if not files:
  115. logger.info("No locally built wheels cached.")
  116. return
  117. results = []
  118. for filename in files:
  119. wheel = os.path.basename(filename)
  120. size = filesystem.format_file_size(filename)
  121. results.append(f" - {wheel} ({size})")
  122. logger.info("Cache contents:\n")
  123. logger.info("\n".join(sorted(results)))
  124. def format_for_abspath(self, files: List[str]) -> None:
  125. if not files:
  126. return
  127. results = []
  128. for filename in files:
  129. results.append(filename)
  130. logger.info("\n".join(sorted(results)))
  131. def remove_cache_items(self, options: Values, args: List[Any]) -> None:
  132. if len(args) > 1:
  133. raise CommandError("Too many arguments")
  134. if not args:
  135. raise CommandError("Please provide a pattern")
  136. files = self._find_wheels(options, args[0])
  137. no_matching_msg = "No matching packages"
  138. if args[0] == "*":
  139. # Only fetch http files if no specific pattern given
  140. files += self._find_http_files(options)
  141. else:
  142. # Add the pattern to the log message
  143. no_matching_msg += ' for pattern "{}"'.format(args[0])
  144. if not files:
  145. logger.warning(no_matching_msg)
  146. for filename in files:
  147. os.unlink(filename)
  148. logger.verbose("Removed %s", filename)
  149. logger.info("Files removed: %s", len(files))
  150. def purge_cache(self, options: Values, args: List[Any]) -> None:
  151. if args:
  152. raise CommandError("Too many arguments")
  153. return self.remove_cache_items(options, ["*"])
  154. def _cache_dir(self, options: Values, subdir: str) -> str:
  155. return os.path.join(options.cache_dir, subdir)
  156. def _find_http_files(self, options: Values) -> List[str]:
  157. http_dir = self._cache_dir(options, "http")
  158. return filesystem.find_files(http_dir, "*")
  159. def _find_wheels(self, options: Values, pattern: str) -> List[str]:
  160. wheel_dir = self._cache_dir(options, "wheels")
  161. # The wheel filename format, as specified in PEP 427, is:
  162. # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
  163. #
  164. # Additionally, non-alphanumeric values in the distribution are
  165. # normalized to underscores (_), meaning hyphens can never occur
  166. # before `-{version}`.
  167. #
  168. # Given that information:
  169. # - If the pattern we're given contains a hyphen (-), the user is
  170. # providing at least the version. Thus, we can just append `*.whl`
  171. # to match the rest of it.
  172. # - If the pattern we're given doesn't contain a hyphen (-), the
  173. # user is only providing the name. Thus, we append `-*.whl` to
  174. # match the hyphen before the version, followed by anything else.
  175. #
  176. # PEP 427: https://www.python.org/dev/peps/pep-0427/
  177. pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
  178. return filesystem.find_files(wheel_dir, pattern)