Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a simple order strategy for result of search command #4131

Closed
wants to merge 5 commits into from
Closed
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions pip/commands/search.py
@@ -1,8 +1,10 @@

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unnecessary.

from __future__ import absolute_import

import logging
import sys
import textwrap
import re
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Global imports should be alphabetically ordered

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it. Modified.


from pip.basecommand import Command, SUCCESS
from pip.compat import OrderedDict
Expand Down Expand Up @@ -44,6 +46,7 @@ def run(self, options, args):
query = args
pypi_hits = self.search(query, options)
hits = transform_hits(pypi_hits)
hits = sort_hits(query, hits)

terminal_width = None
if sys.stdout.isatty():
Expand Down Expand Up @@ -131,3 +134,38 @@ def print_results(hits, name_column_width=None, terminal_width=None):

def highest_version(versions):
return max(versions, key=parse_version)


def sort_hits(query, hits):
if len(query) != 1:
# Now only handle the easiest condition,
# which is possibly the most frequent condition
return hits
query = query[0]
p = re.compile(query)
p_ignorecase = re.compile(query, re.IGNORECASE)
for item in hits:
item['match_score'] = 0
name = item['name']
summary = item['summary'] or ''
m1 = p.match(name)
m2 = p_ignorecase.match(name)
m3 = p_ignorecase.findall(name)
m4 = p_ignorecase.findall(summary)

# Ordering strategy
if name == query:
item['match_score'] += 10000
elif name.lower() == query.lower():
item['match_score'] += 9000
if m1 is not None:
item['match_score'] += 1000
elif m2 is not None:
item['match_score'] += 900
elif m3 is not None:
item['match_score'] += 800
if m4 is not None:
item['match_score'] += len(m3) + len(m4)

hits.sort(key=lambda i: i['match_score'], reverse=True)
return hits