fosslight-util 2.2.16__tar.gz → 2.2.18__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {fosslight_util-2.2.16/src/fosslight_util.egg-info → fosslight_util-2.2.18}/PKG-INFO +2 -2
  2. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/pyproject.toml +2 -2
  3. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/oss_item.py +1 -0
  4. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/output_format.py +2 -6
  5. fosslight_util-2.2.18/src/fosslight_util/write_spdx.py +447 -0
  6. {fosslight_util-2.2.16 → fosslight_util-2.2.18/src/fosslight_util.egg-info}/PKG-INFO +2 -2
  7. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util.egg-info/SOURCES.txt +1 -0
  8. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util.egg-info/requires.txt +1 -3
  9. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_cyclonedx.py +34 -5
  10. fosslight_util-2.2.18/tests/test_spdx.py +798 -0
  11. fosslight_util-2.2.16/src/fosslight_util/write_spdx.py +0 -274
  12. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/LICENSE +0 -0
  13. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/MANIFEST.in +0 -0
  14. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/README.md +0 -0
  15. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/setup.cfg +0 -0
  16. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/__init__.py +0 -0
  17. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/_get_downloadable_url.py +0 -0
  18. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/compare_yaml.py +0 -0
  19. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/constant.py +0 -0
  20. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/correct.py +0 -0
  21. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/cover.py +0 -0
  22. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/download.py +0 -0
  23. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/exclude.py +0 -0
  24. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/get_pom_license.py +0 -0
  25. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/help.py +0 -0
  26. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/parsing_yaml.py +0 -0
  27. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/read_excel.py +0 -0
  28. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/resources/frequentLicenselist.json +0 -0
  29. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/resources/frequent_license_nick_list.json +0 -0
  30. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/resources/licenses.json +0 -0
  31. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/set_log.py +1 -1
  32. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/spdx_licenses.py +0 -0
  33. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/time.py +0 -0
  34. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/timer_thread.py +0 -0
  35. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/write_cyclonedx.py +0 -0
  36. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/write_excel.py +0 -0
  37. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/write_opossum.py +0 -0
  38. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/write_scancodejson.py +0 -0
  39. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/write_txt.py +0 -0
  40. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util/write_yaml.py +0 -0
  41. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util.egg-info/dependency_links.txt +0 -0
  42. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util.egg-info/entry_points.txt +0 -0
  43. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/src/fosslight_util.egg-info/top_level.txt +0 -0
  44. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_decide_checkout.py +0 -0
  45. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_download.py +0 -0
  46. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_download_maven.py +0 -0
  47. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_download_packagist.py +0 -0
  48. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_download_timeout.py +0 -0
  49. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_download_version_hint.py +0 -0
  50. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_opossum.py +0 -0
  51. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_spdx_licenses.py +0 -0
  52. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_text.py +0 -0
  53. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_write_excel_hidden_sheet.py +0 -0
  54. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_write_output.py +0 -0
  55. {fosslight_util-2.2.16 → fosslight_util-2.2.18}/tests/test_write_yaml.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fosslight_util
3
- Version: 2.2.16
3
+ Version: 2.2.18
4
4
  Summary: FOSSLight Util
5
5
  Author: LG Electronics
6
6
  License-Expression: Apache-2.0
@@ -24,7 +24,7 @@ Requires-Dist: lastversion
24
24
  Requires-Dist: coloredlogs
25
25
  Requires-Dist: beautifulsoup4
26
26
  Requires-Dist: jsonmerge
27
- Requires-Dist: spdx-tools==0.8.2; sys_platform == "linux"
27
+ Requires-Dist: spdx-tools==0.8.2
28
28
  Requires-Dist: setuptools>=65.5.1
29
29
  Requires-Dist: numpy
30
30
  Requires-Dist: requests
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "fosslight_util"
10
- version = "2.2.16"
10
+ version = "2.2.18"
11
11
  description = "FOSSLight Util"
12
12
  readme = "README.md"
13
13
  license = "Apache-2.0"
@@ -31,7 +31,7 @@ dependencies = [
31
31
  "coloredlogs",
32
32
  "beautifulsoup4",
33
33
  "jsonmerge",
34
- "spdx-tools==0.8.2; sys_platform == 'linux'",
34
+ "spdx-tools==0.8.2",
35
35
  "setuptools>=65.5.1",
36
36
  "numpy",
37
37
  "requests",
@@ -23,6 +23,7 @@ class OssItem:
23
23
  self.version = version
24
24
  self._license = []
25
25
  self.license = license
26
+ self.license_texts: Dict[str, str] = {}
26
27
  self.download_location = dl_url
27
28
  self.exclude = False
28
29
  self.comment = ""
@@ -3,7 +3,6 @@
3
3
  # Copyright (c) 2021 LG Electronics Inc.
4
4
  # SPDX-License-Identifier: Apache-2.0
5
5
  import os
6
- import platform
7
6
  from fosslight_util.write_excel import write_result_to_excel, write_result_to_csv
8
7
  from fosslight_util.write_opossum import write_opossum
9
8
  from fosslight_util.write_yaml import write_yaml
@@ -189,11 +188,8 @@ def write_output_file(output_file_without_ext: str, file_extension: str, scan_it
189
188
  elif format == 'yaml':
190
189
  success, msg, _ = write_yaml(result_file, scan_item, False)
191
190
  elif format.startswith('spdx'):
192
- if platform.system() == 'Windows' or platform.system() == 'Darwin':
193
- success = False
194
- msg = f'{platform.system()} not support spdx format.'
195
- else:
196
- success, msg, _ = write_spdx(output_file_without_ext, file_extension, scan_item, spdx_version)
191
+ success, msg, _ = write_spdx(output_file_without_ext, file_extension, scan_item, spdx_version,
192
+ scanner_covers=scanner_covers)
197
193
  elif format.startswith('cyclonedx'):
198
194
  success, msg, result_file = write_cyclonedx(
199
195
  output_file_without_ext,
@@ -0,0 +1,447 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ # Copyright (c) 2022 LG Electronics Inc.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import ntpath
10
+ import os
11
+ import re
12
+ import uuid
13
+ from collections import defaultdict
14
+ from importlib.metadata import PackageNotFoundError, version as package_version
15
+ from pathlib import Path
16
+ from datetime import datetime, timezone
17
+ from fosslight_util.spdx_licenses import get_spdx_licenses_json, get_license_from_nick
18
+ from fosslight_util.constant import (LOGGER_NAME, FOSSLIGHT_DEPENDENCY, FOSSLIGHT_SCANNER,
19
+ FOSSLIGHT_BINARY, FOSSLIGHT_SOURCE, FOSSLIGHT_OCI, FOSSLIGHT_OCI_BINARY)
20
+ from fosslight_util.oss_item import get_checksum_sha1
21
+
22
+ logger = logging.getLogger(LOGGER_NAME)
23
+ _spdx_import_error = None
24
+
25
+ try:
26
+ from packageurl import PackageURL
27
+ from spdx_tools.common.spdx_licensing import spdx_licensing
28
+ from spdx_tools.spdx.jsonschema.document_converter import DocumentConverter
29
+ from spdx_tools.spdx.jsonschema.external_package_ref_converter import ExternalPackageRefConverter
30
+ from spdx_tools.spdx.model import (
31
+ Actor,
32
+ ActorType,
33
+ Checksum,
34
+ ChecksumAlgorithm,
35
+ CreationInfo,
36
+ Document,
37
+ ExternalPackageRef,
38
+ ExternalPackageRefCategory,
39
+ ExtractedLicensingInfo,
40
+ File,
41
+ FileType,
42
+ Package,
43
+ Relationship,
44
+ RelationshipType,
45
+ SpdxNoAssertion,
46
+ SpdxNone
47
+ )
48
+ from spdx_tools.spdx.validation.document_validator import validate_full_spdx_document
49
+ from spdx_tools.spdx.validation.uri_validators import validate_download_location, validate_url
50
+ from spdx_tools.spdx.writer.json import json_writer
51
+ from spdx_tools.spdx.writer.write_anything import write_file
52
+ from spdx_tools.spdx.writer.xml import xml_writer
53
+ from spdx_tools.spdx.writer.yaml import yaml_writer
54
+ except Exception as error:
55
+ _spdx_import_error = error
56
+ logger.info('No import spdx-tools')
57
+
58
+
59
+ def get_license_list_version():
60
+ version = 'N/A'
61
+ success, error_msg, licenses = get_spdx_licenses_json()
62
+ if success:
63
+ version = licenses['licenseListVersion']
64
+ else:
65
+ logger.info(f'Fail to get spdx license list version:{error_msg}')
66
+ return version
67
+
68
+
69
+ def write_spdx(output_file_without_ext, output_extension, scan_item, spdx_version='2.3', scanner_covers=None):
70
+ if _spdx_import_error is not None:
71
+ return False, f'Failed to import spdx-tools: {_spdx_import_error}', ''
72
+ if not scan_item:
73
+ return False, 'No item to write in output file.', ''
74
+ result_file = ''
75
+ try:
76
+ document = Document(creation_info=_creation_info(scan_item, scanner_covers))
77
+ root = Package(
78
+ name=document.creation_info.name, spdx_id=_ROOT_PACKAGE_ID,
79
+ download_location=SpdxNoAssertion(), files_analyzed=False
80
+ )
81
+ document.packages.append(root)
82
+ seen_relationships = set()
83
+ _add_relationship(document, seen_relationships, 'SPDXRef-DOCUMENT', RelationshipType.DESCRIBES, root.spdx_id)
84
+ package_ids_by_purl = defaultdict(list)
85
+ dependency_rows = []
86
+ root_purls = set()
87
+ checksums = {}
88
+ registry = _LicenseRegistry()
89
+ for scanner_name, file_items in scan_item.file_items.items():
90
+ scanner_type = {
91
+ FOSSLIGHT_OCI: FOSSLIGHT_DEPENDENCY,
92
+ FOSSLIGHT_OCI_BINARY: FOSSLIGHT_BINARY,
93
+ }.get(scanner_name, scanner_name)
94
+ if scanner_type not in (FOSSLIGHT_DEPENDENCY, FOSSLIGHT_SOURCE, FOSSLIGHT_BINARY):
95
+ continue
96
+ is_dependency = scanner_type == FOSSLIGHT_DEPENDENCY
97
+ for file_item in file_items:
98
+ if file_item.exclude:
99
+ continue
100
+ oss_items = [oss_item for oss_item in file_item.oss_items if not oss_item.exclude]
101
+ if file_item.oss_items and not oss_items:
102
+ continue
103
+ file_info = None if is_dependency else _file_info(
104
+ file_item, scan_item.cover.input_path, scanner_type, f'SPDXRef-File{len(document.files) + 1}', checksums
105
+ )
106
+ if file_info:
107
+ for oss_item in oss_items:
108
+ file_info.license_info_in_file.extend(
109
+ registry.licenses(oss_item.license, getattr(oss_item, 'license_texts', None))
110
+ )
111
+ file_info.license_info_in_file = _unique_licenses(file_info.license_info_in_file)
112
+ copyright_lines = {
113
+ line for oss_item in oss_items if oss_item.copyright != '-'
114
+ for line in oss_item.copyright.splitlines() if line
115
+ }
116
+ file_info.copyright_text = '\n'.join(sorted(copyright_lines)) or None
117
+ document.files.append(file_info)
118
+ _add_relationship(document, seen_relationships, 'SPDXRef-DOCUMENT', RelationshipType.DESCRIBES,
119
+ file_info.spdx_id)
120
+ for oss_item in oss_items:
121
+ classification = oss_item.comment
122
+ purl = _normalized_purl(getattr(file_item, 'purl', '')) if is_dependency else ''
123
+ if is_dependency and re.search(r'\broot package\b', classification, re.IGNORECASE):
124
+ package = root
125
+ else:
126
+ name = '' if oss_item.name == '-' else oss_item.name
127
+ raw_download_location = '' if oss_item.download_location in ('-', None) else oss_item.download_location
128
+ version = '' if oss_item.version == '-' else oss_item.version
129
+ copyright_text = '' if oss_item.copyright == '-' else oss_item.copyright
130
+ if not is_dependency and not name and not raw_download_location:
131
+ continue
132
+ package = Package(
133
+ name=name or 'NOASSERTION', spdx_id=f'SPDXRef-Package{len(document.packages)}',
134
+ download_location=_spdx_download_location(oss_item.download_location),
135
+ version=version or None, homepage=_spdx_homepage(oss_item.homepage),
136
+ copyright_text=copyright_text or None,
137
+ files_analyzed=not is_dependency
138
+ )
139
+ if is_dependency:
140
+ licenses = registry.licenses(oss_item.license, getattr(oss_item, 'license_texts', None))
141
+ licenses = [
142
+ value for value in licenses if not isinstance(value, (SpdxNone, SpdxNoAssertion))
143
+ ] or licenses
144
+ package.license_declared = (
145
+ spdx_licensing.parse(' AND '.join(f'({value})' for value in licenses)) if len(licenses) > 1
146
+ else licenses[0] if licenses else SpdxNone()
147
+ )
148
+ document.packages.append(package)
149
+ _add_relationship(document, seen_relationships, 'SPDXRef-DOCUMENT', RelationshipType.DESCRIBES,
150
+ package.spdx_id)
151
+ if file_info:
152
+ _add_relationship(document, seen_relationships, package.spdx_id, RelationshipType.CONTAINS,
153
+ file_info.spdx_id)
154
+ if is_dependency:
155
+ if purl:
156
+ if package.spdx_id not in package_ids_by_purl[purl]:
157
+ package_ids_by_purl[purl].append(package.spdx_id)
158
+ if package is not root or purl not in root_purls:
159
+ package.external_references.append(ExternalPackageRef(
160
+ ExternalPackageRefCategory.PACKAGE_MANAGER, 'purl', purl
161
+ ))
162
+ if package is root:
163
+ root_purls.add(purl)
164
+ depends_on = getattr(file_item, 'depends_on', []) or []
165
+ dependency_rows.append((package.spdx_id, [depends_on] if isinstance(depends_on, str) else depends_on))
166
+ if package is not root and re.search(r'\bdirect\b', classification, re.IGNORECASE):
167
+ _add_relationship(document, seen_relationships, root.spdx_id, RelationshipType.DEPENDS_ON,
168
+ package.spdx_id)
169
+ for source, dependencies in dependency_rows:
170
+ for dependency in dependencies:
171
+ for target in package_ids_by_purl.get(_normalized_purl(dependency), []):
172
+ _add_relationship(document, seen_relationships, source, RelationshipType.DEPENDS_ON, target)
173
+ registry.finalize(document)
174
+ _populate_package_licenses(document)
175
+ messages = validate_full_spdx_document(document)
176
+ if messages:
177
+ return False, 'Failed to validate SPDX document: ' + '; '.join(
178
+ message.validation_message for message in messages
179
+ ), ''
180
+ result_file = str(output_file_without_ext) + output_extension
181
+ Path(result_file).parent.mkdir(parents=True, exist_ok=True)
182
+ if output_extension == '.tag':
183
+ write_file(document, result_file, validate=False)
184
+ else:
185
+ class _ExternalRefConverter(ExternalPackageRefConverter):
186
+ def convert(self, external_ref, document=None):
187
+ converted = super().convert(external_ref, document)
188
+ converted['referenceCategory'] = converted['referenceCategory'].replace('_', '-')
189
+ return converted
190
+
191
+ converter = DocumentConverter()
192
+ converter.package_converter.external_package_ref_converter = _ExternalRefConverter()
193
+ writer = {'.json': json_writer, '.yaml': yaml_writer, '.xml': xml_writer}[output_extension]
194
+ writer.write_document_to_file(document, result_file, validate=False, converter=converter, drop_duplicates=False)
195
+ return True, '', result_file
196
+ except Exception as error:
197
+ logger.debug('Failed to create or write SPDX document', exc_info=True)
198
+ if result_file and os.path.isfile(result_file):
199
+ os.remove(result_file)
200
+ return False, f'Failed to create or write SPDX document: {error}', result_file
201
+
202
+
203
+ _SCANNER_TOOL_NAMES = {
204
+ FOSSLIGHT_SCANNER: 'FOSSLIGHT_SCANNER',
205
+ FOSSLIGHT_DEPENDENCY: 'FOSSLIGHT_Dependency',
206
+ FOSSLIGHT_SOURCE: 'FOSSLIGHT_Source',
207
+ FOSSLIGHT_BINARY: 'FOSSLIGHT_Binary',
208
+ FOSSLIGHT_OCI: 'FOSSLIGHT_OCI',
209
+ FOSSLIGHT_OCI_BINARY: 'FOSSLIGHT_OCI_Binary',
210
+ }
211
+ _TOOL_PATTERN = re.compile(r'^([A-Za-z0-9_-]+)\s+v([^\s(]+)')
212
+ _SHA1_PATTERN = re.compile(r'^[0-9a-fA-F]{40}$')
213
+ _TLSH_PATTERN = re.compile(r'^(?:T1)?[0-9a-f]{70}$', re.IGNORECASE)
214
+ _ROOT_PACKAGE_ID = 'SPDXRef-ROOT-PACKAGE'
215
+
216
+
217
+ def _tool(cover):
218
+ tool_name = getattr(cover, 'tool_name', '')
219
+ if not tool_name and hasattr(cover, 'get_print_json'):
220
+ tool_name = cover.get_print_json().get('Tool information', '')
221
+ return _TOOL_PATTERN.match(tool_name.strip())
222
+
223
+
224
+ def _unique_licenses(licenses):
225
+ return list({str(license_value): license_value for license_value in sorted(licenses, key=str)}.values())
226
+
227
+
228
+ class _LicenseRegistry:
229
+ def __init__(self):
230
+ self.aliases = get_license_from_nick() or {}
231
+ self.parsed = {}
232
+ self.references = {}
233
+
234
+ def _reference(self, name, texts):
235
+ text = texts.get(name, '') or ''
236
+ identity = (name, text)
237
+ if identity not in self.references:
238
+ self.references[identity] = spdx_licensing.parse(f'LicenseRef-FOSSLight-Internal{len(self.references) + 1}')
239
+ return self.references[identity]
240
+
241
+ def licenses(self, values, texts=None):
242
+ texts = texts or {}
243
+ result = []
244
+ for value in [values] if isinstance(values, str) else values:
245
+ if not value or value == '-':
246
+ continue
247
+ if value in ('NONE', 'NOASSERTION'):
248
+ result.append(SpdxNone() if value == 'NONE' else SpdxNoAssertion())
249
+ continue
250
+ canonical = self.aliases.get(value.casefold(), value)
251
+ try:
252
+ if canonical not in self.parsed:
253
+ self.parsed[canonical] = spdx_licensing.parse(canonical)
254
+ expression = self.parsed[canonical]
255
+ except Exception:
256
+ result.append(self._reference(value, texts))
257
+ continue
258
+ replacements = {}
259
+ for symbol in spdx_licensing.license_symbols(expression, unique=True, decompose=True):
260
+ if symbol.key not in spdx_licensing.known_symbols:
261
+ alias = self.aliases.get(symbol.key.casefold())
262
+ replacements[symbol] = spdx_licensing.parse(alias) if alias else self._reference(symbol.key, texts)
263
+ result.append(expression.subs(replacements) if replacements else expression)
264
+ return _unique_licenses(result)
265
+
266
+ def finalize(self, document):
267
+ groups = defaultdict(list)
268
+ for identity, expression in self.references.items():
269
+ name = re.sub(r'[\s_(]+', '-', identity[0].removeprefix('LicenseRef-'))
270
+ identifier = re.sub(r'[^A-Za-z0-9.\-]', '', convert_to_spdx_style(name))
271
+ groups[identifier].append((identity, expression))
272
+ used_ids = {base for base, entries in groups.items() if base != 'LicenseRef-' and len(entries) == 1}
273
+ replacements = {}
274
+ definitions = []
275
+ for base, entries in sorted(groups.items()):
276
+ for (name, text), expression in sorted(entries, key=lambda entry: entry[0]):
277
+ identifier = base
278
+ if base == 'LicenseRef-' or len(entries) > 1:
279
+ digest = hashlib.sha256(json.dumps([name, text], ensure_ascii=False).encode('utf-8')).hexdigest()
280
+ for length in range(8, 65, 4):
281
+ identifier = f"{base}{'' if base == 'LicenseRef-' else '-'}{digest[:length]}"
282
+ if identifier not in used_ids:
283
+ break
284
+ else:
285
+ raise ValueError('Could not assign a unique LicenseRef identifier')
286
+ used_ids.add(identifier)
287
+ replacements[expression] = spdx_licensing.parse(identifier)
288
+ definitions.append(ExtractedLicensingInfo(
289
+ license_id=identifier, extracted_text=text or name, license_name=name
290
+ ))
291
+ for file_info in document.files:
292
+ file_info.license_info_in_file = [
293
+ value.subs(replacements) if hasattr(value, 'subs') else value
294
+ for value in file_info.license_info_in_file
295
+ ]
296
+ for package in document.packages:
297
+ if hasattr(package.license_declared, 'subs'):
298
+ package.license_declared = package.license_declared.subs(replacements)
299
+ document.extracted_licensing_info = sorted(definitions, key=lambda definition: definition.license_id)
300
+
301
+
302
+ def _creation_info(scan_item, scanner_covers):
303
+ input_path = scan_item.cover.input_path
304
+ path_module = ntpath if ntpath.splitdrive(input_path)[0] else os.path
305
+ document_name = path_module.basename(path_module.normpath(path_module.abspath(input_path))) or 'Root Component'
306
+ first_tool = _tool(scan_item.cover)
307
+ scanner_name = first_tool.group(1).lower() if first_tool else FOSSLIGHT_SCANNER
308
+ creators = []
309
+ seen = set()
310
+ for cover in [scan_item.cover] if scanner_covers is None else scanner_covers:
311
+ match = _tool(cover)
312
+ if not match:
313
+ continue
314
+ name = _SCANNER_TOOL_NAMES.get(match.group(1).lower())
315
+ identity = (name, match.group(2))
316
+ if name and identity not in seen:
317
+ creators.append(Actor(ActorType.TOOL, f'{name} - {match.group(2)}'))
318
+ seen.add(identity)
319
+ try:
320
+ spdx_tools_version = package_version('spdx-tools')
321
+ except PackageNotFoundError:
322
+ spdx_tools_version = 'unknown'
323
+ creators.append(Actor(ActorType.TOOL, f'spdx-tools - {spdx_tools_version}'))
324
+ return CreationInfo(
325
+ spdx_version='SPDX-2.3', spdx_id='SPDXRef-DOCUMENT', name=document_name, data_license='CC0-1.0',
326
+ document_namespace=f'http://opensource.lge.com/spdxdocs/{scanner_name}-{uuid.uuid4()}',
327
+ creators=creators, created=datetime.now(timezone.utc)
328
+ )
329
+
330
+
331
+ def _file_info(file_item, input_path, scanner_name, identifier, checksums):
332
+ name = file_item.source_name_or_path
333
+ if not name or name.endswith(('/', '\\')):
334
+ return None
335
+ path_module = ntpath if ntpath.splitdrive(input_path)[0] else os.path
336
+ name = name.replace('\\', '/')
337
+ full_path = path_module.normpath(name if path_module.isabs(name) else path_module.join(input_path, name))
338
+ try:
339
+ relative_path = path_module.relpath(full_path, input_path).replace('\\', '/')
340
+ except ValueError:
341
+ return None
342
+ if relative_path == '.' or os.path.isdir(full_path):
343
+ return None
344
+ checksum = file_item.checksum
345
+ if not _SHA1_PATTERN.fullmatch(checksum):
346
+ if full_path not in checksums:
347
+ checksums[full_path] = get_checksum_sha1(full_path)
348
+ checksum = checksums[full_path]
349
+ if not _SHA1_PATTERN.fullmatch(checksum):
350
+ logger.info(f'Failed to get SHA-1, skip File: {name}')
351
+ return None
352
+ tlsh = str(getattr(file_item, 'tlsh', '') or '').strip()
353
+ comment = f'fosslight:tlsh={tlsh}' if scanner_name == FOSSLIGHT_BINARY and _TLSH_PATTERN.fullmatch(tlsh) else None
354
+ return File(
355
+ name=f'./{relative_path}', spdx_id=identifier,
356
+ checksums=[Checksum(ChecksumAlgorithm.SHA1, checksum.lower())],
357
+ file_types=[FileType.BINARY if scanner_name == FOSSLIGHT_BINARY else FileType.SOURCE], comment=comment
358
+ )
359
+
360
+
361
+ def _spdx_download_location(value):
362
+ if value == '-' or value is None:
363
+ value = ''
364
+ if value in ('NONE', 'NOASSERTION', ''):
365
+ return SpdxNone() if value == 'NONE' else SpdxNoAssertion()
366
+ if validate_download_location(value):
367
+ return SpdxNoAssertion()
368
+ return value
369
+
370
+
371
+ def _spdx_homepage(value):
372
+ if value == '-' or not value or validate_url(value):
373
+ return None
374
+ return value
375
+
376
+
377
+ def _normalized_purl(value):
378
+ try:
379
+ return str(PackageURL.from_string(value))
380
+ except (TypeError, ValueError):
381
+ return ''
382
+
383
+
384
+ def _add_relationship(document, seen, source, relation_type, target):
385
+ identity = (source, relation_type, target)
386
+ if source != target and identity not in seen:
387
+ document.relationships.append(Relationship(source, relation_type, target))
388
+ seen.add(identity)
389
+
390
+
391
+ def _populate_package_licenses(document):
392
+ files = {file_info.spdx_id: file_info for file_info in document.files}
393
+ licenses = defaultdict(list)
394
+ for relationship in document.relationships:
395
+ if relationship.relationship_type == RelationshipType.CONTAINS and relationship.related_spdx_element_id in files:
396
+ licenses[relationship.spdx_element_id].extend(files[relationship.related_spdx_element_id].license_info_in_file)
397
+ for package in document.packages:
398
+ if package.files_analyzed:
399
+ package.license_info_from_files = _unique_licenses(licenses[package.spdx_id]) or [SpdxNone()]
400
+
401
+
402
+ def convert_to_spdx_style(input_string):
403
+ input_string = re.sub(r'[^\w\s\.\-]', '', input_string)
404
+ input_string = re.sub(r'[\s\_]', '-', input_string)
405
+ input_converted = f"LicenseRef-{input_string}"
406
+ return input_converted
407
+
408
+
409
+ def check_input_license_format(input_license):
410
+ spdx_licenses = get_spdx_licensename()
411
+ for spdx in spdx_licenses:
412
+ if input_license.casefold() == spdx.casefold():
413
+ return spdx
414
+
415
+ if input_license.startswith('LicenseRef-'):
416
+ return input_license
417
+
418
+ licensesfromJson = get_license_from_nick()
419
+ if licensesfromJson == "":
420
+ logger.warning(" Error - Return Value to get license from Json is none")
421
+
422
+ try:
423
+ converted_license = licensesfromJson.get(input_license.casefold())
424
+ if converted_license is None:
425
+ converted_license = convert_to_spdx_style(input_license)
426
+ except Exception as ex:
427
+ logger.warning(f"Error - Get frequetly used license : {ex}")
428
+
429
+ return converted_license
430
+
431
+
432
+ def get_spdx_licensename():
433
+ spdx_licenses = []
434
+ try:
435
+ success, error_msg, licenses = get_spdx_licenses_json()
436
+ if success is False:
437
+ logger.warning(f"Error to get SPDX Licesens : {error_msg}")
438
+
439
+ licenseInfo = licenses.get("licenses")
440
+ for info in licenseInfo:
441
+ shortID = info.get("licenseId")
442
+ isDeprecated = info.get("isDeprecatedLicenseId")
443
+ if isDeprecated is False:
444
+ spdx_licenses.append(shortID)
445
+ except Exception as ex:
446
+ logger.warning(f"Error access to get_spdx_licenses_json : {ex}")
447
+ return spdx_licenses
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fosslight_util
3
- Version: 2.2.16
3
+ Version: 2.2.18
4
4
  Summary: FOSSLight Util
5
5
  Author: LG Electronics
6
6
  License-Expression: Apache-2.0
@@ -24,7 +24,7 @@ Requires-Dist: lastversion
24
24
  Requires-Dist: coloredlogs
25
25
  Requires-Dist: beautifulsoup4
26
26
  Requires-Dist: jsonmerge
27
- Requires-Dist: spdx-tools==0.8.2; sys_platform == "linux"
27
+ Requires-Dist: spdx-tools==0.8.2
28
28
  Requires-Dist: setuptools>=65.5.1
29
29
  Requires-Dist: numpy
30
30
  Requires-Dist: requests
@@ -44,6 +44,7 @@ tests/test_download_packagist.py
44
44
  tests/test_download_timeout.py
45
45
  tests/test_download_version_hint.py
46
46
  tests/test_opossum.py
47
+ tests/test_spdx.py
47
48
  tests/test_spdx_licenses.py
48
49
  tests/test_text.py
49
50
  tests/test_write_excel_hidden_sheet.py
@@ -7,12 +7,10 @@ lastversion
7
7
  coloredlogs
8
8
  beautifulsoup4
9
9
  jsonmerge
10
+ spdx-tools==0.8.2
10
11
  setuptools>=65.5.1
11
12
  numpy
12
13
  requests
13
14
  GitPython<3.2,>=3.1.62
14
15
  cyclonedx-python-lib>=11.0.0
15
16
  defusedxml
16
-
17
- [:sys_platform == "linux"]
18
- spdx-tools==0.8.2
@@ -358,7 +358,7 @@ def test_cyclonedx_serialization_failure_is_reported(monkeypatch, scan_item):
358
358
 
359
359
  @pytest.mark.parametrize("system", ["Windows", "Darwin"])
360
360
  def test_cyclonedx_is_supported_on_all_platforms(monkeypatch, scan_item, system):
361
- monkeypatch.setattr("fosslight_util.output_format.platform.system", lambda: system)
361
+ monkeypatch.setattr("platform.system", lambda: system)
362
362
  output_file_without_ext = os.path.join(constants.TEST_RESULT_DIR, system, "cyclonedx")
363
363
 
364
364
  success, err_msg, result_file = write_output_file(
@@ -369,15 +369,44 @@ def test_cyclonedx_is_supported_on_all_platforms(monkeypatch, scan_item, system)
369
369
 
370
370
 
371
371
  @pytest.mark.parametrize("system", ["Windows", "Darwin"])
372
- def test_spdx_platform_restriction_is_unchanged(monkeypatch, scan_item, system):
373
- monkeypatch.setattr("fosslight_util.output_format.platform.system", lambda: system)
372
+ @pytest.mark.parametrize("format_name, extension", [
373
+ ("spdx-json", ".json"),
374
+ ("spdx-xml", ".xml"),
375
+ ("spdx-tag", ".tag"),
376
+ ])
377
+ def test_spdx_formats_are_supported_on_all_platforms(tmp_path, monkeypatch, scan_item, system, format_name, extension):
378
+ monkeypatch.setattr("platform.system", lambda: system)
379
+ success, err_msg, result_file = write_output_file(
380
+ os.path.join(str(tmp_path), format_name),
381
+ extension,
382
+ scan_item,
383
+ format=format_name,
384
+ )
385
+
386
+ assert success is True, err_msg
387
+ assert os.path.isfile(result_file)
388
+ if extension == ".json":
389
+ with open(result_file, encoding="utf-8") as spdx_file:
390
+ assert json.load(spdx_file)["spdxVersion"] == "SPDX-2.3"
391
+ elif extension == ".xml":
392
+ assert ElementTree.parse(result_file).getroot().tag == "Document"
393
+ else:
394
+ with open(result_file, encoding="utf-8") as spdx_file:
395
+ assert "SPDXVersion: SPDX-2.3" in spdx_file.read()
396
+
397
+
398
+ def test_spdx_import_failure_is_reported(monkeypatch, tmp_path, scan_item):
399
+ monkeypatch.setattr(
400
+ "fosslight_util.write_spdx._spdx_import_error",
401
+ ImportError("spdx-tools is unavailable"),
402
+ )
374
403
 
375
404
  success, err_msg, _ = write_output_file(
376
- os.path.join(constants.TEST_RESULT_DIR, system, "spdx"),
405
+ os.path.join(str(tmp_path), "spdx"),
377
406
  ".json",
378
407
  scan_item,
379
408
  format="spdx-json",
380
409
  )
381
410
 
382
411
  assert success is False
383
- assert err_msg == f"{system} not support spdx format."
412
+ assert "spdx-tools is unavailable" in err_msg