|
8 | 8 |
|
9 | 9 | import json |
10 | 10 | from collections import defaultdict |
| 11 | +from contextlib import suppress |
11 | 12 |
|
12 | 13 | from django import forms |
13 | 14 | from django.core.exceptions import ValidationError |
@@ -768,22 +769,34 @@ def import_dependency(self, dependency_data): |
768 | 769 |
|
769 | 770 | def look_for_existing_package(self, package_data): |
770 | 771 | package = None |
771 | | - unique_together_lookups = { |
| 772 | + package_qs = Package.objects.scope(self.user.dataspace) |
| 773 | + |
| 774 | + # 1. Check if the Package already exists in the local Dataspace |
| 775 | + # Using exact match first: purl + download_url + filename |
| 776 | + exact_match_lookups = { |
772 | 777 | field: package_data.get(field, "") for field in self.unique_together_fields |
773 | 778 | } |
774 | | - |
775 | | - # Check if the Package already exists in the local Dataspace |
776 | | - try: |
777 | | - package = Package.objects.scope(self.user.dataspace).get(**unique_together_lookups) |
| 779 | + with suppress(ObjectDoesNotExist): |
| 780 | + package = package_qs.get(**exact_match_lookups) |
778 | 781 | self.existing["package"].append(str(package)) |
779 | | - except ObjectDoesNotExist: |
780 | | - package = None |
| 782 | + return package |
| 783 | + |
| 784 | + # 2. If the package data does not include a download_url value: |
| 785 | + # Attemp to find an existing package using purl-only match. |
| 786 | + if not package_data.get("download_url"): |
| 787 | + purl_lookups = {field: package_data.get(field, "") for field in PACKAGE_URL_FIELDS} |
| 788 | + same_purl_packages = package_qs.filter(**purl_lookups) |
| 789 | + if len(same_purl_packages) == 1: |
| 790 | + package = same_purl_packages[0] |
| 791 | + self.existing["package"].append(str(package)) |
| 792 | + return package |
781 | 793 |
|
782 | 794 | # Check if the Package already exists in the reference Dataspace |
| 795 | + # Using exact match only: purl + download_url + filename |
783 | 796 | reference_dataspace = Dataspace.objects.get_reference() |
784 | 797 | user_dataspace = self.user.dataspace |
785 | 798 | if not package and user_dataspace != reference_dataspace: |
786 | | - qs = Package.objects.scope(reference_dataspace).filter(**unique_together_lookups) |
| 799 | + qs = Package.objects.scope(reference_dataspace).filter(**exact_match_lookups) |
787 | 800 | if qs.exists(): |
788 | 801 | reference_object = qs.first() |
789 | 802 | try: |
|
0 commit comments