cache.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. from __future__ import absolute_import
  2. import logging
  3. import os
  4. import textwrap
  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.typing import MYPY_CHECK_RUNNING
  10. if MYPY_CHECK_RUNNING:
  11. from optparse import Values
  12. from typing import Any, List
  13. logger = logging.getLogger(__name__)
  14. class CacheCommand(Command):
  15. """
  16. Inspect and manage pip's wheel cache.
  17. Subcommands:
  18. dir: Show the cache directory.
  19. info: Show information about the cache.
  20. list: List filenames of packages stored in the cache.
  21. remove: Remove one or more package from the cache.
  22. purge: Remove all items from the cache.
  23. <pattern> can be a glob expression or a package name.
  24. """
  25. ignore_require_venv = True
  26. usage = """
  27. %prog dir
  28. %prog info
  29. %prog list [<pattern>]
  30. %prog remove <pattern>
  31. %prog purge
  32. """
  33. def run(self, options, args):
  34. # type: (Values, List[Any]) -> int
  35. handlers = {
  36. "dir": self.get_cache_dir,
  37. "info": self.get_cache_info,
  38. "list": self.list_cache_items,
  39. "remove": self.remove_cache_items,
  40. "purge": self.purge_cache,
  41. }
  42. if not options.cache_dir:
  43. logger.error("pip cache commands can not "
  44. "function since cache is disabled.")
  45. return ERROR
  46. # Determine action
  47. if not args or args[0] not in handlers:
  48. logger.error("Need an action ({}) to perform.".format(
  49. ", ".join(sorted(handlers)))
  50. )
  51. return ERROR
  52. action = args[0]
  53. # Error handling happens here, not in the action-handlers.
  54. try:
  55. handlers[action](options, args[1:])
  56. except PipError as e:
  57. logger.error(e.args[0])
  58. return ERROR
  59. return SUCCESS
  60. def get_cache_dir(self, options, args):
  61. # type: (Values, List[Any]) -> None
  62. if args:
  63. raise CommandError('Too many arguments')
  64. logger.info(options.cache_dir)
  65. def get_cache_info(self, options, args):
  66. # type: (Values, List[Any]) -> None
  67. if args:
  68. raise CommandError('Too many arguments')
  69. num_packages = len(self._find_wheels(options, '*'))
  70. cache_location = self._wheels_cache_dir(options)
  71. cache_size = filesystem.format_directory_size(cache_location)
  72. message = textwrap.dedent("""
  73. Location: {location}
  74. Size: {size}
  75. Number of wheels: {package_count}
  76. """).format(
  77. location=cache_location,
  78. package_count=num_packages,
  79. size=cache_size,
  80. ).strip()
  81. logger.info(message)
  82. def list_cache_items(self, options, args):
  83. # type: (Values, List[Any]) -> None
  84. if len(args) > 1:
  85. raise CommandError('Too many arguments')
  86. if args:
  87. pattern = args[0]
  88. else:
  89. pattern = '*'
  90. files = self._find_wheels(options, pattern)
  91. if not files:
  92. logger.info('Nothing cached.')
  93. return
  94. results = []
  95. for filename in files:
  96. wheel = os.path.basename(filename)
  97. size = filesystem.format_file_size(filename)
  98. results.append(' - {} ({})'.format(wheel, size))
  99. logger.info('Cache contents:\n')
  100. logger.info('\n'.join(sorted(results)))
  101. def remove_cache_items(self, options, args):
  102. # type: (Values, List[Any]) -> None
  103. if len(args) > 1:
  104. raise CommandError('Too many arguments')
  105. if not args:
  106. raise CommandError('Please provide a pattern')
  107. files = self._find_wheels(options, args[0])
  108. if not files:
  109. raise CommandError('No matching packages')
  110. for filename in files:
  111. os.unlink(filename)
  112. logger.debug('Removed %s', filename)
  113. logger.info('Files removed: %s', len(files))
  114. def purge_cache(self, options, args):
  115. # type: (Values, List[Any]) -> None
  116. if args:
  117. raise CommandError('Too many arguments')
  118. return self.remove_cache_items(options, ['*'])
  119. def _wheels_cache_dir(self, options):
  120. # type: (Values) -> str
  121. return os.path.join(options.cache_dir, 'wheels')
  122. def _find_wheels(self, options, pattern):
  123. # type: (Values, str) -> List[str]
  124. wheel_dir = self._wheels_cache_dir(options)
  125. # The wheel filename format, as specified in PEP 427, is:
  126. # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
  127. #
  128. # Additionally, non-alphanumeric values in the distribution are
  129. # normalized to underscores (_), meaning hyphens can never occur
  130. # before `-{version}`.
  131. #
  132. # Given that information:
  133. # - If the pattern we're given contains a hyphen (-), the user is
  134. # providing at least the version. Thus, we can just append `*.whl`
  135. # to match the rest of it.
  136. # - If the pattern we're given doesn't contain a hyphen (-), the
  137. # user is only providing the name. Thus, we append `-*.whl` to
  138. # match the hyphen before the version, followed by anything else.
  139. #
  140. # PEP 427: https://www.python.org/dev/peps/pep-0427/
  141. pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
  142. return filesystem.find_files(wheel_dir, pattern)