Skip to content

Commit

Permalink
Cache to avoid manually selecting packages/distributions multiple times
Browse files Browse the repository at this point in the history
Signed-off-by: Xiaochao Dong (@damnever) <the.xcdong@gmail.com>
  • Loading branch information
damnever committed Dec 18, 2024
1 parent 755aed7 commit 889aa96
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions pigar/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def __init__(self, project_root):
distributions=self._installed_dists.values()
)
self._requirements = _LocatableRequirements()
self._cached_choices = dict()
self._uncertain_requirements = collections.defaultdict(
_LocatableRequirements
) # Multiple requirements for same import name.
Expand Down Expand Up @@ -394,15 +395,15 @@ def write_requirements(

if self._uncertain_requirements:
stream.write(
'\nWARNING(pigar): some manual fixes are required since pigar has found duplicate requirements for the same import name.\n'
'\n# WARNING(pigar): some manual fixes might be required as pigar has detected duplicate requirements for the same import name (possibly for different submodules).\n' # noqa: E501
)
uncertain_requirements = sorted(
self._uncertain_requirements.items(),
key=lambda item: item[0].lower()
)
for import_name, reqs in uncertain_requirements:
stream.write(
f'# WARNING(pigar): the following duplicate requirements are for import name: {import_name}\n'
f'# WARNING(pigar): the following duplicate requirements are for the import name: {import_name}\n' # noqa: E501
)
with_ref_comments_once = with_ref_comments
for _, req in reqs.sorted_items():
Expand Down Expand Up @@ -461,6 +462,10 @@ def _maybe_filter_distributions_with_same_import_name(
):
if dists_filter is None or len(distributions) <= 1:
return distributions
# We can use `functools.cache` in later versions of Python.
existing = self._cached_choices.get(import_name, None)
if existing is not None:
return existing

assert (hasattr(distributions[0], 'name'))

Expand All @@ -481,7 +486,11 @@ def _maybe_filter_distributions_with_same_import_name(
best_match = casefold_match
if best_match is None and len(contains) == 1:
best_match = contains[0]
return dists_filter(import_name, locations, distributions, best_match)
choosed = dists_filter(
import_name, locations, distributions, best_match
)
self._cached_choices[import_name] = choosed
return choosed


class LocalRequirementWithLatestVersion(NamedTuple):
Expand Down

0 comments on commit 889aa96

Please sign in to comment.