cache.py 7.2 KB

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