search.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 = '{name_latest:{name_column_width}} - {summary}'.format(
  100. name_latest='{name} ({latest})'.format(**locals()),
  101. **locals())
  102. try:
  103. write_output(line)
  104. if name in installed_packages:
  105. dist = pkg_resources.get_distribution(name)
  106. with indent_log():
  107. if dist.version == latest:
  108. write_output('INSTALLED: %s (latest)', dist.version)
  109. else:
  110. write_output('INSTALLED: %s', dist.version)
  111. if parse_version(latest).pre:
  112. write_output('LATEST: %s (pre-release; install'
  113. ' with "pip install --pre")', latest)
  114. else:
  115. write_output('LATEST: %s', latest)
  116. except UnicodeEncodeError:
  117. pass
  118. def highest_version(versions):
  119. return max(versions, key=parse_version)