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

Cache to avoid manually selecting packages/distributions multiple times #223

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading