-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathmodel.py
More file actions
1948 lines (1721 loc) · 75.4 KB
/
model.py
File metadata and controls
1948 lines (1721 loc) · 75.4 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
#!/usr/bin/env python
# -*- coding: utf8 -*-
# ============================================================================
# Copyright (c) nexB Inc. http://www.nexb.com/ - All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.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.
# ============================================================================
"""
AboutCode toolkit is a tool to process ABOUT files. ABOUT files are
small text files that document the provenance (aka. the origin and
license) of software components as well as the essential obligation
such as attribution/credits and source code redistribution. See the
ABOUT spec at http://dejacode.org.
AboutCode toolkit reads and validates ABOUT files and collect software
components inventories.
"""
import json
import os
import posixpath
from requests import get
import traceback
from itertools import zip_longest
from urllib.parse import urljoin
from urllib.parse import urlparse
from license_expression import Licensing
from packageurl import PackageURL
from attributecode import __version__
from attributecode import CRITICAL
from attributecode import ERROR
from attributecode import INFO
from attributecode import WARNING
from attributecode import api
from attributecode import Error
from attributecode import saneyaml
from attributecode import gen
from attributecode import util
from attributecode.transform import write_excel
from attributecode.util import add_unc
from attributecode.util import boolean_fields
from attributecode.util import copy_license_notice_files
from attributecode.util import copy_file
from attributecode.util import csv
from attributecode.util import file_fields
from attributecode.util import filter_errors
from attributecode.util import get_spdx_key_and_lic_key_from_licdb
from attributecode.util import is_valid_name
from attributecode.util import on_windows
from attributecode.util import norm
from attributecode.util import replace_tab_with_spaces
from attributecode.util import wrap_boolean_value
from attributecode.util import UNC_PREFIX
from attributecode.util import ungroup_licenses
from attributecode.util import ungroup_licenses_from_sctk
genereated_tk_version = "# Generated with AboutCode Toolkit Version %s \n\n" % __version__
class Field(object):
"""
An ABOUT file field. The initial value is a string. Subclasses can and
will alter the value type as needed.
"""
def __init__(self, name=None, value=None, required=False, present=False):
# normalized names are lowercased per specification
self.name = name
# save this and do not mutate it afterwards
if isinstance(value, str):
self.original_value = value
# elif value:
# Don't convert it to string. Leave the format as-is
# self.original_value = repr(value)
else:
self.original_value = value
# can become a string, list or OrderedDict() after validation
self.value = value or self.default_value()
self.required = required
# True if the field is present in an About object
self.present = present
self.errors = []
def default_value(self):
return ''
def validate(self, *args, **kwargs):
"""
Validate and normalize thyself. Return a list of errors.
"""
errors = []
name = self.name
self.value = self.default_value()
if not self.present:
# required fields must be present
if self.required:
msg = u'Field %(name)s is required'
errors.append(Error(CRITICAL, msg % locals()))
return errors
else:
# present fields should have content ...
# The boolean value can be True, False and None
# The value True or False is the content of boolean fields
if not name in boolean_fields and not self.has_content:
# ... especially if required
if self.required:
msg = u'Field %(name)s is required and empty'
severity = CRITICAL
else:
severity = INFO
msg = u'Field %(name)s is present but empty.'
errors.append(Error(severity, msg % locals()))
else:
# present fields with content go through validation...
# first trim any trailing spaces on each line
if isinstance(self.original_value, str):
value = '\n'.join(s.rstrip() for s
in self.original_value.splitlines(False))
# then strip leading and trailing spaces
value = value.strip()
else:
value = self.original_value
self.value = value
try:
validation_errors = self._validate(*args, **kwargs)
errors.extend(validation_errors)
except Exception as e:
emsg = repr(e)
msg = u'Error validating field %(name)s: %(value)r: %(emsg)r'
errors.append(Error(CRITICAL, msg % locals()))
raise
# set or reset self
self.errors = errors
return errors
def _validate(self, *args, **kwargs):
"""
Validate and normalize thyself. Return a list of errors.
Subclasses should override as needed.
"""
return []
def _serialized_value(self):
return self.value if self.value else u''
def serialize(self):
"""
Return a unicode serialization of self in the ABOUT format.
"""
name = self.name
value = self.serialized_value() or u''
if self.has_content or self.value:
value = value.splitlines(True)
# multi-line
if len(value) > 1:
# This code is used to read the YAML's multi-line format in
# ABOUT files
# (Test: test_loads_dumps_is_idempotent)
if value[0].strip() == u'|' or value[0].strip() == u'>':
value = u' '.join(value)
else:
# Insert '|' as the indicator for multi-line follow by a
# newline character
value.insert(0, u'|\n')
# insert 4 spaces for newline values
value = u' '.join(value)
else:
# FIXME: See https://github.com/nexB/aboutcode-toolkit/issues/323
# The yaml.load() will throw error if the parsed value
# contains ': ' character. A work around is to put a pipe, '|'
# to indicate the whole value as a string
if value and ': ' in value[0]:
value.insert(0, u'|\n')
# insert 4 spaces for newline values
value = u' '.join(value)
else:
value = u''.join(value)
serialized = u'%(name)s:' % locals()
if value:
serialized += ' ' + '%(value)s' % locals()
return serialized
def serialized_value(self):
"""
Return a unicode serialization of self in the ABOUT format.
Does not include a white space for continuations.
"""
return self._serialized_value() or u''
@property
def has_content(self):
return self.original_value
def __repr__(self):
name = self.name
value = self.value
required = self.required
has_content = self.has_content
present = self.present
r = ('Field(name=%(name)r, value=%(value)r, required=%(required)r, present=%(present)r)')
return r % locals()
def __eq__(self, other):
"""
Equality based on string content value, ignoring spaces.
"""
return (isinstance(other, self.__class__)
and self.name == other.name
and self.value == other.value)
class StringField(Field):
"""
A field containing a string value possibly on multiple lines.
The validated value is a string.
"""
def _validate(self, *args, **kwargs):
errors = super(StringField, self)._validate(*args, ** kwargs)
no_special_char_field = [
'license_expression', 'license_key', 'license_name']
name = self.name
if name in no_special_char_field:
val = self.value
special_char = detect_special_char(val)
if special_char:
msg = (u'The following character(s) cannot be in the %(name)s: '
'%(special_char)r' % locals())
errors.append(Error(ERROR, msg))
return errors
def _serialized_value(self):
return self.value if self.value else u''
def __eq__(self, other):
"""
Equality based on string content value, ignoring spaces
"""
if not (isinstance(other, self.__class__)
and self.name == other.name):
return False
if self.value == other.value:
return True
# compare values stripped from spaces. Empty and None are equal
if self.value:
sval = u''.join(self.value.split())
if not sval:
sval = None
if other.value:
oval = u''.join(other.value.split())
if not oval:
oval = None
if sval == oval:
return True
class SingleLineField(StringField):
"""
A field containing a string value on a single line. The validated value is
a string.
"""
def _validate(self, *args, **kwargs):
errors = super(SingleLineField, self)._validate(*args, ** kwargs)
if self.value and isinstance(self.value, str) and '\n' in self.value:
name = self.name
value = self.original_value
msg = (u'Field %(name)s: Cannot span multiple lines: %(value)s'
% locals())
errors.append(Error(ERROR, msg))
return errors
class ListField(StringField):
"""
A field containing a list of string values, one per line. The validated
value is a list.
"""
def default_value(self):
return []
def _validate(self, *args, **kwargs):
errors = super(ListField, self)._validate(*args, ** kwargs)
# reset
self.value = []
if isinstance(self.original_value, str):
values = self.original_value.splitlines(False)
elif isinstance(self.original_value, list):
values = self.original_value
else:
values = [repr(self.original_value)]
for val in values:
if isinstance(val, str):
val = val.strip()
if not val:
name = self.name
msg = (u'Field %(name)s: ignored empty list value'
% locals())
errors.append(Error(INFO, msg))
continue
# keep only unique and report error for duplicates
if val not in self.value:
self.value.append(val)
else:
name = self.name
msg = (u'Field %(name)s: ignored duplicated list value: '
'%(val)r' % locals())
errors.append(Error(WARNING, msg))
return errors
def _serialized_value(self):
return self.value if self.value else u''
def __eq__(self, other):
"""
Equality based on sort-insensitive values
"""
if not (isinstance(other, self.__class__)
and self.name == other.name):
return False
if self.value == other.value:
return True
# compare values stripped from spaces.
sval = []
if self.value and isinstance(self.value, list):
sval = sorted(self.value)
oval = []
if other.value and isinstance(other.value, list):
oval = sorted(other.value)
if sval == oval:
return True
class PackageUrlField(StringField):
"""
A Package URL field. The validated value is a purl.
"""
def _validate(self, *args, **kwargs):
"""
Check that Package URL is valid. Return a list of errors.
"""
errors = super(PackageUrlField, self)._validate(*args, ** kwargs)
name = self.name
val = self.value
if not self.is_valid_purl(val):
msg = (u'Field %(name)s: Invalid Package URL: %(val)s' % locals())
errors.append(Error(WARNING, msg))
return errors
@staticmethod
def is_valid_purl(purl):
"""
Return True if a Package URL is valid.
"""
try:
return bool(PackageURL.from_string(purl))
except:
return False
class UrlListField(ListField):
"""
A URL field. The validated value is a list of URLs.
"""
def _validate(self, *args, **kwargs):
"""
Check that URLs are valid. Return a list of errors.
"""
errors = super(UrlListField, self)._validate(*args, ** kwargs)
name = self.name
val = self.value
for url in val:
if not self.is_valid_url(url):
msg = (u'Field %(name)s: Invalid URL: %(val)s' % locals())
errors.append(Error(WARNING, msg))
return errors
@staticmethod
def is_valid_url(url):
"""
Return True if a URL is valid.
"""
scheme, netloc, _path, _p, _q, _frg = urlparse(url)
valid = scheme in ('http', 'https', 'ftp') and netloc
return valid
class UrlField(StringField):
"""
A URL field. The validated value is a URL.
"""
def _validate(self, *args, **kwargs):
"""
Check that URL is valid. Return a list of errors.
"""
errors = super(UrlField, self)._validate(*args, ** kwargs)
name = self.name
val = self.value
if not self.is_valid_url(val):
msg = (u'Field %(name)s: Invalid URL: %(val)s' % locals())
errors.append(Error(WARNING, msg))
return errors
@staticmethod
def is_valid_url(url):
"""
Return True if a URL is valid.
"""
scheme, netloc, _path, _p, _q, _frg = urlparse(url)
valid = scheme in ('http', 'https', 'ftp') and netloc
return valid
class PathField(ListField):
"""
A field pointing to one or more paths relative to the ABOUT file location.
The validated value is an ordered dict of path->location or None.
The paths can also be resolved
"""
def default_value(self):
return {}
def _validate(self, *args, **kwargs):
"""
Ensure that paths point to existing resources. Normalize to posix
paths. Return a list of errors.
base_dir is the directory location of the ABOUT file used to resolve
relative paths to actual file locations.
"""
errors = super(PathField, self)._validate(*args, ** kwargs)
self.about_file_path = kwargs.get('about_file_path')
self.running_inventory = kwargs.get('running_inventory')
self.base_dir = kwargs.get('base_dir')
self.reference_dir = kwargs.get('reference_dir')
if self.base_dir:
self.base_dir = util.to_posix(self.base_dir)
name = self.name
# Why are paths a dict?
# Ans: The reason why the PathField use a dict is because
# for the FileTextField, the key is used as the path to the file and
# the value is used as the context of the file
# dict of normalized paths to a location or None
paths = {}
for path_value in self.value:
p = path_value.split(',')
for path in p:
path = path.strip()
path = util.to_posix(path)
# normalize eventual / to .
# and a succession of one or more ////// to . too
if path.strip() and not path.strip(posixpath.sep):
path = '.'
# removing leading and trailing path separator
# path are always relative
path = path.strip(posixpath.sep)
# the license files, if need to be copied, are located under the path
# set from the 'license-text-location' option, so the tool should check
# at the 'license-text-location' instead of the 'base_dir'
if not (self.base_dir or self.reference_dir):
msg = (u'Field %(name)s: Unable to verify path: %(path)s:'
u' No base directory provided' % locals())
errors.append(Error(ERROR, msg))
location = None
paths[path] = location
continue
if self.reference_dir:
location = posixpath.join(self.reference_dir, path)
else:
# The 'about_resource' should be a joined path with
# the 'about_file_path' and the 'base_dir
if not self.running_inventory and self.about_file_path:
# Get the parent directory of the 'about_file_path'
afp_parent = posixpath.dirname(self.about_file_path)
# Create a relative 'about_resource' path by joining the
# parent of the 'about_file_path' with the value of the
# 'about_resource'
arp = posixpath.join(afp_parent, path)
normalized_arp = posixpath.normpath(
arp).strip(posixpath.sep)
location = posixpath.join(
self.base_dir, normalized_arp)
else:
location = posixpath.normpath(
posixpath.join(self.base_dir, path))
location = util.to_native(location)
location = os.path.abspath(os.path.normpath(location))
location = util.to_posix(location)
location = add_unc(location)
if not os.path.exists(location):
# We don't want to show the UNC_PREFIX in the error message
location = util.to_posix(location.strip(UNC_PREFIX))
msg = (u'Field %(name)s: Path %(location)s not found'
% locals())
# We want to show INFO error for 'about_resource'
if name == u'about_resource':
errors.append(Error(INFO, msg))
else:
errors.append(Error(CRITICAL, msg))
location = None
paths[path] = location
self.value = paths
return errors
class AboutResourceField(PathField):
"""
Special field for about_resource, which points to the path(s) that the ABOUT
file is documenting. self.resolved_paths contains a list of
the paths resolved relative to the about file path.
"""
def __init__(self, *args, ** kwargs):
super(AboutResourceField, self).__init__(*args, ** kwargs)
self.resolved_paths = []
def _validate(self, *args, **kwargs):
errors = super(AboutResourceField, self)._validate(*args, ** kwargs)
return errors
class FileTextField(PathField):
"""
A path field pointing to one or more text files such as license files.
The validated value is an ordered dict of path->Text or None if no
location or text could not be loaded.
"""
def _validate(self, *args, **kwargs):
"""
Load and validate the texts referenced by paths fields. Return a list
of errors. base_dir is the directory used to resolve a file location
from a path.
"""
errors = super(FileTextField, self)._validate(*args, ** kwargs)
# a FileTextField is a PathField
# self.value is a paths to location ordered dict
# we will replace the location with the text content
name = self.name
for path, location in self.value.items():
if not location:
# do not try to load if no location
# errors about non existing locations are PathField errors
# already collected.
continue
try:
# TODO: we have lots the location by replacing it with a text
location = add_unc(location)
with open(location, encoding='utf-8', errors='replace') as txt:
text = txt.read()
self.value[path] = text
except Exception as e:
# only keep the first 100 char of the exception
emsg = repr(e)[:100]
msg = (u'Field %(name)s: Failed to load text at path: '
u'%(path)s '
u'with error: %(emsg)s' % locals())
errors.append(Error(ERROR, msg))
# set or reset self
self.errors = errors
return errors
class BooleanField(SingleLineField):
"""
An flag field with a boolean value. Validated value is False, True or None.
"""
def default_value(self):
return None
true_flags = ('yes', 'y', 'true', 'x')
false_flags = ('no', 'n', 'false')
flag_values = true_flags + false_flags
def _validate(self, *args, **kwargs):
"""
Check that flag are valid. Convert flags to booleans. Default flag to
False. Return a list of errors.
"""
errors = super(BooleanField, self)._validate(*args, ** kwargs)
self.about_file_path = kwargs.get('about_file_path')
flag = self.get_flag(self.original_value)
if flag is False:
name = self.name
val = self.original_value
about_file_path = self.about_file_path
flag_values = self.flag_values
msg = (u'Path: %(about_file_path)s - Field %(name)s: Invalid flag value: %(val)r is not '
u'one of: %(flag_values)s' % locals())
errors.append(Error(ERROR, msg))
self.value = None
elif flag is None:
name = self.name
msg = (u'Field %(name)s: field is present but empty. ' % locals())
errors.append(Error(INFO, msg))
self.value = None
else:
if flag == u'yes' or flag is True:
self.value = True
else:
self.value = False
return errors
def get_flag(self, value):
"""
Return a normalized existing flag value if found in the list of
possible values or None if empty or False if not found or original value
if it is not a boolean value
"""
if value is None or value == '':
return None
if isinstance(value, bool):
return value
else:
if isinstance(value, str):
value = value.strip()
if not value:
return None
value = value.lower()
if value in self.flag_values:
if value in self.true_flags:
return u'yes'
else:
return u'no'
else:
return False
else:
return False
@property
def has_content(self):
"""
Return true if it has content regardless of what value, False otherwise
"""
if self.original_value:
return True
return False
def _serialized_value(self):
# default normalized values for serialization
if self.value:
return u'yes'
elif self.value is False:
return u'no'
else:
# self.value is None
# TODO: should we serialize to No for None???
return u''
def __eq__(self, other):
"""
Boolean equality
"""
return (isinstance(other, self.__class__)
and self.name == other.name
and self.value == other.value)
def validate_fields(fields, about_file_path, running_inventory, base_dir,
reference_dir=None):
"""
Validate a sequence of Field objects. Return a list of errors.
Validation may update the Field objects as needed as a side effect.
"""
errors = []
for f in fields:
val_err = f.validate(
base_dir=base_dir,
about_file_path=about_file_path,
running_inventory=running_inventory,
reference_dir=reference_dir,
)
errors.extend(val_err)
return errors
def validate_field_name(name):
if not is_valid_name(name):
msg = ('Field name: %(name)r contains illegal name characters '
'(or empty spaces) and is ignored.')
return Error(WARNING, msg % locals())
class License:
"""
Represent a License object
"""
def __init__(self, key, name, filename, url, text):
self.key = key
self.name = name
self.filename = filename
self.url = url
self.text = text
class About(object):
"""
Represent an ABOUT file and functions to parse and validate a file.
"""
# special names, used only when serializing lists of ABOUT files to CSV or
# similar
# name of the attribute containing the relative ABOUT file path
ABOUT_FILE_PATH_ATTR = 'about_file_path'
# name of the attribute containing the resolved relative Resources paths
about_resource_path_attr = 'about_resource_path'
# name of the attribute containing the resolved relative Resources paths
ABOUT_RESOURCE_ATTR = 'about_resource'
# Required fields
required_fields = ['name', ABOUT_RESOURCE_ATTR]
def get_required_fields(self):
return [f for f in self.fields if f.required]
def set_standard_fields(self):
"""
Create fields in an ordered dict to keep a standard ordering. We
could use a metaclass to track ordering django-like but this approach
is simpler.
"""
self.fields = dict([
('about_resource', AboutResourceField(required=True)),
('ignored_resources', AboutResourceField()),
('deployed_resource', AboutResourceField()),
('name', SingleLineField(required=True)),
('version', SingleLineField()),
('download_url', UrlField()),
('description', StringField()),
('homepage_url', UrlField()),
('package_url', PackageUrlField()),
('notes', StringField()),
('license_expression', StringField()),
('license_key', ListField()),
('license_name', ListField()),
('license_file', FileTextField()),
('license_url', UrlListField()),
('spdx_license_expression', StringField()),
('spdx_license_key', ListField()),
('copyright', StringField()),
('notice_file', FileTextField()),
('notice_url', UrlField()),
('redistribute', BooleanField()),
('attribute', BooleanField()),
('track_changes', BooleanField()),
('modified', BooleanField()),
('internal_use_only', BooleanField()),
('is_curation', BooleanField()),
('changelog_file', FileTextField()),
('owner', StringField()),
('owner_url', UrlField()),
('contact', StringField()),
('author', StringField()),
('author_file', FileTextField()),
('vcs_tool', SingleLineField()),
('vcs_repository', SingleLineField()),
('vcs_path', SingleLineField()),
('vcs_tag', SingleLineField()),
('vcs_branch', SingleLineField()),
('vcs_revision', SingleLineField()),
('checksum_md5', SingleLineField()),
('checksum_sha1', SingleLineField()),
('checksum_sha256', SingleLineField()),
('spec_version', SingleLineField()),
])
for name, field in self.fields.items():
# we could have a hack to get the actual field name
# but setting an attribute is explicit and cleaner
field.name = name
setattr(self, name, field)
def __init__(self, location=None, about_file_path=None, strict=False):
"""
Create an instance.
If strict is True, raise an Exception on errors. Otherwise the errors
attribute contains the errors.
"""
self.set_standard_fields()
self.custom_fields = {}
self.errors = []
# about file path relative to the root of an inventory using posix
# path separators
self.about_file_path = about_file_path
# os native absolute location, using posix path separators
self.location = location
self.base_dir = None
if self.location:
self.base_dir = os.path.dirname(location)
self.errors.extend(self.load(location))
if strict and self.errors and filter_errors(self.errors):
msg = '\n'.join(map(str, self.errors))
raise Exception(msg)
def __repr__(self):
return repr(self.all_fields())
def __eq__(self, other):
"""
Equality based on fields and custom_fields., i.e. content.
"""
return (isinstance(other, self.__class__)
and self.fields == other.fields
and self.custom_fields == other.custom_fields)
def all_fields(self):
"""
Return the list of all Field objects.
"""
return list(self.fields.values()) + list(self.custom_fields.values())
def as_dict(self):
"""
Return all the standard fields and customer-defined fields of this
About object in an ordered dict.
"""
data = {}
data[self.ABOUT_FILE_PATH_ATTR] = self.about_file_path
with_values = ((fld.name, fld.serialized_value())
for fld in self.all_fields())
non_empty = ((name, value) for name, value in with_values if value)
data.update(non_empty)
return data
def hydrate(self, fields):
"""
Process an iterable of field (name, value) tuples. Update or create
Fields attributes and the fields and custom fields dictionaries.
Return a list of errors.
"""
errors = []
seen_fields = {}
illegal_name_list = []
for name, value in fields:
orig_name = name
name = name.lower()
# Some special attributes
if name == self.ABOUT_FILE_PATH_ATTR:
# this is a special attribute set directly on object
setattr(self, name, value)
continue
if name == self.about_resource_path_attr:
# this is a special attribute, skip entirely
continue
# A field that has been already processed ... and has a value
previous_value = seen_fields.get(name)
if previous_value:
if value != previous_value:
msg = (u'Field %(orig_name)s is a duplicate. '
u'Original value: "%(previous_value)s" '
u'replaced with: "%(value)s"')
errors.append(Error(WARNING, msg % locals()))
continue
seen_fields[name] = value
# A standard field (could be essential/required or not)
standard_field = self.fields.get(name)
if standard_field:
standard_field.original_value = value
standard_field.value = value
standard_field.present = True
continue
# A custom field
# is the name valid?
if not is_valid_name(name):
if not name in illegal_name_list:
illegal_name_list.append(name)
continue
msg = 'Custom Field: %(orig_name)s'
errors.append(Error(INFO, msg % locals()))
# is this a known one?
custom_field = self.custom_fields.get(name)
if custom_field:
# An known custom field
custom_field.original_value = value
custom_field.value = value
custom_field.present = True
else:
# A new, unknown custom field
custom_field = Field(name=name, value=value, present=True)
self.custom_fields[name] = custom_field
# FIXME: why would this ever fail???
try:
if name in dir(self):
raise Exception(
'Illegal field: %(name)r: %(value)r.' % locals())
setattr(self, name, custom_field)
except:
msg = 'Internal error with custom field: %(name)r: %(value)r.'
errors.append(Error(CRITICAL, msg % locals()))
if illegal_name_list:
msg = ('Field name: %(illegal_name_list)r contains illegal name characters '
'(or empty spaces) and is ignored.')
errors.append(Error(WARNING, msg % locals()))
return errors
def process(self, fields, about_file_path, running_inventory=False,
base_dir=None, scancode=False, from_attrib=False, reference_dir=None):
"""
Validate and set as attributes on this About object a sequence of
`fields` name/value tuples. Return a list of errors.
"""
self.base_dir = base_dir
self.reference_dir = reference_dir
afp = self.about_file_path
errors = self.hydrate(fields)
# We want to copy the license_files before the validation
if reference_dir and not from_attrib:
copy_err = copy_license_notice_files(
fields, base_dir, reference_dir, afp)
errors.extend(copy_err)
# TODO: why? we validate all fields, not only these hydrated
# The validate functions does not allow duplicated entry for a list meaning
# it will cause problem when using scancode license detection as an input as
# it usually returns duplicated license_key and many license have duplicated
# score such as 100. We need to handle this scenario using different method.
if not scancode:
validation_errors = validate_fields(
self.all_fields(),
about_file_path,
running_inventory,
self.base_dir,
self.reference_dir)
errors.extend(validation_errors)
return errors