Skip to content

Commit 32854a0

Browse files
committed
Extract FastSearch class to encapsulate search calculations
1 parent d87acc2 commit 32854a0

File tree

1 file changed

+29
-15
lines changed

1 file changed

+29
-15
lines changed

importlib_metadata/__init__.py

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -413,12 +413,33 @@ def zip_children(self):
413413
for child in names
414414
)
415415

416-
def is_egg(self, normalized, prefix):
416+
def is_egg(self, search):
417417
root_n_low = os.path.split(self.root)[1].lower()
418418

419419
return (
420-
root_n_low == normalized + '.egg'
421-
or root_n_low.startswith(prefix) and root_n_low.endswith('.egg'))
420+
root_n_low == search.normalized + '.egg'
421+
or root_n_low.startswith(search.prefix)
422+
and root_n_low.endswith('.egg'))
423+
424+
425+
class FastSearch:
426+
"""
427+
Micro-optimized class for searching for an
428+
optional package name in list of children.
429+
"""
430+
normalized = ''
431+
prefix = ''
432+
suffixes = '.dist-info', '.egg-info'
433+
exact_matches = []
434+
435+
def __init__(self, name):
436+
self.name = name
437+
if name is None:
438+
return
439+
self.normalized = name.lower().replace('-', '_')
440+
self.prefix = self.normalized + '-'
441+
self.exact_matches = [
442+
self.normalized + suffix for suffix in self.suffixes]
422443

423444

424445
@install
@@ -445,26 +466,19 @@ def find_distributions(self, context=DistributionFinder.Context()):
445466
def _search_paths(cls, name, paths):
446467
"""Find metadata directories in paths heuristically."""
447468
return itertools.chain.from_iterable(
448-
cls._search_path(path, name)
469+
cls._search_path(path, FastSearch(name))
449470
for path in map(FastPath, paths)
450471
)
451472

452473
@classmethod
453474
def _search_path(cls, root, name):
454-
if name is not None:
455-
normalized = name.lower().replace('-', '_')
456-
prefix = normalized + '-'
457-
else:
458-
normalized = prefix = ''
459-
suffixes = ('.dist-info', '.egg-info')
460-
exact_matches = [normalized + suffix for suffix in suffixes]
461475
for child in root.children():
462476
n_low = child.lower()
463-
if (n_low in exact_matches
464-
or n_low.startswith(prefix) and n_low.endswith(suffixes)
477+
if (n_low in name.exact_matches
478+
or n_low.startswith(name.prefix)
479+
and n_low.endswith(name.suffixes)
465480
# legacy case:
466-
or root.is_egg(normalized, prefix)
467-
and n_low == 'egg-info'):
481+
or root.is_egg(name) and n_low == 'egg-info'):
468482
yield root.path_type(root.root, child)
469483

470484

0 commit comments

Comments
 (0)