-
-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathviews.py
More file actions
2837 lines (2407 loc) · 92 KB
/
views.py
File metadata and controls
2837 lines (2407 loc) · 92 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 difflib
import io
import json
import operator
from collections import Counter
from contextlib import suppress
from django.apps import apps
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import SuspiciousFileOperation
from django.core.exceptions import ValidationError
from django.core.files.storage.filesystem import FileSystemStorage
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Prefetch
from django.db.models.manager import Manager
from django.http import FileResponse
from django.http import Http404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.http import QueryDict
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.shortcuts import render
from django.template.defaultfilters import filesizeformat
from django.urls import reverse
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.text import capfirst
from django.views import generic
from django.views.decorators.http import require_POST
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.edit import FormView
from django.views.generic.edit import UpdateView
import saneyaml
import xlsxwriter
from django_filters.views import FilterView
from django_htmx.http import HttpResponseClientRedirect
from licensedcode.spans import Span
from packageurl.contrib.django.models import PACKAGE_URL_FIELDS
from scancodeio.auth import ConditionalLoginRequired
from scancodeio.auth import conditional_login_required
from scanpipe.api.serializers import DiscoveredDependencySerializer
from scanpipe.filters import PAGE_VAR
from scanpipe.filters import DependencyFilterSet
from scanpipe.filters import LicenseFilterSet
from scanpipe.filters import PackageFilterSet
from scanpipe.filters import ProjectFilterSet
from scanpipe.filters import ProjectMessageFilterSet
from scanpipe.filters import RelationFilterSet
from scanpipe.filters import ResourceFilterSet
from scanpipe.forms import AddInputsForm
from scanpipe.forms import AddLabelsForm
from scanpipe.forms import AddPipelineForm
from scanpipe.forms import BaseProjectActionForm
from scanpipe.forms import EditInputSourceTagForm
from scanpipe.forms import PipelineRunStepSelectionForm
from scanpipe.forms import ProjectArchiveForm
from scanpipe.forms import ProjectCloneForm
from scanpipe.forms import ProjectForm
from scanpipe.forms import ProjectOutputDownloadForm
from scanpipe.forms import ProjectReportForm
from scanpipe.forms import ProjectResetForm
from scanpipe.forms import ProjectSettingsForm
from scanpipe.forms import WebhookSubscriptionForm
from scanpipe.models import CodebaseRelation
from scanpipe.models import CodebaseResource
from scanpipe.models import DiscoveredDependency
from scanpipe.models import DiscoveredLicense
from scanpipe.models import DiscoveredPackage
from scanpipe.models import Project
from scanpipe.models import ProjectMessage
from scanpipe.models import Run
from scanpipe.models import RunInProgressError
from scanpipe.pipes import compliance
from scanpipe.pipes import count_group_by
from scanpipe.pipes import filename_now
from scanpipe.pipes import output
from scanpipe.pipes import purldb
scanpipe_app = apps.get_app_config("scanpipe")
# Cancel the default ordering for better performances
unordered_resources = CodebaseResource.objects.order_by()
LICENSE_CLARITY_FIELDS = [
(
"Declared license",
"declared_license",
"Indicates that the software package licensing is documented at top-level or "
"well-known locations in the software project, typically in a package "
"manifest, NOTICE, LICENSE, COPYING or README file. "
"Scoring Weight = 40.",
"+40",
),
(
"Identification precision",
"identification_precision",
"Indicates how well the license statement(s) of the software identify known "
"licenses that can be designated by precise keys (identifiers) as provided in "
"a publicly available license list, such as the ScanCode LicenseDB, the SPDX "
"license list, the OSI license list, or a URL pointing to a specific license "
"text in a project or organization website. "
"Scoring Weight = 40.",
"+40",
),
(
"License text",
"has_license_text",
"Indicates that license texts are provided to support the declared license "
"expression in files such as a package manifest, NOTICE, LICENSE, COPYING or "
"README. "
"Scoring Weight = 10.",
"+10",
),
(
"Declared copyrights",
"declared_copyrights",
"Indicates that the software package copyright is documented at top-level or "
"well-known locations in the software project, typically in a package "
"manifest, NOTICE, LICENSE, COPYING or README file. "
"Scoring Weight = 10.",
"+10",
),
(
"Ambiguous compound licensing",
"ambiguous_compound_licensing",
"Indicates that the software has a license declaration that makes it "
"difficult to construct a reliable license expression, such as in the case "
"of multiple licenses where the conjunctive versus disjunctive relationship "
"is not well defined. "
"Scoring Weight = -10.",
"-10",
),
(
"Conflicting license categories",
"conflicting_license_categories",
"Indicates the declared license expression of the software is in the "
"permissive category, but that other potentially conflicting categories, "
"such as copyleft and proprietary, have been detected in lower level code. "
"Scoring Weight = -20.",
"-20",
),
(
"Score",
"score",
"The license clarity score is a value from 0-100 calculated by combining the "
"weighted values determined for each of the scoring elements: Declared license,"
" Identification precision, License text, Declared copyrights, Ambiguous "
"compound licensing, and Conflicting license categories.",
None,
),
]
SCAN_SUMMARY_FIELDS = [
"declared_license_expression",
"declared_holder",
"primary_language",
"other_license_expressions",
"other_holders",
"other_languages",
]
def purldb_is_configured(*args):
return purldb.is_configured()
class PrefetchRelatedViewMixin:
prefetch_related = []
def get_queryset(self):
return super().get_queryset().prefetch_related(*self.prefetch_related)
def render_as_yaml(value):
if value:
return saneyaml.dump(value, indent=2)
def render_size(size_in_bytes):
if size_in_bytes:
return f"{size_in_bytes} ({filesizeformat(size_in_bytes)})"
def fields_have_no_values(fields_data):
return not any([field_data.get("value") for field_data in fields_data.values()])
def do_not_disable(*args, **kwargs):
return False
DISPLAYABLE_IMAGE_MIME_TYPE = [
"image/apng",
"image/avif",
"image/bmp",
"image/gif",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/webp",
"image/x-icon",
]
def is_displayable_image_type(resource):
"""Return True if the ``resource`` file is supported by the HTML <img> tag."""
return resource.mime_type and resource.mime_type in DISPLAYABLE_IMAGE_MIME_TYPE
class TabSetMixin:
"""
tabset = {
"<tab_id>": {
"fields": [
"<field_name>",
"<field_name>",
{
"field_name": "<field_name>",
"label": None,
"template": None,
"render_func": None,
},
],
"verbose_name": "",
"template": "",
"icon_class": "",
"display_condition": <func>,
"disable_condition": <func>,
}
}
"""
tabset = {}
def get_tabset_data(self):
"""Return the tabset data structure used in template rendering."""
tabset_data = {}
for tab_id, tab_definition in self.tabset.items():
if tab_data := self.get_tab_data(tab_definition):
tabset_data[tab_id] = tab_data
return tabset_data
def get_tab_data(self, tab_definition):
"""Return the data for a single tab based on the ``tab_definition``."""
if display_condition := tab_definition.get("display_condition"):
if not display_condition(self.object):
return
fields_data = self.get_fields_data(fields=tab_definition.get("fields", []))
is_disabled = False
if disable_condition := tab_definition.get("disable_condition"):
is_disabled = disable_condition(self.object, fields_data)
# This can be bypassed by providing ``do_not_disable`` to ``disable_condition``
elif fields_have_no_values(fields_data):
is_disabled = True
tab_data = {
"verbose_name": tab_definition.get("verbose_name"),
"icon_class": tab_definition.get("icon_class"),
"template": tab_definition.get("template"),
"fields": fields_data,
"disabled": is_disabled,
"label_count": self.get_label_count(fields_data),
}
return tab_data
def get_fields_data(self, fields):
"""Return the tab fields including their values for display."""
fields_data = {}
for field_definition in fields:
# Support for single "field_name" entry in fields list.
if not isinstance(field_definition, dict):
field_name = field_definition
field_data = {"field_name": field_name}
else:
field_name = field_definition.get("field_name")
field_data = field_definition.copy()
if "label" not in field_data:
field_data["label"] = self.get_field_label(field_name)
render_func = field_data.get("render_func")
field_data["value"] = self.get_field_value(field_name, render_func)
fields_data[field_name] = field_data
return fields_data
def get_field_value(self, field_name, render_func=None):
"""
Return the formatted value of the specified `field_name` from the object.
By default, JSON types (list and dict) are rendered as YAML,
except some fields which are used for a more complex tabular
representation with links to other views.
If a `render_func` is provided, it will take precedence and be used for
rendering the value.
"""
field_value = getattr(self.object, field_name, None)
if field_value and render_func:
return render_func(field_value)
if isinstance(field_value, Manager):
return list(field_value.all())
# We need these as mappings
detection_fields = [
"license_detections",
"other_license_detections",
"license_clues",
"matches",
"file_regions",
"urls",
"emails",
"datafile_paths",
"datasource_ids",
"detection_log",
"review_comments",
]
if isinstance(field_value, list | dict):
if field_name not in detection_fields:
with suppress(Exception):
field_value = render_as_yaml(field_value)
return field_value
@staticmethod
def get_field_label(field_name):
"""Return a formatted label for display based on the `field_name`."""
return field_name.replace("_", " ").capitalize().replace("url", "URL")
@staticmethod
def get_label_count(fields_data):
"""
Return the count of objects to be displayed in the tab label.
This only support tabs with a single field that has a single `list` for value.
"""
if len(fields_data.keys()) == 1:
value = list(fields_data.values())[0].get("value")
if isinstance(value, list):
return len(value)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["tabset_data"] = self.get_tabset_data()
return context
class TableColumnsMixin:
"""
table_columns = [
"<field_name>",
"<field_name>",
{
"field_name": "<field_name>",
"label": None,
"condition": None,
"sort_name": None,
"css_class": None,
},
]
"""
table_columns = []
def get_columns_data(self):
"""Return the columns data structure used in template rendering."""
columns_data = []
sortable_fields = []
active_sort = ""
filterset = getattr(self, "filterset", None)
if filterset and "sort" in filterset.filters:
sortable_fields = list(filterset.filters["sort"].param_map.keys())
active_sort = filterset.data.get("sort", "")
for column_definition in self.table_columns:
# Support for single "field_name" entry in columns list.
if not isinstance(column_definition, dict):
field_name = column_definition
column_data = {"field_name": field_name}
else:
field_name = column_definition.get("field_name")
column_data = column_definition.copy()
condition = column_data.get("condition", None)
if condition is not None and not bool(condition):
continue
if "label" not in column_data:
column_data["label"] = self.get_field_label(field_name)
sort_name = column_data.get("sort_name") or field_name
if sort_name in sortable_fields:
is_sorted = sort_name == active_sort.lstrip("-")
sort_direction = ""
if is_sorted and not active_sort.startswith("-"):
sort_direction = "-"
column_data["is_sorted"] = is_sorted
column_data["sort_direction"] = sort_direction
query_dict = self.request.GET.copy()
query_dict["sort"] = f"{sort_direction}{sort_name}"
column_data["sort_query"] = query_dict.urlencode()
if filter_fieldname := column_data.get("filter_fieldname"):
column_data["filter"] = filterset.form[filter_fieldname]
columns_data.append(column_data)
return columns_data
@staticmethod
def get_field_label(field_name):
"""Return a formatted label for display based on the `field_name`."""
return field_name.replace("_", " ").capitalize().replace("url", "URL")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["columns_data"] = self.get_columns_data()
context["request_query_string"] = self.request.GET.urlencode()
return context
class ExportXLSXMixin:
"""
Add the ability to export the current filtered QuerySet of a `FilterView` into
the XLSX format.
"""
export_xlsx_query_param = "export_xlsx"
def get_export_xlsx_queryset(self):
return self.filterset.qs
def get_export_xlsx_filename(self):
return f"{self.project.name}_{self.model._meta.model_name}.xlsx"
def export_xlsx_file_response(self):
output_file = io.BytesIO()
queryset = self.get_export_xlsx_queryset()
with xlsxwriter.Workbook(output_file) as workbook:
output.queryset_to_xlsx_worksheet(
queryset,
workbook,
exclude_fields=output.XLSX_EXCLUDE_FIELDS,
)
output_file.seek(0)
return FileResponse(
output_file,
as_attachment=True,
filename=self.get_export_xlsx_filename(),
)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
query_dict = self.request.GET.copy()
query_dict[self.export_xlsx_query_param] = True
context["export_xlsx_url_query"] = query_dict.urlencode()
return context
def get(self, request, *args, **kwargs):
response = super().get(request, *args, **kwargs)
if request.GET.get(self.export_xlsx_query_param):
return self.export_xlsx_file_response()
return response
class ExportJSONMixin:
"""
Add the ability to export the current filtered QuerySet of a `FilterView`
into JSON format.
"""
export_json_query_param = "export_json"
def get_export_json_queryset(self):
return self.filterset.qs
def get_export_json_filename(self):
return f"{self.project.name}_{self.model._meta.model_name}.json"
def export_json_file_response(self):
from scanpipe.api.serializers import get_model_serializer
queryset = self.get_export_json_queryset()
serializer_class = get_model_serializer(queryset.model)
serializer = serializer_class(queryset, many=True)
serialized_data = json.dumps(serializer.data, indent=2, cls=DjangoJSONEncoder)
output_file = io.BytesIO(serialized_data.encode("utf-8"))
return FileResponse(
output_file,
as_attachment=True,
filename=self.get_export_json_filename(),
content_type="application/json",
)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
query_dict = self.request.GET.copy()
query_dict[self.export_json_query_param] = True
context["export_json_url_query"] = query_dict.urlencode()
return context
def get(self, request, *args, **kwargs):
response = super().get(request, *args, **kwargs)
if request.GET.get(self.export_json_query_param):
return self.export_json_file_response()
return response
class HTMXFormMixin:
def form_valid(self, form):
response = super().form_valid(form)
if self.request.htmx:
return HttpResponseClientRedirect(self.get_success_url())
return response
def form_invalid(self, form):
response = super().form_invalid(form)
if self.request.htmx:
# Re-render the form with errors
return self.render_to_response(self.get_context_data(form=form))
return response
def get_success_url(self):
return self.object.get_absolute_url()
class PaginatedFilterView(FilterView):
"""
Add a `url_params_without_page` value in the template context to include the
current filtering in the pagination.
"""
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
query_dict = self.request.GET.copy()
query_dict.pop(PAGE_VAR, None)
context["url_params_without_page"] = query_dict.urlencode()
context["searchable_fields"] = sorted(
field.name
for field in self.model._meta.get_fields()
if not field.is_relation
)
return context
class AccountProfileView(LoginRequiredMixin, generic.TemplateView):
template_name = "account/profile.html"
class ProjectListView(
ConditionalLoginRequired,
PrefetchRelatedViewMixin,
TableColumnsMixin,
PaginatedFilterView,
):
model = Project
filterset_class = ProjectFilterSet
paginate_by = settings.SCANCODEIO_PAGINATE_BY.get("project", 20)
template_name = "scanpipe/project_list.html"
prefetch_related = [
"labels",
Prefetch(
"runs",
queryset=Run.objects.only(
"uuid",
"pipeline_name",
"project_id",
"task_id",
"task_start_date",
"task_end_date",
"task_exitcode",
),
),
]
table_columns = [
"name",
{
"field_name": "discoveredpackages",
"label": "Packages",
"sort_name": "discoveredpackages_count",
},
{
"field_name": "discovereddependencies",
"label": "Dependencies",
"sort_name": "discovereddependencies_count",
},
{
"field_name": "codebaseresources",
"label": "Resources",
"sort_name": "codebaseresources_count",
},
{
"field_name": "projectmessages",
"label": "Messages",
"sort_name": "projectmessages_count",
},
{
"field_name": "runs",
"label": "Pipelines",
},
{
"label": "",
"css_class": "is-narrow",
},
]
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["action_form"] = BaseProjectActionForm()
context["archive_form"] = ProjectArchiveForm()
context["reset_form"] = ProjectResetForm()
context["outputs_download_form"] = ProjectOutputDownloadForm()
context["report_form"] = ProjectReportForm()
return context
def get_queryset(self):
return (
super()
.get_queryset()
.only(
"uuid",
"name",
"slug",
"created_date",
)
.with_counts(
"codebaseresources",
"discoveredpackages",
"discovereddependencies",
"projectmessages",
)
.order_by("-created_date")
)
class ProjectCreateView(ConditionalLoginRequired, generic.CreateView):
model = Project
form_class = ProjectForm
template_name = "scanpipe/project_form.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
pipelines = {
key: pipeline_class.get_info()
for key, pipeline_class in scanpipe_app.pipelines.items()
if not pipeline_class.is_addon
}
pipelines_available_groups = {
name: info["available_groups"] for name, info in pipelines.items()
}
context["pipelines"] = pipelines
context["pipelines_available_groups"] = pipelines_available_groups
return context
@property
def is_xhr(self):
# The request is XMLHttpRequest when using the input upload progress
return self.request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest"
def form_valid(self, form):
response = super().form_valid(form)
if self.is_xhr:
return JsonResponse({"redirect_url": self.get_success_url()}, status=201)
return response
def form_invalid(self, form):
response = super().form_invalid(form)
if self.is_xhr:
return JsonResponse({"errors": str(form.errors)}, status=400)
return response
class ProjectDetailView(ConditionalLoginRequired, generic.DetailView):
model = Project
template_name = "scanpipe/project_detail.html"
def get_queryset(self):
return super().get_queryset().prefetch_related("runs")
@staticmethod
def get_license_clarity_data(scan_summary_json):
license_clarity_score = scan_summary_json.get("license_clarity_score", {})
return [
{
"label": label,
"value": license_clarity_score.get(field),
"help_text": help_text,
"weight": weight,
}
for label, field, help_text, weight in LICENSE_CLARITY_FIELDS
]
@staticmethod
def get_scan_summary_data(project, scan_summary_json):
summary_data = {}
for field_name, field_data in scan_summary_json.items():
if field_name not in SCAN_SUMMARY_FIELDS:
continue
if type(field_data) is list:
# Do not include `None` entries
values = [entry for entry in field_data if entry.get("value")]
else:
# Converts single value type into common data-structure
values = [{"value": field_data}]
summary_data[field_name] = values
key_files = project.codebaseresources.filter(is_key_file=True)
summary_data["key_file_licenses"] = {
key_file.path: key_file.detected_license_expression
for key_file in key_files
}
return summary_data
def check_run_scancode_version(self, pipeline_runs, version_limit="32.2.0"):
"""
Display a warning message if one of the ``pipeline_runs`` scancodeio_version
is prior to or currently is ``old_version``.
"""
run_versions = [
run.scancodeio_version for run in pipeline_runs if run.scancodeio_version
]
if run_versions and min(run_versions) <= version_limit:
message = (
"WARNING: Some this project pipelines have been run with an "
"out of date ScanCode-toolkit version.\n"
"The scan data was migrated, but it is recommended to reset the "
"project and re-run the pipelines to benefit from the latest "
"scan results improvements."
)
messages.warning(self.request, message)
def check_for_missing_inputs(self, project):
uploaded_input_sources = project.inputsources.filter(is_uploaded=True)
missing_inputs = [
input_source
for input_source in uploaded_input_sources
if not input_source.exists()
]
if missing_inputs:
filenames = [input_source.filename for input_source in missing_inputs]
missing_files = "\n- ".join(filenames)
message = (
f"The following input files are not available on disk anymore:\n"
f"- {missing_files}"
)
messages.error(self.request, message)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = self.object
project_resources_url = reverse("project_resources", args=[project.slug])
self.check_for_missing_inputs(project)
if project.is_archived:
message = "WARNING: This project is archived and read-only."
messages.warning(self.request, message)
license_clarity = []
scan_summary = {}
scan_summary_file = project.get_latest_output(filename="summary")
if scan_summary_file:
with suppress(json.decoder.JSONDecodeError):
scan_summary_json = json.loads(scan_summary_file.read_text())
license_clarity = self.get_license_clarity_data(scan_summary_json)
scan_summary = self.get_scan_summary_data(project, scan_summary_json)
codebase_root = sorted(
project.codebase_path.glob("*"),
key=operator.attrgetter("name"),
)
codebase_root.sort(key=operator.methodcaller("is_file"))
pipeline_runs = project.runs.all()
self.check_run_scancode_version(pipeline_runs)
license_policies_enabled = False
try:
license_policies_enabled = project.license_policies_enabled
except ValidationError as e:
messages.error(self.request, str(e))
context.update(
{
"input_sources": project.get_inputs_with_source(),
"labels": list(project.labels.all()),
"add_pipeline_form": AddPipelineForm(),
"pipeline_choices": self.get_pipeline_choices(pipeline_runs),
"add_inputs_form": AddInputsForm(),
"add_labels_form": AddLabelsForm(),
"edit_input_tag_from": EditInputSourceTagForm(),
"project_clone_form": ProjectCloneForm(project),
"project_resources_url": project_resources_url,
"license_clarity": license_clarity,
"scan_summary": scan_summary,
"pipeline_runs": pipeline_runs,
"codebase_root": codebase_root,
"file_filter": self.request.GET.get("file-filter", "all"),
"license_policies_enabled": license_policies_enabled,
}
)
if project.extra_data:
context["extra_data_yaml"] = render_as_yaml(project.extra_data)
return context
def post(self, request, *args, **kwargs):
project = self.get_object()
if "add-inputs-submit" in request.POST:
form_class = AddInputsForm
success_message = "Input file(s) added."
error_message = "Input file addition error."
elif "add-pipeline-submit" in request.POST:
form_class = AddPipelineForm
success_message = "Pipeline added."
error_message = "Pipeline addition error."
elif "add-labels-submit" in request.POST:
form_class = AddLabelsForm
success_message = "Label(s) added."
error_message = "Label addition error."
elif "edit-input-tag-submit" in request.POST:
form_class = EditInputSourceTagForm
success_message = "Tag updated."
error_message = "Tag update error."
else:
raise Http404
form_kwargs = {"data": request.POST, "files": request.FILES}
form = form_class(**form_kwargs)
if form.is_valid() and form.save(project):
messages.success(request, success_message)
else:
messages.error(request, error_message)
return redirect(project)
@staticmethod
def get_pipeline_choices(pipeline_runs):
"""
Determine pipeline choices based on the project context:
1. If no pipelines are assigned to the project:
Include all base (non-addon) pipelines.
2. If at least one pipeline already exists on the project:
Include all addon pipelines and the existing pipeline (useful for
potential re-runs in debug mode).
"""
project_run_names = {run.pipeline_name for run in pipeline_runs or []}
pipeline_choices = [
(name, pipeline_class.get_info())
for name, pipeline_class in scanpipe_app.pipelines.items()
# no pipelines are assigned to the project
if (not pipeline_runs and not pipeline_class.is_addon)
# at least one pipeline already exists on the project
or pipeline_runs
and (name in project_run_names or pipeline_class.is_addon)
]
return pipeline_choices
class ProjectSettingsView(ConditionalLoginRequired, UpdateView):
model = Project
template_name = "scanpipe/project_settings.html"
form_class = ProjectSettingsForm
success_message = 'The project "{}" settings have been updated.'
def get_queryset(self):
return super().get_queryset().prefetch_related("webhooksubscriptions")
def form_valid(self, form):
response = super().form_valid(form)
project = self.get_object()
messages.success(self.request, self.success_message.format(project))
return response
def get(self, request, *args, **kwargs):
if request.GET.get("download"):
return self.download_config_file(project=self.get_object())
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = self.get_object()
context["archive_form"] = ProjectArchiveForm()
context["reset_form"] = ProjectResetForm()
context["webhook_form"] = WebhookSubscriptionForm()
context["webhook_subscriptions"] = project.webhooksubscriptions.all()
return context
@staticmethod
def download_config_file(project):
"""
Download the ``scancode-config.yml`` config file generated from the current
project settings.
"""
response = FileResponse(
streaming_content=project.get_settings_as_yml(),
content_type="application/x-yaml",
)
filename = output.safe_filename(settings.SCANCODEIO_CONFIG_FILE)
response["Content-Disposition"] = f'attachment; filename="{filename}"'
return response
class ProjectSettingsWebhookCreateView(
ConditionalLoginRequired, HTMXFormMixin, UpdateView
):
model = Project
form_class = WebhookSubscriptionForm
template_name = "scanpipe/forms/project_webhook_form.html"
def get_success_url(self):
url = reverse("project_settings", args=[self.object.slug])
return url + "#webhooks"
def form_valid(self, form):
form.save(project=self.object)
messages.success(self.request, "Webhook added to the project.")
return HttpResponseClientRedirect(self.get_success_url())
class ProjectChartsView(ConditionalLoginRequired, generic.DetailView):
model = Project
template_name = "scanpipe/project_charts.html"
@staticmethod
def get_summary(values_list, limit=settings.SCANCODEIO_MOST_COMMON_LIMIT):
counter = Counter(values_list)
has_only_empty_string = list(counter.keys()) == [""]