You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

search.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # The following comment should be removed at some point in the future.
  2. # mypy: disallow-untyped-defs=False
  3. from __future__ import absolute_import
  4. import logging
  5. import sys
  6. import textwrap
  7. from collections import OrderedDict
  8. from pip._vendor import pkg_resources
  9. from pip._vendor.packaging.version import parse as parse_version
  10. # NOTE: XMLRPC Client is not annotated in typeshed as on 2017-07-17, which is
  11. # why we ignore the type on this import
  12. from pip._vendor.six.moves import xmlrpc_client # type: ignore
  13. from pip._internal.cli.base_command import Command
  14. from pip._internal.cli.req_command import SessionCommandMixin
  15. from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS
  16. from pip._internal.exceptions import CommandError
  17. from pip._internal.models.index import PyPI
  18. from pip._internal.network.xmlrpc import PipXmlrpcTransport
  19. from pip._internal.utils.compat import get_terminal_size
  20. from pip._internal.utils.logging import indent_log
  21. from pip._internal.utils.misc import write_output
  22. logger = logging.getLogger(__name__)
  23. class SearchCommand(Command, SessionCommandMixin):
  24. """Search for PyPI packages whose name or summary contains <query>."""
  25. usage = """
  26. %prog [options] <query>"""
  27. ignore_require_venv = True
  28. def __init__(self, *args, **kw):
  29. super(SearchCommand, self).__init__(*args, **kw)
  30. self.cmd_opts.add_option(
  31. '-i', '--index',
  32. dest='index',
  33. metavar='URL',
  34. default=PyPI.pypi_url,
  35. help='Base URL of Python Package Index (default %default)')
  36. self.parser.insert_option_group(0, self.cmd_opts)
  37. def run(self, options, args):
  38. if not args:
  39. raise CommandError('Missing required argument (search query).')
  40. query = args
  41. pypi_hits = self.search(query, options)
  42. hits = transform_hits(pypi_hits)
  43. terminal_width = None
  44. if sys.stdout.isatty():
  45. terminal_width = get_terminal_size()[0]
  46. print_results(hits, terminal_width=terminal_width)
  47. if pypi_hits:
  48. return SUCCESS
  49. return NO_MATCHES_FOUND
  50. def search(self, query, options):
  51. index_url = options.index
  52. session = self.get_default_session(options)
  53. transport = PipXmlrpcTransport(index_url, session)
  54. pypi = xmlrpc_client.ServerProxy(index_url, transport)
  55. hits = pypi.search({'name': query, 'summary': query}, 'or')
  56. return hits
  57. def transform_hits(hits):
  58. """
  59. The list from pypi is really a list of versions. We want a list of
  60. packages with the list of versions stored inline. This converts the
  61. list from pypi into one we can use.
  62. """
  63. packages = OrderedDict()
  64. for hit in hits:
  65. name = hit['name']
  66. summary = hit['summary']
  67. version = hit['version']
  68. if name not in packages.keys():
  69. packages[name] = {
  70. 'name': name,
  71. 'summary': summary,
  72. 'versions': [version],
  73. }
  74. else:
  75. packages[name]['versions'].append(version)
  76. # if this is the highest version, replace summary and score
  77. if version == highest_version(packages[name]['versions']):
  78. packages[name]['summary'] = summary
  79. return list(packages.values())
  80. def print_results(hits, name_column_width=None, terminal_width=None):
  81. if not hits:
  82. return
  83. if name_column_width is None:
  84. name_column_width = max([
  85. len(hit['name']) + len(highest_version(hit.get('versions', ['-'])))
  86. for hit in hits
  87. ]) + 4
  88. installed_packages = [p.project_name for p in pkg_resources.working_set]
  89. for hit in hits:
  90. name = hit['name']
  91. summary = hit['summary'] or ''
  92. latest = highest_version(hit.get('versions', ['-']))
  93. if terminal_width is not None:
  94. target_width = terminal_width - name_column_width - 5
  95. if target_width > 10:
  96. # wrap and indent summary to fit terminal
  97. summary = textwrap.wrap(summary, target_width)
  98. summary = ('\n' + ' ' * (name_column_width + 3)).join(summary)
  99. line = '%-*s - %s' % (name_column_width,
  100. '%s (%s)' % (name, latest), summary)
  101. try:
  102. write_output(line)
  103. if name in installed_packages:
  104. dist = pkg_resources.get_distribution(name)
  105. with indent_log():
  106. if dist.version == latest:
  107. write_output('INSTALLED: %s (latest)', dist.version)
  108. else:
  109. write_output('INSTALLED: %s', dist.version)
  110. if parse_version(latest).pre:
  111. write_output('LATEST: %s (pre-release; install'
  112. ' with "pip install --pre")', latest)
  113. else:
  114. write_output('LATEST: %s', latest)
  115. except UnicodeEncodeError:
  116. pass
  117. def highest_version(versions):
  118. return max(versions, key=parse_version)