-
-
Notifications
You must be signed in to change notification settings - Fork 574
/
Copy pathmodels.py
2732 lines (2284 loc) · 91.4 KB
/
models.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 hashlib
import io
import os
import sys
import traceback
from collections import Counter
from collections import defaultdict
from itertools import chain
from operator import itemgetter
from os.path import abspath
from os.path import dirname
from os.path import exists
from os.path import join
from time import time
from pathlib import Path
import attr
from license_expression import ExpressionError
from license_expression import Licensing
from commoncode.fileutils import file_base_name
from commoncode.fileutils import file_name
from commoncode.fileutils import resource_iter
from licensedcode import MIN_MATCH_HIGH_LENGTH
from licensedcode import MIN_MATCH_LENGTH
from licensedcode import SMALL_RULE
from licensedcode.cache import get_index
from licensedcode.frontmatter import SaneYAMLHandler
from licensedcode.frontmatter import FrontmatterPost
from licensedcode.frontmatter import dumps_frontmatter
from licensedcode.frontmatter import load_frontmatter
from licensedcode.frontmatter import get_rule_text
from licensedcode.languages import LANG_INFO as known_languages
from licensedcode.spans import Span
from licensedcode.tokenize import index_tokenizer
from licensedcode.tokenize import index_tokenizer_with_stopwords
from licensedcode.tokenize import key_phrase_tokenizer
from licensedcode.tokenize import KEY_PHRASE_OPEN
from licensedcode.tokenize import KEY_PHRASE_CLOSE
from scancode.api import SCANCODE_LICENSE_RULE_URL
from scancode.api import SCANCODE_RULE_URL
"""
Reference License and license Rule structures persisted as a combo of a YAML
data file and one or more text files containing license or notice texts.
"""
# Tracing flags
TRACE = False or os.environ.get('SCANCODE_DEBUG_LICENSE_MODELS', False)
# Set to True to print more detailed representations of objects when tracing
TRACE_REPR = False
def logger_debug(*args):
pass
if TRACE:
use_print = True
if use_print:
printer = print
else:
import logging
logger = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
printer = logger.debug
def logger_debug(*args):
return printer(' '.join(isinstance(a, str) and a or repr(a) for a in args))
# these are globals but always side-by-side with the code so do no not move them around
data_dir = join(abspath(dirname(__file__)), 'data')
licenses_data_dir = join(data_dir, 'licenses')
rules_data_dir = join(data_dir, 'rules')
FOSS_CATEGORIES = set([
'Copyleft',
'Copyleft Limited',
'Patent License',
'Permissive',
'Public Domain',
])
OTHER_CATEGORIES = set([
'Commercial',
'Proprietary Free',
'Free Restricted',
'Source-available',
'Unstated License',
])
CATEGORIES = FOSS_CATEGORIES | OTHER_CATEGORIES
@attr.s(slots=True)
class License:
"""
A license consists of these files, where <key> is the license key:
- <key>.yml : the license data in YAML
- <key>.LICENSE: the license text
A License object is identified by a unique `key` and its data stored in the
`src_dir` directory. Key is a lower-case unique ascii string.
"""
key = attr.ib(
repr=True,
metadata=dict(
help='Mandatory unique key: this is a lower case string with only '
'ASCII characters, digits, underscore or dots.')
)
is_deprecated = attr.ib(
default=False,
repr=False,
metadata=dict(
help='Flag set to True if this is a deprecated license. '
'The policy is to never delete a license key once attributed. '
'Instead it can be marked as deprecated and will be ignored for '
'detection. When marking a license as deprecated, add notes '
'explaining why this is deprecated. And all license rules must be '
'updated accordingly to point to a new license expression.')
)
language = attr.ib(
default='en',
repr=False,
metadata=dict(
help='Two-letter ISO 639-1 language code if this license text is '
'not in English. See https://en.wikipedia.org/wiki/ISO_639-1 . '
'NOTE: each translation of a license text MUST have a different '
'license key. By convention, we append the language code to the '
'license key')
)
short_name = attr.ib(
default=None,
repr=False,
metadata=dict(
help='Commonly used license short name, often abbreviated.')
)
name = attr.ib(
default=None,
repr=False,
metadata=dict(
help='License full name')
)
category = attr.ib(
default=None,
repr=False,
metadata=dict(
help='Category for this license. Use "Unstated License" if unknown. '
'One of: ' + ', '.join(sorted(CATEGORIES)))
)
owner = attr.ib(
default=None,
repr=False,
metadata=dict(
help='Required owner or author for this license. '
'Use "Unspecified" if unknown.')
)
homepage_url = attr.ib(
default=None,
repr=False,
metadata=dict(
help='Homepage URL for this license')
)
notes = attr.ib(
default=None,
repr=False,
metadata=dict(
help='Free text notes.')
)
is_builtin = attr.ib(
default=True,
repr=False,
metadata=dict(
help='Flag set to True if this is a builtin standard license.')
)
# TODO: add the license key(s) this exception applies to
is_exception = attr.ib(
default=False,
repr=False,
metadata=dict(
help='Flag set to True if this is a license exception')
)
is_unknown = attr.ib(
default=False,
repr=False,
metadata=dict(
help='Flag set to True if this license is for some unknown licensing')
)
is_generic = attr.ib(
default=False,
repr=False,
metadata=dict(
help='Flag set to True if this license if for a generic, unnamed license')
)
spdx_license_key = attr.ib(
default=None,
repr=False,
metadata=dict(
help='SPDX short form license identifier. '
'Use a LicenseRef-scancode-<license key> for licenses not listed in '
'the SPDX licenses list')
)
other_spdx_license_keys = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='List of other SPDX keys, such as the id of a deprecated '
'license or alternative LicenseRef identifiers')
)
osi_license_key = attr.ib(
default=None,
repr=False,
metadata=dict(
help='OSI License key if available')
)
text_urls = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='Text URL for this license')
)
osi_url = attr.ib(
default=None,
repr=False,
metadata=dict(
help='OpenSource.org URL for this license')
)
faq_url = attr.ib(
default=None,
repr=False,
metadata=dict(
help='Frequently Asked Questions page URL for this license')
)
other_urls = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='A list of other interesting URLs for this license')
)
key_aliases = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='List of alternative license keys for this license')
)
minimum_coverage = attr.ib(
default=0,
repr=False,
metadata=dict(
help='Can this license text be matched only with a minimum coverage e.g., '
'when a minimum proportion of tokens have been matched? This is as a '
'float between 0 and 100 where 100 means that all tokens must be '
'matched and a smaller value means a smaller proportion of matched '
'tokens is acceptable. This is mormally computed at indexing time based on '
'the length of a license. Providing a stored value in the license data '
'file overrides this default computed value. For example, a short '
'license notice such as "MIT license" must be matched with all its words, '
'e.g., a 100 minimum_coverage. Otherwise matching only "mit" or '
'"license" is not a strong enough licensing clue.')
)
standard_notice = attr.ib(
default=None,
repr=False,
metadata=dict(
help='Standard notice text for this license.')
)
###########################################################################
# lists of clues that can be ignored when detected in this license as they
# are part of the license or rule text itself
ignorable_copyrights = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='List of copyrights that can be ignored when detected in this '
'text as they are part of the license or rule text proper and can'
'optionally be excluded from the copyrights detection')
)
ignorable_holders = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='List of holders that can be ignored when detected in this '
'text as they are part of the license or rule text proper and can'
'optionally be excluded from the holders detection')
)
ignorable_authors = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='List of authors that can be ignored when detected in this '
'text as they are part of the license or rule text proper and can'
'optionally be excluded from the authors detection')
)
ignorable_urls = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='List of holders that can be ignored when detected in this '
'text as they are part of the license or rule text proper and can'
'optionally be excluded from the holders detection')
)
ignorable_emails = attr.ib(
default=attr.Factory(list),
repr=False,
metadata=dict(
help='List of emails that can be ignored when detected in this '
'text as they are part of the license or rule text proper and can'
'optionally be excluded from the emails detection')
)
text = attr.ib(
default=None,
repr=False,
metadata=dict(
help='License text.')
)
@classmethod
def from_dir(cls, key, licenses_data_dir=licenses_data_dir, check_consistency=True, is_builtin=True):
"""
Return a new License object for a license ``key`` and load its attribute
from a data file stored in ``licenses_data_dir``.
"""
lic = cls(key=key, is_builtin=is_builtin)
license_file = lic.license_file(licenses_data_dir=licenses_data_dir)
lic.load(license_file=license_file, check_consistency=check_consistency)
return lic
def license_file(self, licenses_data_dir=licenses_data_dir):
return join(licenses_data_dir, f'{self.key}.LICENSE')
def update(self, mapping):
for k, v in mapping.items():
setattr(self, k, v)
def __copy__(self):
oldl = self.to_dict()
newl = License(key=self.key)
newl.update(oldl)
return newl
def to_dict(self, include_ignorables=True, include_text=False):
"""
Return an ordered mapping of license data (excluding text, unless
``include_text`` is True). Fields with empty values are not included.
Optionally include the "ignorable*" attributes if ``include_ignorables``
is True.
"""
# do not dump false, empties and paths
def dict_fields(attr, value):
if not value:
return False
if isinstance(value, str) and not value.strip():
return False
# default to English which is implied
if attr.name == 'language' and value == 'en':
return False
if attr.name == 'minimum_coverage' and value == 100:
return False
if not include_ignorables and attr.name.startswith('ignorable_'):
return False
if not include_text and attr.name == 'text':
return False
return True
data = attr.asdict(self, filter=dict_fields, dict_factory=dict)
cv = data.get('minimum_coverage', 0)
if cv:
data['minimum_coverage'] = as_int(cv)
if include_text:
data['text'] = self.text or ''
return data
def dump(self, licenses_data_dir):
"""
Dump a representation of this license as a .LICENSE file with:
- the license data as YAML frontmatter
- the license text
"""
metadata = self.to_dict()
content = self.text
rule_post = FrontmatterPost(content=content, handler=SaneYAMLHandler(), **metadata)
output = dumps_frontmatter(post=rule_post)
license_file = self.license_file(licenses_data_dir=licenses_data_dir)
with open(license_file, 'w') as of:
of.write(output)
def load(self, license_file, check_consistency=True):
"""
Populate license data from a .LICENSE file stored as a YAML frontmatter.
Does not load text files yet.
Unknown fields are ignored and not bound to the License object.
"""
try:
post = load_frontmatter(license_file)
data = post.metadata
if check_consistency:
if not data:
raise InvalidLicense(
f'Cannot load License with empty YAML frontmatter: '
f'{self}: file://{license_file}'
)
if not post.content:
if check_consistency:
if not any(
attribute in data
for attribute in ('is_deprecated', 'is_generic', 'is_unknown')
):
raise InvalidLicense(
f'Cannot load License with empty text: '
f'only deprecated, generic or unknown licenses can exist without text '
f'{self}: file://{license_file}'
)
self.text = ''
else:
self.text = post.content.lstrip("\n")
for k, v in data.items():
if k == 'minimum_coverage':
v = as_int(v)
if k == 'key':
assert self.key == v, (
'The license "key" attribute in the YAML frontmatter MUST ' +
'be the same as the base name of this .LICENSE ' +
'license file. ' +
f'Yet file name = {self.key} and license key = {v}'
)
setattr(self, k, v)
except Exception as e:
# this is a rare case: fail loudly
print()
print('#############################')
print('INVALID LICENSE YAML FILE:', f'file://{self.license_file}')
print('#############################')
print(traceback.format_exc())
print('#############################')
raise e
return self
def spdx_keys(self):
"""
Yield SPDX keys for this license.
"""
if self.spdx_license_key:
yield self.spdx_license_key
for key in self.other_spdx_license_keys:
yield key
@staticmethod
def validate(licenses, verbose=False, no_dupe_urls=False):
"""
Check that the ``licenses`` a mapping of {key: License} are valid.
Return dictionaries of infos, errors and warnings mapping a license key
to validation issue messages. Print messages if ``verbose`` is True.
NOTE: we DO NOT run this validation as part of loading or constructing
License objects. Instead this is invoked ONLY as part of the test suite.
"""
infos = defaultdict(list)
warnings = defaultdict(list)
errors = defaultdict(list)
# used for global dedupe of texts
by_spdx_key_lowered = defaultdict(list)
by_text = defaultdict(list)
by_short_name_lowered = defaultdict(list)
by_name_lowered = defaultdict(list)
for key, lic in licenses.items():
warn = warnings[key].append
info = infos[key].append
error = errors[key].append
if lic.name:
by_name_lowered[lic.name.lower()].append(lic)
else:
by_name_lowered[lic.name].append(lic)
if lic.short_name:
by_short_name_lowered[lic.short_name.lower()].append(lic)
else:
by_short_name_lowered[lic.short_name].append(lic)
if lic.key != lic.key.lower():
error('Incorrect license key case: must be all lowercase.')
if len(lic.key) > 50:
error('key must be 50 characters or less.')
if '_'in lic.key:
error('key cannot contain an underscore: this is not valid in SPDX.')
if not lic.short_name:
error('No short name')
elif len(lic.short_name) > 50:
error('short name must be 50 characters or less.')
if not lic.name:
error('No name')
if not lic.category:
error('No category: Use "Unstated License" if not known.')
if lic.category and lic.category not in CATEGORIES:
cats = '\n'.join(sorted(CATEGORIES))
error(
f'Unknown license category: {lic.category}.\n' +
f'Use one of these valid categories:\n{cats}'
)
if not lic.owner:
error('No owner: Use "Unspecified" if not known.')
if lic.language not in known_languages:
error(f'Unknown language: {lic.language}')
if lic.is_unknown:
if not 'unknown' in lic.key and lic.key != 'no-license':
error(
'is_unknown can be true only for licenses with '
'"unknown " in their key string.'
)
if lic.is_generic and lic.is_unknown:
error('is_generic and is_unknown flags are incompatible')
# URLS dedupe and consistency
if no_dupe_urls:
if lic.text_urls and not all(lic.text_urls):
warn('Some empty text_urls values')
if lic.other_urls and not all(lic.other_urls):
warn('Some empty other_urls values')
# redundant URLs used multiple times
if lic.homepage_url:
if lic.homepage_url in lic.text_urls:
warn('Homepage URL also in text_urls')
if lic.homepage_url in lic.other_urls:
warn('Homepage URL also in other_urls')
if lic.homepage_url == lic.faq_url:
warn('Homepage URL same as faq_url')
if lic.homepage_url == lic.osi_url:
warn('Homepage URL same as osi_url')
if lic.osi_url or lic.faq_url:
if lic.osi_url == lic.faq_url:
warn('osi_url same as faq_url')
all_licenses = lic.text_urls + lic.other_urls
for url in lic.osi_url, lic.faq_url, lic.homepage_url:
if url:
all_licenses.append(url)
if not len(all_licenses) == len(set(all_licenses)):
warn('Some duplicated URLs')
# local text consistency
text = lic.text
license_itokens = tuple(index_tokenizer(text))
if not license_itokens:
info('No license text')
else:
# for global dedupe
by_text[license_itokens].append(f'{key}: TEXT')
# SPDX consistency
if lic.spdx_license_key:
if len(lic.spdx_license_key) > 50:
error('spdx_license_key must be 50 characters or less.')
by_spdx_key_lowered[lic.spdx_license_key.lower()].append(key)
else:
# SPDX license key is now mandatory
error('No SPDX license key')
for oslk in lic.other_spdx_license_keys:
by_spdx_key_lowered[oslk].append(key)
# global SPDX consistency
multiple_spdx_keys_used = {
k: v for k, v in by_spdx_key_lowered.items()
if len(v) > 1
}
if multiple_spdx_keys_used:
for k, lkeys in multiple_spdx_keys_used.items():
errors['GLOBAL'].append(
f'SPDX key: {k} used in multiple licenses: ' +
', '.join(sorted(lkeys)))
# global text dedupe
multiple_texts = {k: v for k, v in by_text.items() if len(v) > 1}
if multiple_texts:
for k, msgs in multiple_texts.items():
errors['GLOBAL'].append(
'Duplicate texts in multiple licenses: ' +
', '.join(sorted(msgs))
)
# global short_name dedupe
for short_name, licenses in by_short_name_lowered.items():
if len(licenses) == 1:
continue
errors['GLOBAL'].append(
f'Duplicate short name (ignoring case): {short_name} in licenses: ' +
', '.join(sorted(l.key for l in licenses))
)
# global name dedupe
for name, licenses in by_name_lowered.items():
if len(licenses) == 1:
continue
errors['GLOBAL'].append(
f'Duplicate name (ignoring case): {name} in licenses: ' +
', '.join(sorted(l.key for l in licenses))
)
errors = {k: v for k, v in errors.items() if v}
warnings = {k: v for k, v in warnings.items() if v}
infos = {k: v for k, v in infos.items() if v}
if verbose:
print('Licenses validation errors:')
for key, msgs in sorted(errors.items()):
print(f'ERRORS for: {key}:', '\n'.join(msgs))
print('Licenses validation warnings:')
for key, msgs in sorted(warnings.items()):
print(f'WARNINGS for: {key}:', '\n'.join(msgs))
print('Licenses validation infos:')
for key, msgs in sorted(infos.items()):
print(f'INFOS for: {key}:', '\n'.join(msgs))
return errors, warnings, infos
def ignore_editor_tmp_files(location):
return location.endswith('.swp')
def load_licenses(
licenses_data_dir=licenses_data_dir,
with_deprecated=False,
check_consistency=True,
is_builtin=True,
):
"""
Return a mapping of {key: License} loaded from license data and text files
found in ``licenses_data_dir``. Raise Exceptions if there are dangling or
orphaned files.
Optionally include deprecated license if ``with_deprecated`` is True.
Optionally check for dangling orphaned files if ``check_dangling`` is True.
"""
all_files = list(resource_iter(
location=licenses_data_dir,
ignored=ignore_editor_tmp_files,
with_dirs=False,
follow_symlinks=True,
))
licenses = {}
for license_file in all_files:
if license_file.endswith('.LICENSE'):
if TRACE:
logger_debug('load_licenses: license_file:', license_file)
key = file_base_name(license_file)
try:
lic = License.from_dir(
key=key,
licenses_data_dir=licenses_data_dir,
check_consistency=check_consistency,
is_builtin=is_builtin,
)
except Exception as e:
msg = (
f'Failed to load license: {key} from: '
f'file://{licenses_data_dir}/{key}.LICENSE with error: {e}'
)
raise InvalidLicense(msg) from e
if not with_deprecated and lic.is_deprecated:
continue
licenses[key] = lic
if not licenses:
msg = (
'No licenses were loaded. Check to see if the license data files '
f'are available at "{licenses_data_dir}".'
)
raise InvalidLicense(msg)
return licenses
def get_rules(
licenses_db=None,
licenses_data_dir=licenses_data_dir,
rules_data_dir=rules_data_dir,
validate=False,
is_builtin=True,
):
"""
Yield Rule objects loaded from a ``licenses_db`` and license files found in
``licenses_data_dir`` and rule files found in `rules_data_dir`. Raise an
Exception if a rule is inconsistent or incorrect.
"""
licenses_db = licenses_db or load_licenses(
licenses_data_dir=licenses_data_dir,
)
rules = list(load_rules(
rules_data_dir=rules_data_dir,
is_builtin=is_builtin,
))
if validate:
validate_rules(rules=rules, licenses_by_key=licenses_db)
licenses_as_rules = build_rules_from_licenses(licenses_db)
return chain(licenses_as_rules, rules)
def get_license_dirs(additional_dirs):
"""
Return a list of all subdirectories containing license files within the
input list of additional directories. These directories do not have to be absolute paths.
"""
return [f"{str(Path(path).absolute())}/licenses" for path in additional_dirs]
def get_rule_dirs(additional_dirs):
"""
Return a list of all subdirectories containing rule files within the
input list of additional directories. These directories do not have to be absolute paths.
"""
return [f"{str(Path(path).absolute())}/rules" for path in additional_dirs]
def get_paths_to_installed_licenses_and_rules():
"""
Return a list of paths to externally packaged licenses or rules that the user has
installed. Gets a list of all of these licenses (installed as plugins) and
then gets the plugins containing licenses by checking that their names start
with a common prefix.
"""
from importlib_metadata import entry_points
from licensedcode.additional_license_location_provider import get_location
installed_plugins = entry_points(group='scancode_additional_license_location_provider')
paths = []
for plugin in installed_plugins:
# get path to directory of licenses and/or rules
paths.append(get_location(plugin.name))
return paths
def load_licenses_from_multiple_dirs(
builtin_license_data_dir,
additional_license_data_dirs,
with_deprecated=False,
):
"""
Return a mapping of {key: License} combining a list of
``additional_license_data_dirs`` containing additional licenses with the
builtin ``builtin_license_data_dir`` licenses into the same mapping.
"""
#raise Exception(builtin_license_data_dir)
combined_licenses = load_licenses(
licenses_data_dir=builtin_license_data_dir,
with_deprecated=with_deprecated,
is_builtin=True,
)
for license_dir in additional_license_data_dirs:
additional_licenses = load_licenses(
licenses_data_dir=license_dir,
with_deprecated=with_deprecated,
is_builtin=False,
)
# validate that additional licenses keys do not exist as builtin
duplicate_keys = set(combined_licenses).intersection(set(additional_licenses))
if duplicate_keys:
dupes = ', '.join(sorted(duplicate_keys))
message = f'Duplicate licenses found when loading additional licenses from: {license_dir}: {dupes}'
raise ValueError(message)
combined_licenses.update(additional_licenses)
return combined_licenses
def get_rules_from_multiple_dirs(
licenses_db,
builtin_rule_data_dir,
additional_rules_data_dirs,
):
"""
Yield Rule(s) built from:
- A ``license_db`` mapping of {key: License}
- The ``builtin_rule_data_dir`` of builtin license rules
- The list of ``additional_rules_data_dirs`` containing additional rules.
"""
# first load all builtin
combined_rules = list(get_rules(
licenses_db=licenses_db,
rules_data_dir=builtin_rule_data_dir,
))
# load additional rules
for rules_dir in additional_rules_data_dirs or []:
combined_rules.extend(load_rules(
rules_data_dir=rules_dir,
is_builtin=False,
))
validate_rules(rules=combined_rules, licenses_by_key=licenses_db)
return combined_rules
class InvalidLicense(Exception):
pass
def validate_additional_license_data(additional_directories, scancode_license_dir):
"""
Raises an exception if there are any invalid licenses in the directories of
additional licenses.
"""
licenses = load_licenses_from_multiple_dirs(
additional_license_data_dirs=additional_directories,
builtin_license_data_dir=scancode_license_dir
)
errors, _, _ = License.validate(
licenses,
verbose=False,
)
if errors:
message = ['Errors while validating licenses:']
for key, msgs in errors.items():
message.append('')
message.append(f'License: {key}')
for msg in msgs:
message.append(f' {msg!r}')
raise InvalidLicense('\n'.join(message))
def _ignorable_clue_error(rule, rules_dir):
"""
Return a pair of the result of validating a rule's ignorable clues and expected ignorable clues
if there is an error. Otherwise, returns None.
"""
result = get_ignorables(rule.rule_file(rules_data_dir=rules_dir))
expected = get_normalized_ignorables(rule)
if result != expected:
rule_file = rule.rule_file(rules_data_dir=rules_dir)
result['files'] = [
f'file://{rule_file}',
]
return result, expected
def validate_ignorable_clues(rule_directories, is_builtin):
"""
Raises an exception if any ignorable clues declared in a Rule are improperly detected
in the rule text file.
"""
messages = ['Errors while validating ignorable rules:']
error_present = False
for rules_dir in rule_directories:
r = list(load_rules(
rules_data_dir=rules_dir,
is_builtin=is_builtin,
))
for rule in r:
if _ignorable_clue_error(rule, rules_dir):
error_present = True
result, expected = _ignorable_clue_error(rule, rules_dir)
messages.append('')
messages.append(f'{rule!r}')
messages.append('Result:')
messages.append(result)
messages.append('Expected:')
messages.append(expected)
if error_present:
raise InvalidRule('\n'.join(messages))
class InvalidRule(Exception):
pass
class InvalidLicense(Exception):
pass
def _validate_all_rules(rules, licenses_by_key):
"""
Return a mapping of {error message: [list of Rule]} from validating a list
of ``rules`` Rule integrity and correctness using known licenses from a
mapping of ``licenses_by_key`` {key: License}`.
"""
licensing = Licensing(symbols=licenses_by_key.values())
errors = defaultdict(list)
for rule in rules:
for err_msg in rule.validate(licensing):
errors[err_msg].append(rule)
return errors
def validate_rules(rules, licenses_by_key, with_text=False, rules_data_dir=rules_data_dir):
"""
Return a mapping of {error message: [list of Rule]) from validating a list
of ``rules`` Rule integrity and correctness using known licenses from a
mapping of ``licenses_by_key`` {key: License}`.
"""
errors = _validate_all_rules(rules=rules, licenses_by_key=licenses_by_key)
if errors:
message = ['Errors while validating rules:']
for msg, rules in errors.items():
message.append('')
message.append(msg)
for rule in rules:
message.append(f' {rule!r}')
rule_file = rule.rule_file(rules_data_dir=rules_data_dir)
if rule_file and exists(rule_file):
message.append(f' file://{rule_file}')
if with_text:
txt = rule.text[:100].strip()
message.append(f' {txt}...')
raise InvalidRule('\n'.join(message))
def build_rules_from_licenses(licenses_by_key):
"""
Return an iterable of rules built from each license text from a