index.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import logging
  2. from optparse import Values
  3. from typing import Any, Iterable, List, Optional, Union
  4. from pip._vendor.packaging.version import LegacyVersion, Version
  5. from pip._internal.cli import cmdoptions
  6. from pip._internal.cli.req_command import IndexGroupCommand
  7. from pip._internal.cli.status_codes import ERROR, SUCCESS
  8. from pip._internal.commands.search import print_dist_installation_info
  9. from pip._internal.exceptions import CommandError, DistributionNotFound, PipError
  10. from pip._internal.index.collector import LinkCollector
  11. from pip._internal.index.package_finder import PackageFinder
  12. from pip._internal.models.selection_prefs import SelectionPreferences
  13. from pip._internal.models.target_python import TargetPython
  14. from pip._internal.network.session import PipSession
  15. from pip._internal.utils.misc import write_output
  16. logger = logging.getLogger(__name__)
  17. class IndexCommand(IndexGroupCommand):
  18. """
  19. Inspect information available from package indexes.
  20. """
  21. usage = """
  22. %prog versions <package>
  23. """
  24. def add_options(self) -> None:
  25. cmdoptions.add_target_python_options(self.cmd_opts)
  26. self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
  27. self.cmd_opts.add_option(cmdoptions.pre())
  28. self.cmd_opts.add_option(cmdoptions.no_binary())
  29. self.cmd_opts.add_option(cmdoptions.only_binary())
  30. index_opts = cmdoptions.make_option_group(
  31. cmdoptions.index_group,
  32. self.parser,
  33. )
  34. self.parser.insert_option_group(0, index_opts)
  35. self.parser.insert_option_group(0, self.cmd_opts)
  36. def run(self, options: Values, args: List[str]) -> int:
  37. handlers = {
  38. "versions": self.get_available_package_versions,
  39. }
  40. logger.warning(
  41. "pip index is currently an experimental command. "
  42. "It may be removed/changed in a future release "
  43. "without prior warning."
  44. )
  45. # Determine action
  46. if not args or args[0] not in handlers:
  47. logger.error(
  48. "Need an action (%s) to perform.",
  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 _build_package_finder(
  61. self,
  62. options: Values,
  63. session: PipSession,
  64. target_python: Optional[TargetPython] = None,
  65. ignore_requires_python: Optional[bool] = None,
  66. ) -> PackageFinder:
  67. """
  68. Create a package finder appropriate to the index command.
  69. """
  70. link_collector = LinkCollector.create(session, options=options)
  71. # Pass allow_yanked=False to ignore yanked versions.
  72. selection_prefs = SelectionPreferences(
  73. allow_yanked=False,
  74. allow_all_prereleases=options.pre,
  75. ignore_requires_python=ignore_requires_python,
  76. )
  77. return PackageFinder.create(
  78. link_collector=link_collector,
  79. selection_prefs=selection_prefs,
  80. target_python=target_python,
  81. use_deprecated_html5lib="html5lib" in options.deprecated_features_enabled,
  82. )
  83. def get_available_package_versions(self, options: Values, args: List[Any]) -> None:
  84. if len(args) != 1:
  85. raise CommandError("You need to specify exactly one argument")
  86. target_python = cmdoptions.make_target_python(options)
  87. query = args[0]
  88. with self._build_session(options) as session:
  89. finder = self._build_package_finder(
  90. options=options,
  91. session=session,
  92. target_python=target_python,
  93. ignore_requires_python=options.ignore_requires_python,
  94. )
  95. versions: Iterable[Union[LegacyVersion, Version]] = (
  96. candidate.version for candidate in finder.find_all_candidates(query)
  97. )
  98. if not options.pre:
  99. # Remove prereleases
  100. versions = (
  101. version for version in versions if not version.is_prerelease
  102. )
  103. versions = set(versions)
  104. if not versions:
  105. raise DistributionNotFound(
  106. "No matching distribution found for {}".format(query)
  107. )
  108. formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)]
  109. latest = formatted_versions[0]
  110. write_output("{} ({})".format(query, latest))
  111. write_output("Available versions: {}".format(", ".join(formatted_versions)))
  112. print_dist_installation_info(query, latest)