-
-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathd2d.py
More file actions
2554 lines (2111 loc) · 90.5 KB
/
Copy pathd2d.py
File metadata and controls
2554 lines (2111 loc) · 90.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: Apache-2.0
#
# http://nexb.com and https://github.com/aboutcode-org/scancode.io
# The ScanCode.io software is licensed under the Apache License version 2.0.
# Data generated with ScanCode.io is provided as-is without warranties.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# Data Generated with ScanCode.io is provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# ScanCode.io should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
#
# ScanCode.io is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/aboutcode-org/scancode.io for support and download.
import re
from collections import Counter
from collections import defaultdict
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from re import match as regex_match
from django.contrib.postgres.aggregates.general import ArrayAgg
from django.core.exceptions import MultipleObjectsReturned
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F
from django.db.models import Q
from django.db.models import Value
from django.db.models.expressions import Subquery
from django.db.models.functions import Concat
from django.template.defaultfilters import pluralize
from binary_inspector.binary import collect_and_parse_macho_symbols
from binary_inspector.binary import collect_and_parse_winpe_symbols
from commoncode.paths import common_prefix
from elf_inspector.binary import collect_and_parse_elf_symbols
from elf_inspector.dwarf import get_dwarf_paths
from extractcode import EXTRACT_SUFFIX
from go_inspector.plugin import collect_and_parse_symbols
from packagedcode.npm import NpmPackageJsonHandler
from rust_inspector.binary import collect_and_parse_rust_symbols
from summarycode.classify import LEGAL_STARTS_ENDS
from aboutcode.pipeline import LoopProgress
from scanpipe import pipes
from scanpipe.models import CodebaseRelation
from scanpipe.models import CodebaseResource
from scanpipe.models import convert_glob_to_django_regex
from scanpipe.pipes import d2d_config
from scanpipe.pipes import flag
from scanpipe.pipes import get_resource_diff_ratio
from scanpipe.pipes import js
from scanpipe.pipes import jvm
from scanpipe.pipes import pathmap
from scanpipe.pipes import purldb
from scanpipe.pipes import resolve
from scanpipe.pipes import scancode
from scanpipe.pipes import stringmap
from scanpipe.pipes import symbolmap
from scanpipe.pipes import symbols
FROM = "from/"
TO = "to/"
def get_inputs(project):
"""
Locate the ``from`` and ``to`` input files in project inputs/ directory.
The input source can be flagged using a "from-" / "to-" prefix in the filename or
by adding a "#from" / "#to" fragment at the end of the download URL.
"""
from_files = list(project.inputs("from*"))
from_files.extend([input.path for input in project.inputsources.filter(tag="from")])
to_files = list(project.inputs("to*"))
to_files.extend([input.path for input in project.inputsources.filter(tag="to")])
if len(from_files) < 1:
raise FileNotFoundError("from* input files not found.")
if len(to_files) < 1:
raise FileNotFoundError("to* input files not found.")
return from_files, to_files
def get_extracted_path(resource):
"""Return the ``-extract/`` extracted path of provided ``resource``."""
return resource.path + "-extract/"
def get_extracted_subpath(path):
"""Return the path segments located after the last ``-extract/`` segment."""
return path.split("-extract/")[-1]
def get_best_path_matches(to_resource, matches):
"""Return the best ``matches`` for the provided ``to_resource``."""
path_parts = Path(to_resource.path.lstrip("/")).parts
for path_parts_index in range(1, len(path_parts)):
subpath = "/".join(path_parts[path_parts_index:])
subpath_matches = [
from_resource
for from_resource in matches
if from_resource.path.endswith(subpath)
]
if subpath_matches:
return subpath_matches
return matches
def get_from_files_for_scanning(resources):
"""
Return resources in the "from/" side which has been mapped to the "to/"
side, but are not mapped using ABOUT files.
"""
mapped_from_files = resources.from_codebase().files().has_relation()
return mapped_from_files.filter(~Q(status=flag.ABOUT_MAPPED))
def _map_checksum_resource(to_resource, from_resources, checksum_field):
checksum_value = getattr(to_resource, checksum_field)
matches = from_resources.filter(**{checksum_field: checksum_value})
for match in get_best_path_matches(to_resource, matches):
pipes.make_relation(
from_resource=match,
to_resource=to_resource,
map_type=checksum_field,
)
def map_checksum(project, checksum_field, logger=None):
"""Map using checksum."""
project_files = project.codebaseresources.files().no_status()
from_resources = project_files.from_codebase().has_value(checksum_field)
to_resources = (
project_files.to_codebase().has_value(checksum_field).has_no_relation()
)
resource_count = to_resources.count()
if logger:
logger(
f"Mapping {resource_count:,d} to/ resources using {checksum_field} "
f"against from/ codebase"
)
resource_iterator = to_resources.iterator(chunk_size=2000)
progress = LoopProgress(resource_count, logger)
for to_resource in progress.iter(resource_iterator):
_map_checksum_resource(to_resource, from_resources, checksum_field)
def _map_jvm_to_class_resource(
to_resource, from_resources, from_classes_index, jvm_lang: jvm.JvmLanguage
):
"""
Map the ``to_resource`` .class file Resource with a Resource in
``from_resources`` source files, using the ``from_classes_index`` index of
from/ fully qualified binary files.
"""
for extension in jvm_lang.source_extensions:
# Perform basic conversion from .class to source file path
source_path = jvm_lang.get_source_path(
path=to_resource.path, extension=extension
)
# Perform basic mapping without normalization for scenarios listed in
# https://github.com/aboutcode-org/scancode.io/issues/1873
match = pathmap.find_paths(path=source_path, index=from_classes_index)
if not match:
normalized_path = jvm_lang.get_normalized_path(
path=to_resource.path, extension=extension
)
match = pathmap.find_paths(path=normalized_path, index=from_classes_index)
if not match:
return
for resource_id in match.resource_ids:
from_resource = from_resources.get(id=resource_id)
# compute the root of the packages on the source side
from_source_root_parts = from_resource.path.strip("/").split("/")
from_source_root = "/".join(
from_source_root_parts[: -match.matched_path_length]
)
pipes.make_relation(
from_resource=from_resource,
to_resource=to_resource,
map_type=jvm_lang.binary_map_type,
extra_data={"from_source_root": f"{from_source_root}/"},
)
def map_jvm_to_class(project, jvm_lang: jvm.JvmLanguage, logger=None):
"""
Map to/ compiled Jvm's binary files to from/ using Jvm language's fully
qualified paths and indexing from/ Jvm lang's source files.
"""
project_files = project.codebaseresources.files()
# Collect all files from "from_codebase", even if they already have a
# status or are mapped. This is necessary because the deploy codebase
# may contain sources that match "from_codebase" via checksum. If those
# checksum-matched files are excluded from mapping, it can result in
# .class files failing to resolve. See
# https://github.com/aboutcode-org/scancode.io/issues/1854#issuecomment-3273472895
from_resources = project_files.from_codebase()
to_resources = project_files.to_codebase().no_status().has_no_relation()
has_source_pkg_attr_name = {
f"extra_data__{jvm_lang.source_package_attribute_name}__isnull": False
}
to_resources_binary_extension = to_resources.filter(
extension__in=jvm_lang.binary_extensions
)
from_resources_source_extension = (
from_resources.filter(extension__in=jvm_lang.source_extensions)
# The source_package_attribute_name extra_data value
# is set during the `find_jvm_package`,
# it is required to build the index.
.filter(**has_source_pkg_attr_name)
)
to_resource_count = to_resources_binary_extension.count()
from_resource_count = from_resources_source_extension.count()
if not from_resource_count:
logger(f"No {jvm_lang.source_extensions} resources to map.")
return
if logger:
logger(
f"Mapping {to_resource_count:,d} .class (or other deployed file) "
f"resources to {from_resource_count:,d} {jvm_lang.source_extensions}"
)
# build an index using from-side fully qualified class file names
# built from the source_package_attribute_name and file name
indexables = jvm_lang.get_indexable_qualified_paths(from_resources_source_extension)
# we do not index subpath since we want to match only fully qualified names
from_classes_index = pathmap.build_index(indexables, with_subpaths=False)
resource_iterator = to_resources_binary_extension.iterator(chunk_size=2000)
progress = LoopProgress(to_resource_count, logger)
for to_resource in progress.iter(resource_iterator):
_map_jvm_to_class_resource(
to_resource=to_resource,
from_resources=from_resources,
from_classes_index=from_classes_index,
jvm_lang=jvm_lang,
)
def find_jvm_packages(project, jvm_lang: jvm.JvmLanguage, logger=None):
"""
Collect the JVM packages of source files for a ``project``.
Multiprocessing is enabled by default on this pipe, the number of processes
can be controlled through the SCANCODEIO_PROCESSES setting.
Note: we use the same API as the ScanCode scans by design
"""
resources = project.codebaseresources.files().no_status().from_codebase()
from_jvm_resources = resources.filter(extension__in=jvm_lang.source_extensions)
if logger:
logger(
f"Finding {jvm_lang.name} packages for {from_jvm_resources.count():,d} "
f"{jvm_lang.source_extensions} resources."
)
scancode.scan_resources(
resource_qs=from_jvm_resources,
scan_func=jvm_lang.scan_for_source_package,
save_func=save_jvm_package_scan_results,
progress_logger=logger,
)
def save_jvm_package_scan_results(codebase_resource, scan_results, scan_errors):
"""
Save the resource Jvm package scan results in the database as Resource.extra_data.
Create project errors if any occurred during the scan.
"""
# The status is only updated in case of errors.
if scan_errors:
codebase_resource.add_errors(scan_errors)
codebase_resource.update(status=flag.SCANNED_WITH_ERROR)
else:
codebase_resource.update_extra_data(scan_results)
def _map_jar_to_jvm_source_resource(
jar_resource, to_resources, from_resources, jvm_lang: jvm.JvmLanguage
):
jar_extracted_path = get_extracted_path(jar_resource)
jar_extracted_dot_class_files = list(
to_resources.filter(
extension__in=jvm_lang.binary_extensions,
path__startswith=jar_extracted_path,
).values("id", "status")
)
# Rely on the status flag to avoid triggering extra SQL queries.
not_mapped_dot_class = [
dot_class_file
for dot_class_file in jar_extracted_dot_class_files
if dot_class_file.get("status") == flag.NO_JAVA_SOURCE
]
# Do not continue if any .class files couldn't be mapped.
if any(not_mapped_dot_class):
return
# Using ids from already evaluated QuerySet to avoid triggering an expensive
# SQL subquery in the following CodebaseRelation QuerySet.
dot_class_file_ids = [
dot_class_file.get("id") for dot_class_file in jar_extracted_dot_class_files
]
jvm_binary_map_type_extra_data_list = CodebaseRelation.objects.filter(
to_resource__in=dot_class_file_ids, map_type=jvm_lang.binary_map_type
).values_list("extra_data", flat=True)
from_source_roots = [
extra_data.get("from_source_root", "")
for extra_data in jvm_binary_map_type_extra_data_list
]
if len(set(from_source_roots)) != 1:
# Could not determine a common root directory for the binary_map_type files
return
common_source_root = from_source_roots[0].rstrip("/")
if common_from_resource := from_resources.get_or_none(path=common_source_root):
pipes.make_relation(
from_resource=common_from_resource,
to_resource=jar_resource,
map_type="jar_to_source",
)
def map_jar_to_jvm_source(project, jvm_lang: jvm.JvmLanguage, logger=None):
"""Map .jar files to their related source directory."""
project_files = project.codebaseresources.files()
# Include the directories to map on the common source
from_resources = project.codebaseresources.from_codebase().has_no_relation()
to_resources = project_files.to_codebase()
to_jars = to_resources.filter(extension=".jar")
to_jars_count = to_jars.count()
if logger:
logger(
f"Mapping {to_jars_count:,d} .jar resources using map_jar_to_source "
f"against from/ codebase"
)
resource_iterator = to_jars.iterator(chunk_size=2000)
progress = LoopProgress(to_jars_count, logger)
for jar_resource in progress.iter(resource_iterator):
_map_jar_to_jvm_source_resource(
jar_resource, to_resources, from_resources, jvm_lang=jvm_lang
)
def _map_path_resource(
to_resource, from_resources, from_resources_index, diff_ratio_threshold=0.7
):
match = pathmap.find_paths(to_resource.path, from_resources_index)
if not match:
return
# Don't path map resource solely based on the file name.
if match.matched_path_length < 2:
return
# Only create relations when the number of matches if inferior or equal to
# the current number of path segment matched.
if len(match.resource_ids) > match.matched_path_length:
return
for resource_id in match.resource_ids:
from_resource = from_resources.get(id=resource_id)
diff_ratio = get_resource_diff_ratio(to_resource, from_resource)
if diff_ratio is not None and diff_ratio < diff_ratio_threshold:
continue
# Do not count the "to/" segment as it is not "matchable"
to_path_length = len(to_resource.path.split("/")) - 1
extra_data = {
"path_score": f"{match.matched_path_length}/{to_path_length}",
}
if diff_ratio:
extra_data["diff_ratio"] = f"{diff_ratio:.1%}"
pipes.make_relation(
from_resource=from_resource,
to_resource=to_resource,
map_type="path",
extra_data=extra_data,
)
def map_path(project, logger=None):
"""Map using path suffix similarities."""
project_files = project.codebaseresources.files().no_status()
from_resources = project_files.from_codebase()
to_resources = project_files.to_codebase().has_no_relation()
resource_count = to_resources.count()
if logger:
logger(
f"Mapping {resource_count:,d} to/ resources using path map "
f"against from/ codebase"
)
if not from_resources.exists():
logger("No from/ resources to map.")
return
from_resources_index = pathmap.build_index(
from_resources.values_list("id", "path"), with_subpaths=True
)
resource_iterator = to_resources.iterator(chunk_size=2000)
progress = LoopProgress(resource_count, logger)
for to_resource in progress.iter(resource_iterator):
_map_path_resource(to_resource, from_resources, from_resources_index)
def get_project_resources_qs(project, resources):
"""
Return a queryset of CodebaseResources from `project` containing the
CodebaseResources from `resources` . If a CodebaseResource in `resources` is
an archive or directory, then their descendants are also included in the
queryset.
Return None if `resources` is empty or None.
"""
lookups = Q()
for resource in resources or []:
lookups |= Q(path=resource.path)
if resource.is_archive:
# This is done to capture the extracted contents of the archive we
# matched to. Generally, the archive contents are in a directory
# that is the archive path with `-extract` at the end.
lookups |= Q(path__startswith=resource.path)
elif resource.is_dir:
# We add a trailing slash to avoid matching on directories we do not
# intend to. For example, if we have matched on the directory with
# the path `foo/bar/1`, using the __startswith filter without
# including a trailing slash on the path would have us get all
# directories under `foo/bar/` that start with 1, such as
# `foo/bar/10001`, `foo/bar/123`, etc., when we just want `foo/bar/1`
# and its descendants.
path = f"{resource.path}/"
lookups |= Q(path__startswith=path)
if lookups:
return project.codebaseresources.filter(lookups)
def create_package_from_purldb_data(project, resources, package_data, status):
"""
Create a DiscoveredPackage instance from PurlDB ``package_data``.
Return a tuple, containing the created DiscoveredPackage and the number of
CodebaseResources matched to PurlDB that are part of that DiscoveredPackage.
"""
package_data = package_data.copy()
# Do not re-use uuid from PurlDB as DiscoveredPackage.uuid is unique and a
# PurlDB match can be found in different projects.
package_data.pop("uuid", None)
package_data.pop("dependencies", None)
resources_qs = get_project_resources_qs(project, resources)
package = pipes.update_or_create_package(
project=project,
package_data=package_data,
codebase_resources=resources_qs,
)
# Get the number of already matched CodebaseResources from `resources_qs`
# before we update the status of all CodebaseResources from `resources_qs`,
# then subtract the number of already matched CodebaseResources from the
# total number of CodebaseResources updated. This is to prevent
# double-counting of CodebaseResources that were matched to purldb
purldb_statuses = [
flag.MATCHED_TO_PURLDB_PACKAGE,
flag.MATCHED_TO_PURLDB_RESOURCE,
flag.MATCHED_TO_PURLDB_DIRECTORY,
]
matched_resources_count = resources_qs.exclude(status__in=purldb_statuses).update(
status=status
)
return package, matched_resources_count
def match_purldb_package(
project, resources_by_sha1, enhance_package_data=True, **kwargs
):
"""
Given a mapping of lists of CodebaseResources by their sha1 values,
`resources_by_sha1`, send those sha1 values to purldb packages API endpoint,
process the matched Package data, then return the number of
CodebaseResources that were matched to a Package.
"""
match_count = 0
sha1_list = list(resources_by_sha1.keys())
if results := purldb.match_packages(
sha1_list=sha1_list,
enhance_package_data=enhance_package_data,
):
# Process matched Package data
for package_data in results:
sha1 = package_data["sha1"]
resources = resources_by_sha1.get(sha1) or []
if not resources:
continue
_, matched_resources_count = create_package_from_purldb_data(
project=project,
resources=resources,
package_data=package_data,
status=flag.MATCHED_TO_PURLDB_PACKAGE,
)
match_count += matched_resources_count
return match_count
def match_purldb_resource(
project, resources_by_sha1, package_data_by_purldb_urls=None, **kwargs
):
"""
Given a mapping of lists of CodebaseResources by their sha1 values,
`resources_by_sha1`, send those sha1 values to purldb resources API
endpoint, process the matched Package data, then return the number of
CodebaseResources that were matched to a Package.
`package_data_by_purldb_urls` is a mapping of package data by their purldb
package instance URLs. This is intended to be used as a cache, to avoid
retrieving package data we retrieved before.
"""
package_data_by_purldb_urls = package_data_by_purldb_urls or {}
match_count = 0
sha1_list = list(resources_by_sha1.keys())
if results := purldb.match_resources(sha1_list=sha1_list):
# Process match results
for result in results:
# Get package data
package_instance_url = result["package"]
if package_instance_url not in package_data_by_purldb_urls:
# Get and cache package data if we do not have it
if package_data := purldb.request_get(url=package_instance_url):
package_data_by_purldb_urls[package_instance_url] = package_data
else:
# Use cached package data
package_data = package_data_by_purldb_urls[package_instance_url]
sha1 = result["sha1"]
resources = resources_by_sha1.get(sha1) or []
if not (resources and package_data):
continue
_, matched_resources_count = create_package_from_purldb_data(
project=project,
resources=resources,
package_data=package_data,
status=flag.MATCHED_TO_PURLDB_RESOURCE,
)
match_count += matched_resources_count
return match_count
def match_purldb_directory(project, resource):
"""Match a single directory resource in the PurlDB."""
fingerprint = resource.extra_data.get("directory_content", "")
if results := purldb.match_directory(fingerprint=fingerprint):
package_url = results[0]["package"]
if package_data := purldb.request_get(url=package_url):
return create_package_from_purldb_data(
project, [resource], package_data, flag.MATCHED_TO_PURLDB_DIRECTORY
)
def match_sha1s_to_purldb(
project, resources_by_sha1, matcher_func, package_data_by_purldb_urls
):
"""
Process `resources_by_sha1` with `matcher_func` and return a 3-tuple
containing an empty defaultdict(list), the number of matches and the number
of sha1s sent to purldb.
"""
matched_count = matcher_func(
project=project,
resources_by_sha1=resources_by_sha1,
package_data_by_purldb_urls=package_data_by_purldb_urls,
)
sha1_count = len(resources_by_sha1)
# Clear out resources_by_sha1 when we are done with the current batch of
# CodebaseResources
resources_by_sha1 = defaultdict(list)
return resources_by_sha1, matched_count, sha1_count
def match_purldb_resources(
project, extensions, matcher_func, chunk_size=1000, logger=None
):
"""
Match against PurlDB selecting codebase resources using provided
``package_extensions`` for archive type files, and ``resource_extensions``.
Match requests are sent off in batches of 1000 SHA1s. This number is set
using `chunk_size`.
"""
to_resources = (
project.codebaseresources.files()
.to_codebase()
.no_status()
.has_value("sha1")
.filter(extension__in=extensions)
)
resource_count = to_resources.count()
extensions_str = ", ".join(extensions)
if logger:
if resource_count > 0:
logger(
f"Matching {resource_count:,d} {extensions_str} resources in PurlDB, "
"using SHA1"
)
else:
logger(
f"Skipping matching for {extensions_str} resources, "
f"as there are {resource_count:,d}"
)
_match_purldb_resources(
project=project,
to_resources=to_resources,
matcher_func=matcher_func,
chunk_size=chunk_size,
logger=logger,
)
def _match_purldb_resources(
project, to_resources, matcher_func, chunk_size=1000, logger=None
):
resource_count = to_resources.count()
resource_iterator = to_resources.iterator(chunk_size=chunk_size)
progress = LoopProgress(resource_count, logger)
total_matched_count = 0
total_sha1_count = 0
processed_resources_count = 0
resources_by_sha1 = defaultdict(list)
package_data_by_purldb_urls = {}
for to_resource in progress.iter(resource_iterator):
resources_by_sha1[to_resource.sha1].append(to_resource)
if (
to_resource.path.endswith(".map")
and "json" in to_resource.file_type.lower()
):
for js_sha1 in js.source_content_sha1_list(to_resource):
resources_by_sha1[js_sha1].append(to_resource)
processed_resources_count += 1
if processed_resources_count % chunk_size == 0:
resources_by_sha1, matched_count, sha1_count = match_sha1s_to_purldb(
project=project,
resources_by_sha1=resources_by_sha1,
matcher_func=matcher_func,
package_data_by_purldb_urls=package_data_by_purldb_urls,
)
total_matched_count += matched_count
total_sha1_count += sha1_count
if resources_by_sha1:
resources_by_sha1, matched_count, sha1_count = match_sha1s_to_purldb(
project=project,
resources_by_sha1=resources_by_sha1,
matcher_func=matcher_func,
package_data_by_purldb_urls=package_data_by_purldb_urls,
)
total_matched_count += matched_count
total_sha1_count += sha1_count
logger(
f"{total_matched_count:,d} resources matched in PurlDB "
f"using {total_sha1_count:,d} SHA1s"
)
def match_purldb_directories(project, logger=None):
"""Match against PurlDB selecting codebase directories."""
# If we are able to get match results for a directory fingerprint, then that
# means every resource and directory under that directory is part of a
# Package. By starting from the root to/ directory, we are attempting to
# match as many files as we can before attempting to match further down. The
# more "higher-up" directories we can match to means that we reduce the
# number of queries made to purldb.
to_directories = (
project.codebaseresources.directories()
.to_codebase()
.no_status(status=flag.ABOUT_MAPPED)
.no_status(status=flag.MATCHED_TO_PURLDB_PACKAGE)
.order_by("path")
)
directory_count = to_directories.count()
if logger:
logger(
f"Matching {directory_count:,d} "
f"director{pluralize(directory_count, 'y,ies')} from to/ in PurlDB"
)
directory_iterator = to_directories.iterator(chunk_size=2000)
progress = LoopProgress(directory_count, logger)
for directory in progress.iter(directory_iterator):
directory.refresh_from_db()
if directory.status != flag.MATCHED_TO_PURLDB_DIRECTORY:
match_purldb_directory(project, directory)
matched_count = (
project.codebaseresources.directories()
.to_codebase()
.filter(status=flag.MATCHED_TO_PURLDB_DIRECTORY)
.count()
)
logger(
f"{matched_count:,d} director{pluralize(matched_count, 'y,ies')} "
f"matched in PurlDB"
)
def map_javascript(project, logger=None):
"""Map a packed or minified JavaScript, TypeScript, CSS and SCSS to its source."""
project_files = project.codebaseresources.files()
to_resources = project_files.to_codebase().no_status().exclude(name__startswith=".")
to_resources_dot_map = to_resources.filter(extension=".map")
to_resources_minified = to_resources.filter(extension__in=[".css", ".js"])
to_resources_dot_map_count = to_resources_dot_map.count()
if logger:
logger(
f"Mapping {to_resources_dot_map_count:,d} .map resources using javascript "
f"map against from/ codebase."
)
from_resources = project_files.from_codebase().exclude(path__contains="/test/")
from_resources_index = pathmap.build_index(
from_resources.values_list("id", "path"), with_subpaths=True
)
resource_iterator = to_resources_dot_map.iterator(chunk_size=2000)
progress = LoopProgress(to_resources_dot_map_count, logger)
for to_dot_map in progress.iter(resource_iterator):
_map_javascript_resource(
to_dot_map, to_resources_minified, from_resources_index, from_resources
)
def _map_javascript_resource(
to_map, to_resources_minified, from_resources_index, from_resources
):
matches = js.get_matches_by_sha1(to_map, from_resources)
# Use diff_ratio if no sha1 match is found.
if not matches:
matches = js.get_matches_by_ratio(to_map, from_resources_index, from_resources)
transpiled = [to_map]
if minified_resource := js.get_minified_resource(
map_resource=to_map,
minified_resources=to_resources_minified,
):
transpiled.append(minified_resource)
for resource in transpiled:
for match, extra_data in matches:
pipes.make_relation(
from_resource=match,
to_resource=resource,
map_type="js_compiled",
extra_data=extra_data,
)
resource.update(status=flag.MAPPED)
@dataclass
class AboutFileIndexes:
"""
About file indexes are used to create packages from
About files and map the resources described in them
to the respective packages created, using regex path
patterns and other About file data.
"""
# Mapping of About file paths and the regex pattern
# string for the files documented
regex_by_about_path: dict
# Mapping of About file paths and a list of path pattern
# strings, for the files to be ignored
ignore_regex_by_about_path: dict
# Resource objects for About files present in the codebase,
# by their path
about_resources_by_path: dict
# mapping of package data present in the About file, by path
about_pkgdata_by_path: dict
# List of mapped resources for each About file, by path
mapped_resources_by_aboutpath: dict
@classmethod
def create_indexes(cls, project, from_about_files, logger=None):
"""
Return an ABOUT file index, containing path pattern mappings,
package data, and resources, created from `from_about_files`,
the About file resources.
"""
about_pkgdata_by_path = {}
regex_by_about_path = {}
ignore_regex_by_about_path = {}
about_resources_by_path = {}
mapped_resources_by_aboutpath = {}
count_indexed_about_files = 0
for about_file_resource in from_about_files:
package_data = resolve.resolve_about_package(
input_location=str(about_file_resource.location_path)
)
error_message_details = {"package_data": package_data}
if not package_data:
project.add_error(
description="Cannot create package from ABOUT file",
model="map_about_files",
details=error_message_details,
object_instance=about_file_resource,
)
continue
about_pkgdata_by_path[about_file_resource.path] = package_data
files_pattern = package_data.get("filename")
if not files_pattern:
# Cannot map anything without the about_resource value.
project.add_error(
description="ABOUT file does not have about_resource",
model="map_about_files",
details=error_message_details,
object_instance=about_file_resource,
)
continue
else:
count_indexed_about_files += 1
regex = convert_glob_to_django_regex(files_pattern)
regex_by_about_path[about_file_resource.path] = regex
if extra_data := package_data.get("extra_data"):
ignore_regex = []
for pattern in extra_data.get("ignored_resources", []):
ignore_regex.append(convert_glob_to_django_regex(pattern))
if ignore_regex:
ignore_regex_by_about_path[about_file_resource.path] = ignore_regex
about_resources_by_path[about_file_resource.path] = about_file_resource
mapped_resources_by_aboutpath[about_file_resource.path] = []
if logger:
logger(
f"Created mapping index from {count_indexed_about_files:,d} .ABOUT "
f"files in the from/ codebase."
)
return cls(
about_pkgdata_by_path=about_pkgdata_by_path,
regex_by_about_path=regex_by_about_path,
ignore_regex_by_about_path=ignore_regex_by_about_path,
about_resources_by_path=about_resources_by_path,
mapped_resources_by_aboutpath=mapped_resources_by_aboutpath,
)
def get_matched_about_path(self, to_resource):
"""
Map `to_resource` using the about file index, and if
mapped, return the path string to the About file it
was mapped to, and if not mapped or ignored, return
None.
"""
resource_mapped = False
for about_path, regex_pattern in self.regex_by_about_path.items():
if regex_match(pattern=regex_pattern, string=to_resource.path):
resource_mapped = True
break
if not resource_mapped:
return
ignore_regex_patterns = self.ignore_regex_by_about_path.get(about_path, [])
ignore_resource = False
for ignore_regex_pattern in ignore_regex_patterns:
if regex_match(pattern=ignore_regex_pattern, string=to_resource.path):
ignore_resource = True
break
if ignore_resource:
return
return about_path
def map_deployed_to_devel_using_about(self, to_resources):
"""
Return mapped resources which are mapped using the
path patterns in About file indexes. Resources are
mapped for each About file in the index, and
their status is updated accordingly.
"""
mapped_to_resources = []
for to_resource in to_resources:
about_path = self.get_matched_about_path(to_resource)
if not about_path:
continue
mapped_resources_about = self.mapped_resources_by_aboutpath.get(about_path)
if mapped_resources_about:
mapped_resources_about.append(to_resource)
else:
self.mapped_resources_by_aboutpath[about_path] = [to_resource]
mapped_to_resources.append(to_resource)
to_resource.update(status=flag.ABOUT_MAPPED)
return mapped_to_resources
def get_about_file_companions(self, about_path):
"""
Given an ``about_path`` path string to an About file,
get CodebaseResource objects for the companion license
and notice files.
"""
about_file_resource = self.about_resources_by_path.get(about_path)
about_file_extra_data = self.about_pkgdata_by_path.get(about_path).get(
"extra_data"
)
about_file_companion_names = [
about_file_extra_data.get("license_file"),
about_file_extra_data.get("notice_file"),
]
about_file_companions = about_file_resource.siblings().filter(
name__in=about_file_companion_names
)
return about_file_companions
def create_about_packages_relations(self, project):
"""
Create packages using About file package data, if the About file
has mapped resources on the to/ codebase and creates the mappings
for the package created and mapped resources.
"""
about_purls = set()
mapped_about_resources = []
for about_path, mapped_resources in self.mapped_resources_by_aboutpath.items():
about_file_resource = self.about_resources_by_path[about_path]
package_data = self.about_pkgdata_by_path[about_path]
if not mapped_resources:
error_message_details = {
"resource_path": about_path,
"package_data": package_data,
}
project.add_warning(
description=(
"Resource paths listed at about_resource is not found"
" in the to/ codebase"
),
model="map_about_files",
details=error_message_details,
)
continue
# Create the Package using .ABOUT data and assign related codebase_resources
about_package = pipes.update_or_create_package(
project=project,
package_data=package_data,
codebase_resources=mapped_resources,
)
about_purls.add(about_package.purl)
mapped_about_resources.append(about_file_resource)