-
Notifications
You must be signed in to change notification settings - Fork 27
/
models.py
314 lines (259 loc) · 9.82 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
#
# Copyright (c) 2017-2018 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/deltacode/
# The DeltaCode software is licensed under the Apache License version 2.0.
# Data generated with DeltaCode require an acknowledgment.
# DeltaCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# When you publish or redistribute any data created with DeltaCode or any DeltaCode
# derivative work, you must accompany this data with the following acknowledgment:
#
# Generated with DeltaCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# DeltaCode should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
# DeltaCode is a free and open source software analysis tool from nexB Inc. and others.
# Visit https://github.com/nexB/deltacode/ for support and download.
#
from __future__ import absolute_import
from collections import OrderedDict
import json
class Scan(object):
"""
Process the files contained in an incoming ScanCode scan to test whether
they are valid, retrieve the scan's 'files_count' value, create a list of
File objects, and generate a dictionary of File objects indexed by a
selected key.
"""
def __init__(self, path=''):
if path is None:
path = ''
self.errors = []
if not self.is_valid_scan(path):
self.path = ''
self.files_count = 0
self.files = []
self.options = {}
else:
self.path = path
self.files_count = self.get_files_count(path)
self.files = self.load_files(path)
self.options = self.get_options(path)
def get_options(self, path):
"""
Collect the ScanCode options contained in the incoming ScanCode file.
"""
# TODO: handle this exception during #171
try:
scan = json.loads(open(path).read())
except IOError:
return
scan = json.loads(open(path).read())
options = scan.get('scancode_options')
if not options:
# Handle new(er) scancode options
headers = scan.get('headers')
if headers:
options = headers[0].get('options')
return options
def is_valid_scan(self, location):
"""
In conjunction with test_deltacode.py, test the incoming files to
ensure that they are well-formed JSON and otherwise satisfy the
requirements to be run in DeltaCode (e.g., ScanCode version, proper
ScanCode options etc.).
"""
try:
scan = json.loads(open(location).read())
except IOError:
return
scan = json.loads(open(location).read())
version = scan.get('scancode_version')
if not version:
# handle new(er) scancode version location
headers = scan.get('headers')
if headers:
version = headers[0].get('tool_version')
options = scan.get('scancode_options')
if not options:
headers = scan.get('headers')
if headers:
options = headers[0].get('options')
if not version:
raise ScanException('JSON file: {} is missing the ScanCode version.'.format(location))
if int(version.split('.').pop(0)) < 2:
raise ScanException('JSON file: {} was created with an old version of ScanCode.'.format(location))
if not options.get('--info'):
raise ScanException('JSON file: {} is missing the ScanCode --info attribute.'.format(location))
return True
def get_files_count(self, path):
"""
Retrieve a scan's 'files_count' value.
"""
if not self.is_valid_scan(path):
# TODO: raise some error
return
with open(path) as jsonf:
scan = jsonf.read()
scan = json.loads(scan)
files_count = scan.get('files_count')
if not files_count:
headers = scan.get('headers')
if headers:
files_count = headers[0].get('extra_data', {}).get('files_count')
return files_count
def load_files(self, path):
"""
Return a list of File objects from a scanfile at 'path',
json format.
"""
if not self.is_valid_scan(path):
# TODO: raise some error
return
with open(path) as jsonf:
scan = jsonf.read()
return [File(f) for f in json.loads(scan).get('files')]
def index_files(self, index_key='path'):
"""
Return a dictionary of a list of File objects indexed by the key passed via
the 'key' variable. If no 'key' variable is passed, the dict is
keyed by the File object's 'path' variable. This function does not
currently catch the AttributeError exception.
"""
index = OrderedDict()
for f in self.files:
key = getattr(f, index_key)
if index.get(key) is None:
index[key] = []
index[key].append(f)
else:
index[key].append(f)
return index
class File(object):
"""
File object created from an ABCD formatted 'file' dictionary.
"""
def __init__(self, dictionary={}):
self.path = dictionary.get('path', '')
self.type = dictionary.get('type', '')
self.name = dictionary.get('name', '')
self.size = dictionary.get('size', '')
self.sha1 = dictionary.get('sha1', '')
self.fingerprint = dictionary.get('fingerprint', '')
self.original_path = ''
self.licenses = self.get_licenses(dictionary) if dictionary.get('licenses') else []
self.copyrights = self.get_copyrights(dictionary) if dictionary.get('copyrights') else []
def get_licenses(self, dictionary):
if dictionary.get('licenses') == []:
return []
else:
return [License(l) for l in dictionary.get('licenses')]
def has_licenses(self):
if len(self.licenses) > 0:
return True
def get_copyrights(self, dictionary):
if dictionary.get('copyrights') == []:
return []
else:
return [Copyright(l) for l in dictionary.get('copyrights')]
def has_copyrights(self):
if len(self.copyrights) > 0:
return True
def to_dict(self):
d = OrderedDict([
('path', self.path),
('type', self.type),
('name', self.name),
('size', self.size),
('sha1', self.sha1),
('fingerprint', self.fingerprint),
('original_path', self.original_path),
])
if self.licenses:
d['licenses'] = [l.to_dict() for l in self.licenses]
else:
d['licenses'] = []
if self.copyrights:
d['copyrights'] = [l.to_dict() for l in self.copyrights]
else:
d['copyrights'] = []
return d
def size_difference(self, other_file):
"""
Return the difference between the size of the instant File object and
a second File object to which it is being compared.
"""
return self.size - other_file.size
def __repr__(self):
"""
Return string containing a printable representation of the File object.
"""
return "%s" % self.__dict__
class License(object):
"""
License object created from the 'license' field in an ABCD formatted 'file'
dictionary.
"""
def __init__(self, dictionary={}):
self.key = dictionary.get('key')
self.score = dictionary.get('score')
self.short_name = dictionary.get('short_name')
self.category = dictionary.get('category')
self.owner = dictionary.get('owner')
def to_dict(self):
"""
Given a License object, return an OrderedDict with the full
set of fields from the ScanCode 'license' value.
"""
d = OrderedDict([
('key', self.key),
('score', self.score),
('short_name', self.short_name),
('category', self.category),
('owner', self.owner)
])
return d
def __repr__(self):
"""
Return string containing a printable representation of the License
object.
"""
return "%s" % self.__dict__
class Copyright(object):
"""
Copyright object created from the 'copyrights' field in an ABCD formatted
'file' dictionary.
"""
def __init__(self, dictionary={}):
self.statements = dictionary.get('statements')
self.holders = dictionary.get('holders')
def to_dict(self):
"""
Given a Copyright object, return an OrderedDict with the full
set of fields from the ScanCode 'copyrights' value.
"""
d = OrderedDict([
('statements', self.statements),
('holders', self.holders)
])
return d
def __repr__(self):
"""
Return string containing a printable representation of the Copyright
object.
"""
return "%s" % self.__dict__
class ScanException(Exception):
"""
Named exception for JSON file (1) containing no 'scancode_version'
attribute, (2) containing old version of ScanCode, or (3) containing no
'scancode_options'/'--info' attribute.
"""
pass