-
-
Notifications
You must be signed in to change notification settings - Fork 576
/
Copy pathdebian_copyright.py
1949 lines (1595 loc) · 67.3 KB
/
debian_copyright.py
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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import fnmatch
import os
import sys
import logging
from collections import defaultdict
from itertools import chain
from pathlib import Path
import attr
from debian_inspector.copyright import CatchAllParagraph
from debian_inspector.copyright import CopyrightFilesParagraph
from debian_inspector.copyright import CopyrightLicenseParagraph
from debian_inspector.copyright import CopyrightHeaderParagraph
from debian_inspector.copyright import DebianCopyright
from debian_inspector.package import CodeMetadata
from debian_inspector.version import Version as DebVersion
from license_expression import ExpressionError
from license_expression import LicenseSymbolLike
from license_expression import Licensing
from licensedcode.detection import get_undetected_matches
from packagedcode import models
from packagedcode.licensing import get_declared_license_expression_spdx
from packagedcode.licensing import get_license_expression_from_matches
from packagedcode.licensing import get_license_detections_from_matches
from packagedcode.licensing import get_license_matches
from packagedcode.licensing import get_license_matches_from_query_string
from packagedcode.licensing import get_mapping_and_expression_from_detections
from licensedcode.detection import LicenseDetection
from packagedcode.utils import combine_expressions
from textcode.analysis import unicode_text
"""
Detect licenses and copyright in Debian copyright files. Can handle dep-5
machine-readable copyright files, pre-dep-5 mostly machine-readable copyright
files and unstructured non-dep5 copyright files.
The machine-readable files are often messy and not always correctly structured.
License texts can be scattered in various paragraphs in license, comments or
extra data.
The license symbols used in these files are local to a single file and therefore
require full detection to assign some meaning to them
See https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
"""
TRACE = os.environ.get('SCANCODE_DEBUG_PACKAGE', False)
def logger_debug(*args):
pass
logger = logging.getLogger(__name__)
if TRACE:
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
def logger_debug(*args):
return logger.debug(
' '.join(isinstance(a, str) and a or repr(a) for a in args)
)
MATCHER_UNKNOWN = '5-unknown'
class BaseDebianCopyrightFileHandler(models.DatafileHandler):
default_package_type = 'deb'
documentation_url = 'https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/'
@classmethod
def is_datafile(cls, location, filetypes=tuple(), strict=False):
isdc = (
super().is_datafile(location, filetypes=filetypes)
# we want the filename to be lowercase
and location.endswith('copyright')
)
if isdc:
if strict:
text = unicode_text(location)
return EnhancedDebianCopyright.is_machine_readable_copyright(text)
else:
return True
@classmethod
def parse(cls, location, package_only=False):
debian_copyright = parse_copyright_file(location)
license_fields = DebianLicenseFields.get_license_fields(
debian_copyright=debian_copyright
)
# TODO: collect the upstream source package details
# find a name... TODO: this should be pushed down to each handler
if fnmatch.fnmatch(name=location, pat='*usr/share/doc/*/copyright'):
path = Path(location)
name = path.parent.name
else:
# no name otherwise for now
name = None
package_data = dict(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
name=name,
)
if not package_only:
license_data = dict(
extracted_license_statement=license_fields.extracted_license_statement,
declared_license_expression=license_fields.declared_license_expression,
declared_license_expression_spdx=license_fields.declared_license_expression_spdx,
license_detections=license_fields.license_detections,
other_license_expression=license_fields.other_license_expression,
other_license_expression_spdx=license_fields.other_license_expression_spdx,
other_license_detections=license_fields.other_license_detections,
copyright=debian_copyright.get_copyright(),
)
package_data.update(license_data)
yield models.PackageData.from_data(package_data, package_only)
@attr.s
class DebianLicenseFields:
extracted_license_statement = attr.ib(default=None)
declared_license_expression = attr.ib(default=None)
declared_license_expression_spdx = attr.ib(default=None)
license_detections = attr.ib(default=attr.Factory(list))
other_license_expression = attr.ib(default=None)
other_license_expression_spdx = attr.ib(default=None)
other_license_detections = attr.ib(default=None)
license_detections = attr.ib(default=attr.Factory(list))
license_expression_keys = attr.ib(default=attr.Factory(list))
@classmethod
def get_license_fields(
cls,
debian_copyright,
simplify_licenses=True,
filter_duplicates=False,
skip_debian_packaging=False,
_licensing=Licensing(),
):
extracted_license_statement = debian_copyright.get_declared_license(
filter_duplicates=filter_duplicates,
skip_debian_packaging=skip_debian_packaging,
)
license_expression = debian_copyright.get_license_expression(
skip_debian_packaging=skip_debian_packaging,
simplify_licenses=simplify_licenses,
)
license_expression_spdx = get_declared_license_expression_spdx(
declared_license_expression=license_expression
)
detections = debian_copyright.get_license_detections_mapping()
if debian_copyright.is_structured and debian_copyright.primary_license:
# Structured debian copyright files mostly have well defined
# primary licenses and other licenses, so we return these as
# the `declared_license_expression` and all other licenses
# as `other_license_expression`.
declared_license_expression = debian_copyright.primary_license
declared_license_expression_spdx = get_declared_license_expression_spdx(
declared_license_expression=declared_license_expression
)
license_detections = debian_copyright.primary_license_detections
other_license_expression = license_expression
other_license_expression_spdx = license_expression_spdx
other_license_detections = detections
combined_license_expression = combine_expressions(
expressions=[
declared_license_expression,
other_license_expression
],
relation='AND',
unique=False,
)
license_expression_keys = list(set(
_licensing.license_keys(combined_license_expression)
))
else:
# We cannot get primary license from Unstructured debian copyright files
# or Structured files without a header/primary-license paragraph,
# so here all the license expressions are `declared_license_expression`
# and `other_license_expression` is None.
declared_license_expression = license_expression
declared_license_expression_spdx = license_expression_spdx
license_detections = detections
other_license_expression = None
other_license_expression_spdx = None
other_license_detections = []
license_expression_keys = list(set(
_licensing.license_keys(declared_license_expression)
))
return cls(
extracted_license_statement=extracted_license_statement,
declared_license_expression=declared_license_expression,
declared_license_expression_spdx=declared_license_expression_spdx,
license_detections=license_detections,
other_license_expression=other_license_expression,
other_license_expression_spdx=other_license_expression_spdx,
other_license_detections=other_license_detections,
license_expression_keys=license_expression_keys,
)
class DebianCopyrightFileInSourceHandler(BaseDebianCopyrightFileHandler):
datasource_id = 'debian_copyright_in_source'
description = 'Debian machine readable file in source'
path_patterns = (
# Seen in a source repo or in *.debian.tar.xz tarball
# See https://github.com/Debian/dcs/blob/c88c75b9fb776b9d3075698716af8c0fd8d7558f/debian/copyright ]
# See http://deb.debian.org/debian/pool/main/p/python-docutils/python-docutils_0.16+dfsg-4.debian.tar.xz
'*/debian/copyright',
)
@classmethod
def assign_package_to_resources(cls, package, resource, codebase, package_adder):
# two levels up
root = resource.parent(codebase).parent(codebase)
if root:
return cls.assign_package_to_resources(package, root, codebase, package_adder)
# TODO: distiguish the cased of an installed package vs. the case of an extracted .deb
class DebianCopyrightFileInPackageHandler(BaseDebianCopyrightFileHandler):
datasource_id = 'debian_copyright_in_package'
description = 'Debian machine readable file in source'
path_patterns = (
# Standard form when seen in an installed form in /usr/share/doc/
# and in the same place in the data.tar.xz inner archive of a .deb archive
# See http://ftp.us.debian.org/debian/pool/main/p/python-docutils/python3-docutils_0.16+dfsg-4_all.deb
'*usr/share/doc/*/copyright',
)
@classmethod
def assemble(cls, package_data, resource, codebase, package_adder):
# DO NOTHING: let other handler reuse this
return []
class StandaloneDebianCopyrightFileHandler(BaseDebianCopyrightFileHandler):
datasource_id = 'debian_copyright_standalone'
description = 'Debian machine readable file standalone'
path_patterns = (
# other places... may be we should treat this strictly wrt. being a structure file only?
'*/copyright',
# Seen in http://metadata.ftp-master.debian.org/changelogs/main/d/dtrx/dtrx_8.2.2-1_copyright
'*_copyright',
)
@classmethod
def is_datafile(cls, location, filetypes=tuple()):
return (
super().is_datafile(location, filetypes=filetypes)
and not DebianCopyrightFileInPackageHandler.is_datafile(location)
and not DebianCopyrightFileInSourceHandler.is_datafile(location)
)
@classmethod
def assemble(cls, package_data, resource, codebase, package_adder):
# assemble is the default
yield from super().assemble(package_data, resource, codebase, package_adder)
@classmethod
def parse(cls, location, package_only=False):
"""
Gets license/copyright information from file like
other copyright files, but also gets purl fields if
present in copyright filename, if obtained from
upstream metadata archive.
"""
package_data = list(super().parse(location, package_only)).pop()
package_data_from_file = build_package_data_from_metadata_filename(
filename=os.path.basename(location),
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
if package_data_from_file:
package_data.update_purl_fields(package_data=package_data_from_file)
yield package_data
def build_package_data_from_metadata_filename(filename, datasource_id, package_type):
"""
Return a PackageData built from the filename of a Debian package metadata.
"""
# TODO: we cannot know the distro from the name only
# PURLs without namespace is invalid, so we need to
# have a default value for this
distro = 'debian'
try:
deb = CodeMetadata.from_filename(filename=filename)
except ValueError:
return
version = deb.version
if isinstance(version, DebVersion):
version = str(version)
return models.PackageData(
datasource_id=datasource_id,
type=package_type,
name=deb.name,
namespace=distro,
version=version,
)
class NotReallyStructuredCopyrightFile(Exception):
"""
Raised when a file has a dep5, machine readable copyrigh file format
declared, but is not strictly structured.
"""
def parse_copyright_file(location, check_consistency=False):
"""
Return a DebianDetector Object containing copyright and license detections
extracted from the debian copyright file at ``location``.
If ``check_consistency`` is True, check if debian copyright file is
consistently structured according to the guidelines specified at
https://www.debian.org/doc/packaging-manuals/copyright-format/1.0
"""
if not location or not location.endswith('copyright'):
return
# FIXME: we should not read the whole files here and then discard it!
text = unicode_text(location)
if EnhancedDebianCopyright.is_machine_readable_copyright(text):
try:
dc = StructuredCopyrightProcessor.from_file(
location=location,
check_consistency=check_consistency,
)
except NotReallyStructuredCopyrightFile:
if TRACE:
logger_debug(
'StructuredCopyrightProcessor.from_file: '
'file is not really structured:',
location
)
dc = UnstructuredCopyrightProcessor.from_file(
location=location,
check_consistency=check_consistency,
)
else:
dc = UnstructuredCopyrightProcessor.from_file(
location=location,
check_consistency=check_consistency,
)
if check_consistency and dc.consistency_errors:
msg = (
f'Debian Copyright file in not consistent, because of the following:'
f' {dc.consistency_errors}'
)
raise DebianCopyrightStructureError(msg)
if TRACE:
logger_debug(f'parse_copyright_file: {type(dc)}')
if isinstance(dc, StructuredCopyrightProcessor):
for det in dc.license_detections:
print()
print(type(det.paragraph))
for f in det.paragraph.get_field_names():
print(f' {f}: {getattr(det.paragraph, f)}')
print()
for m in det.license_matches:
print(m)
print()
return dc
@attr.s
class DebianDetector:
"""
Base class for `UnstructuredCopyrightProcessor` and
`StructuredCopyrightProcessor` classes, defining the common functions and
attributes.
An instance can scan ONLY one copyright file; it cannot be reused.
"""
# Absolute location of this copyright file
location = attr.ib()
# List of consistency error messages if the debian copyright file is not
# consistent. This is populated if the `check_consistency` flag in
# `parse_copyright_file` is set to True.
consistency_errors = attr.ib(default=attr.Factory(list))
@classmethod
def from_file(cls, *args, **kwargs):
"""
Return a DebianDetector object with License and Copyright detections.
"""
raise NotImplementedError
def get_copyright(self, *args, **kwargs):
"""
Return a copyright string (found in Copyright: structured fields or in
plain text).
"""
raise NotImplementedError
def get_license_expression(self, *args, **kwargs):
"""
Return a license expression string suitable to use as a
PackageData.declared_license_expression.
"""
raise NotImplementedError
def get_declared_license(self, *args, **kwargs):
"""
Return a list of declared license string suitable to use as a
PackageData.declared_license.
"""
raise NotImplementedError
def get_license_detections_mapping(self):
"""
Return a list of packagedcode.detection LicenseDetection objects
to be reported at `PackageData.license_detections`.
"""
raise NotImplementedError
@attr.s
class UnstructuredCopyrightProcessor(DebianDetector):
# List of LicenseMatches in an unstructured file
license_matches = attr.ib(default=attr.Factory(list))
# List of detected copyrights in an unstructured file
detected_copyrights = attr.ib(default=attr.Factory(list))
@classmethod
def from_file(cls, location, check_consistency=False):
"""
Return a UnstructuredCopyrightProcessor object created from a
unstructured debian copyright file, after detecting license and
copyrights.
If `check_consistency` is True, will always add a consistency error as
unstructured copyright files are not consistent.
"""
dc = cls(location=location)
if check_consistency:
dc.consistency_errors.append('Debian Copyright File is unstructured')
dc.detected_copyrights = copyright_detector(location)
dc.detect_license(location=location)
return dc
@property
def primary_license(self):
"""
Return None as primary license cannot be detected in an unstructured
debian copyright file.
"""
return None
@property
def is_structured(self):
"""
Return False as this is not a Structured Debian copyright file.
"""
return False
def get_declared_license(self, *args, **kwargs):
"""
Return None as there is no declared licenses in an unstructured debian
copyright file.
"""
return None
def get_license_expression(
self,
simplify_licenses=False,
*args, **kwargs
):
"""
Return a license expression string for the corresponding debian
copyright file.
If simplify_licenses is True, uses Licensing.dedup() to simplify the
license expression.
"""
detected_expressions = [
match.rule.license_expression for match in self.license_matches
]
license_expression = combine_expressions(
expressions=detected_expressions,
relation='AND',
unique=False,
)
if simplify_licenses:
return dedup_expression(license_expression=license_expression)
else:
return license_expression
def get_copyright(self, *args, **kwargs):
"""
Return a copyright string with one copyright statement per line.
"""
return '\n'.join(self.detected_copyrights)
def detect_license(self, location):
"""
Return a list of LicenseMatch objects detected in the file at
``location``. Return a list with a single match to an UnknownRule if no
license is detected since we must detect some license in this text.
"""
# note that we are passing a file location so we have proper line numbers
license_matches = get_license_matches(location=location)
if TRACE:
logger_debug('UnstructuredCopyrightProcessor.detect_license: matches:', license_matches)
license_matches = remove_known_license_intros(
license_matches=license_matches
)
if TRACE:
logger_debug('UnstructuredCopyrightProcessor.detect_license: matches2:', license_matches)
if not license_matches:
text = unicode_text(location)
# We have no match: return unknown as there must be some license
# FIXME: we should track line numbers
license_matches = add_undetected_debian_matches(name=None, text=text)
self.license_matches = license_matches
return license_matches
def get_license_detections_mapping(self):
"""
Return a list of packagedcode.detection LicenseDetection objects
to be reported at `PackageData.license_detections`.
"""
if not self.license_matches:
return []
license_detections = get_license_detections_from_matches(
matches=self.license_matches
)
license_detections_mapping, _expression = get_mapping_and_expression_from_detections(
license_detections=license_detections,
whole_lines=False,
)
return license_detections_mapping
def is_really_structured(dc):
"""
Return False if a `dc` debian_inspector DebianCopyright is not really a
structured file based on its paragraph types makeup.
Return True otherwise.
"""
# With only CatchAllParagraph paras we are not structured
if all(type(p) == CatchAllParagraph for p in dc.paragraphs):
return False
# With over 4 catchall paras, we have too many catchalls.
# A catchall is a sign of recovery from parsing invalid constructions.
para_type_counts = defaultdict(int)
for p in dc.paragraphs:
para_type_counts[type(p)] = para_type_counts[type(p)] + 1
if para_type_counts.get(CatchAllParagraph, 0) > 4:
return False
return True
@attr.s
class StructuredCopyrightProcessor(DebianDetector):
# FIXME: we should also return the plain License paragraphs
# List of DebianLicenseDetection objects from detection in files and header
# paragraphs
license_detections = attr.ib(default=attr.Factory(list))
# List of CopyrightDetection from copyright statements found in files and
# header paragraphs
copyright_detections = attr.ib(default=attr.Factory(list))
# A DebianCopyright object built from the copyright file
debian_copyright = attr.ib(default=None)
# primary license as a license expression. This is the license present in
# header or 'files: *' paragraph for a structured debian copyright file
primary_license = attr.ib(default=None)
# list of LicenseDetection objects for the primary_licens
primary_license_detections = attr.ib(default=attr.Factory(list))
@property
def is_structured(self):
"""
Return True as this is a Structured Debian copyright file.
"""
return True
@classmethod
def from_file(cls, location, check_consistency=False):
"""
Return a DebianCopyrightFileProcessor object built from debian copyright
file at ``location``, or None if this is not a debian copyright file.
If `check_consistency` is True, check if debian copyright file is
consistently structured according to debian guidelines.
"""
if not location or not location.endswith('copyright'):
return
debian_copyright = DebianCopyright.from_file(location)
if not is_really_structured(debian_copyright):
# we bail out and this will be treated as unstructured
raise NotReallyStructuredCopyrightFile(location)
edc = EnhancedDebianCopyright(debian_copyright=debian_copyright)
dc = cls(location=location, debian_copyright=debian_copyright)
dc.detect_license()
dc.detect_copyrights()
dc.set_primary_license()
if check_consistency:
dc.consistentcy_errors = edc.get_consistentcy_errors()
return dc
@property
def license_matches(self):
"""
Get a list of all LicenseMatch objects which are detected in the
copyright file.
"""
matches = (
ld.license_matches
for ld in self.license_detections
if ld.license_matches
)
return chain.from_iterable(matches)
def set_primary_license(self):
"""
Compute and set the primary license expression of this debian copyright file to
`primary_license`. Also set the license detections for the primary license to
`primary_license_detections`.
A primary license in a debian copyright file is the license in the
Header paragraph or the `Files: *` paragraph.
"""
expressions = []
primary_debian_license_detections = []
has_header_license = False
has_primary_license = False
for ld in self.license_detections:
if ld.license_expression_object != None:
if not has_header_license and isinstance(
ld.paragraph, CopyrightHeaderParagraph
):
expressions.append(ld.license_expression_object)
has_header_license = True
primary_debian_license_detections.append(ld)
if not has_primary_license and is_paragraph_primary_license(
ld.paragraph
):
expressions.append(ld.license_expression_object)
has_primary_license = True
primary_debian_license_detections.append(ld)
if not expressions:
return
self.primary_license = dedup_expression(
license_expression=str(combine_expressions(expressions))
)
detection_objects = []
for debian_detection in primary_debian_license_detections:
license_matches = debian_detection.license_matches
if not license_matches:
continue
detection = LicenseDetection.from_matches(
license_matches
)
detection_objects.append(detection)
detections_mapping, _expression = get_mapping_and_expression_from_detections(
license_detections=detection_objects,
whole_lines=False,
)
self.primary_license_detections = detections_mapping
def get_declared_license(
self,
filter_duplicates=False,
skip_debian_packaging=False,
*args, **kwargs,
):
"""
Return a list of declared license strings (`License: <string>`) from the
all paragraphs.
If `filter_duplicates` is True, only unique declared licenses are
returned. If `skip_debian_packaging` is True, skips the declared license
for `Files: debian/*` paragraph.
"""
declarable_paragraphs = [
para
for para in self.debian_copyright.paragraphs
if hasattr(para, 'license') and para.license.name
]
if skip_debian_packaging:
declarable_paragraphs = [
para
for para in declarable_paragraphs
if not is_paragraph_debian_packaging(para)
]
declared_licenses = [
paragraph.license.name for paragraph in declarable_paragraphs
]
if filter_duplicates:
return filter_duplicate_strings(declared_licenses)
else:
return declared_licenses
def get_copyright(
self,
skip_debian_packaging=False,
unique_copyrights=False,
*args,
**kwarg,
):
"""
Return a copyright string from copyright statements collected in this
structured copyright file.
If `unique_copyrights` is True, only unique copyrights are returned.
If `skip_debian_packaging` is True, skips the declared license for
`Files: debian/*` paragraph.
"""
declarable_copyrights = []
seen_copyrights = set()
# TODO: Only Unique Holders (copyright without years) should be reported
# TODO: Report line numbers
for copyright_detection in self.copyright_detections:
if (
skip_debian_packaging
and is_paragraph_debian_packaging(copyright_detection.paragraph)
):
continue
if not isinstance(
copyright_detection.paragraph,
(CopyrightHeaderParagraph, CopyrightFilesParagraph)
):
continue
if unique_copyrights:
for copyrght in copyright_detection.copyrights:
if copyrght not in seen_copyrights:
if any(x in copyrght for x in ('unknown', 'none',)):
continue
seen_copyrights.add(copyrght)
declarable_copyrights.append(copyrght)
continue
declarable_copyrights.extend(copyright_detection.copyrights)
return '\n'.join(declarable_copyrights)
def detect_copyrights(self):
"""
Return a list of CopyrightDetection objects found in paragraphs.
"""
# TODO: We should also track line numbers in the file where a license was found
copyright_detections = []
for paragraph in self.debian_copyright.paragraphs:
copyrights = []
if isinstance(paragraph, (CopyrightHeaderParagraph, CopyrightFilesParagraph)):
pcs = paragraph.copyright.statements or []
for p in pcs:
p = p.dumps()
copyrights.append(p)
copyright_detections.append(
CopyrightDetection(paragraph=paragraph, copyrights=copyrights)
)
# We detect plain copyrights if we didn't find any
if not copyrights:
copyrights = copyright_detector(self.location)
copyright_detections.append(
CopyrightDetection(paragraph=None, copyrights=copyrights)
)
self.copyright_detections = copyright_detections
def get_license_expression(
self,
skip_debian_packaging=False,
simplify_licenses=False,
*args,
**kwargs,
):
"""
Return a license expression string built from the this object
``license_detections``.
If `skip_debian_packaging` is True, skips the declared license for
`Files: debian/*` paragraph.
If `simplify_licenses` is True, license expressions are deduplicated by
Licensing.dedup() and then returned.
"""
if not self.license_detections:
raise_no_license_found_error(location=self.location)
license_detections = [
license_detection
for license_detection in self.license_detections
if license_detection.is_detection_reportable()
]
if skip_debian_packaging:
license_detections = [
license_detection
for license_detection in license_detections
if not is_paragraph_debian_packaging(license_detection.paragraph)
]
expressions = [
license_detection.license_expression_object
for license_detection in license_detections
if license_detection.license_expression_object != None
]
if expressions:
license_expression = str(combine_expressions(expressions, unique=False))
else:
license_matches = list(self.license_matches)
if license_matches:
license_expression = get_license_expression_from_matches(license_matches)
else:
raise_no_license_found_error(location=self.location)
if TRACE:
logger_debug(f"StructuredCopyrightProcessor: get_license_expression: license_expression: {license_expression}")
if simplify_licenses:
return dedup_expression(license_expression=license_expression)
else:
return license_expression
def detect_license(self):
"""
Return a list of DebianLicenseDetection objects found in paragraphs.
"""
# TODO: We should also track line numbers in the file where a license was found
license_detections = []
edebian_copyright = EnhancedDebianCopyright(debian_copyright=self.debian_copyright)
debian_licensing = DebianLicensing.from_license_paragraphs(
paras_with_license=edebian_copyright.paragraphs_with_license_text
)
license_detections.extend(debian_licensing.license_detections)
header_paragraph = edebian_copyright.header_paragraph
if header_paragraph.license.name:
header_license_detections = self.get_license_detections(
paragraph=header_paragraph,
debian_licensing=debian_licensing,
)
license_detections.extend(header_license_detections)
for file_paragraph in edebian_copyright.file_paragraphs:
files_license_detections = self.get_license_detections(
paragraph=file_paragraph,
debian_licensing=debian_licensing,
)
license_detections.extend(files_license_detections)
license_detections.extend(
self.detect_license_in_other_paras(
other_paras=edebian_copyright.other_paragraphs
)
)
self.license_detections = license_detections
@staticmethod
def get_license_detections(paragraph, debian_licensing):
"""
Return a DebianLicenseDetection object from header and files paragraphs.
`debian_licensing` is a DebianLicensing object used to drive detection
such that it is aware of license symbols and references.
"""
license_detections = []
name = paragraph.license.name
if not name:
license_detections.append(
get_license_detection_from_nameless_paragraph(paragraph=paragraph)
)
return license_detections
license_field_detection = debian_licensing.get_license_detection_from_license_field(paragraph)
license_detections.append(license_field_detection)
other_field_detections = get_license_detections_from_other_fields(paragraph) or []
license_detections.extend(other_field_detections)
return license_detections
@staticmethod
def detect_license_in_other_paras(other_paras):
"""
Run license Detection on the entire paragraph text and return result in a
License Detection object.
`other_paras` is a list of CatchAllParagraph paragraphs.
"""
license_detections = []
for paragraph in other_paras:
for field_name, field_value in paragraph.to_dict().items():
start_line, _ = paragraph.get_field_line_numbers(field_name)
matches = get_license_matches_from_query_string(
query_string=field_value,
start_line=start_line,
)
if not matches:
continue
normalized_expression = get_license_expression_from_matches(
license_matches=matches,
)
license_detections.append(
DebianLicenseDetection(
paragraph=paragraph,
license_expression_object=normalized_expression,
license_matches=matches,
)
)
return license_detections
def get_license_detections_mapping(self):