Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 149 additions & 40 deletions src/formattedcode/output_spdx.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
from spdx_tools.spdx.spdx_element_utils import calculate_package_verification_code

from formattedcode import FileOptionType
from licensedcode.detection import get_matches_from_detection_mappings
from plugincode.output import output_impl
from plugincode.output import OutputPlugin
import scancode_config
Expand Down Expand Up @@ -178,6 +177,18 @@ def check_sha1(codebase):
)


def get_detection_uuid(identifier):
"""
Return the UUID portion of a license detection identifier.
"""
try:
return str(uuid.UUID(identifier[-36:]))
except (TypeError, ValueError, AttributeError) as e:
raise ValueError(
f'Invalid license detection identifier: {identifier!r}'
) from e


def write_spdx(
codebase,
output_file,
Expand Down Expand Up @@ -247,6 +258,9 @@ def write_spdx(
all_files_have_no_license = True
all_files_have_no_copyright = True

extracted_license_data = {}
package_license_ids = set()

# FIXME: this should walk the codebase instead!!!
for sid, file_data in enumerate(files, 1):

Expand All @@ -271,49 +285,125 @@ def write_spdx(
)

file_license_detections = file_data.get('license_detections')
license_matches = get_matches_from_detection_mappings(file_license_detections)
if license_matches:
if file_license_detections:
all_files_have_no_license = False
for match in license_matches:
file_license_expression = match["license_expression"]
file_license_keys = licensing.license_keys(
expression=file_license_expression,
unique=True
file_license_expressions = []

for detection in file_license_detections:
license_expression = detection.get("license_expression")
license_expression_spdx = detection.get("license_expression_spdx")

detection_uuid = get_detection_uuid(detection.get("identifier"))

detected_expression = licensing.parse(license_expression)
detected_spdx_expression = licensing.parse(license_expression_spdx)

license_data_by_spdx_id = {}
matched_texts_by_spdx_id = {}

detection_spdx_symbols = {
symbol.key: symbol
for symbol in licensing.license_symbols(
detected_spdx_expression,
unique=True,
)
}

detection_license_keys = licensing.license_keys(
expression=detected_expression,
unique=True,
)
for license_key in file_license_keys:
file_license = licenses.get(license_key)
license_key = file_license.key

for license_key in detection_license_keys:
file_license = licenses.get(license_key)
spdx_id = file_license.spdx_license_key
if not spdx_id:
spdx_id = f'LicenseRef-scancode-{license_key}'
is_license_ref = spdx_id.lower().startswith('licenseref-')

spdx_license = licensing.parse(spdx_id)

if is_license_ref:
text = match.get('matched_text')
# FIXME: replace this with the licensedb URL
comment = (
f'See details at https://github.com/nexB/scancode-toolkit'
f'/blob/develop/src/licensedcode/data/licenses/{license_key}.LICENSE\n'
)
extracted_license = ExtractedLicensingInfo(
license_id=spdx_id,
# always set some text, even if we did not extract the
# matched text
extracted_text=text if text else comment,
license_name=file_license.short_name,
comment=comment,
)
doc.extracted_licensing_info.append(extracted_license)

# Add licenses in the order they appear in the file. Maintaining
# the order might be useful for provenance purposes.
file_entry.license_info_in_file.append(spdx_license)
package.license_info_from_files.append(spdx_license)

elif license_matches is None:

license_data_by_spdx_id[spdx_id] = file_license

# Collect matched text only for non-official SPDX licenses.
for match in detection.get('matches'):
matched_text = match.get('matched_text')
match_expression = match.get('license_expression')
match_license_keys = licensing.license_keys(
expression=match_expression,
unique=True,
)

for license_key in match_license_keys:
file_license = licenses.get(license_key)
spdx_id = file_license.spdx_license_key
if not spdx_id:
spdx_id = f'LicenseRef-scancode-{license_key}'

if not spdx_id.lower().startswith('licenseref-'):
continue

matched_texts_by_spdx_id.setdefault(
spdx_id,
[],
).append(matched_text)

updated_spdx_license_ref = {}

for spdx_id in detection_spdx_symbols:
if not spdx_id.lower().startswith('licenseref-'):
continue

hashed_ref_id = f'{spdx_id}-{detection_uuid}'
updated_spdx_license_ref[spdx_id] = hashed_ref_id
file_license = license_data_by_spdx_id.get(spdx_id)

comment = (
f'See details at https://scancode-licensedb.aboutcode.org/'
f'{file_license.key}.LICENSE\n'
)

license_data = extracted_license_data.setdefault(
hashed_ref_id,
{
'license_name': file_license.short_name,
'comment': comment,
'matched_texts': [],
},
)

for matched_text in matched_texts_by_spdx_id.get(spdx_id, []):
if matched_text not in license_data['matched_texts']:
license_data['matched_texts'].append(matched_text)

updated_license_expression_spdx = license_expression_spdx

for spdx_id, hashed_ref_id in updated_spdx_license_ref.items():
updated_license_expression_spdx = updated_license_expression_spdx.replace(
spdx_id,
hashed_ref_id,
)

updated_detected_license_expr = licensing.dedup(
licensing.parse(updated_license_expression_spdx)
)

file_license_expressions.append(str(updated_detected_license_expr))

for symbol in licensing.license_symbols(
updated_detected_license_expr,
unique=True,
):
package_license_ids.add(symbol.key)

if file_license_expressions:
combined_expression = ' AND '.join(
f'({expression})'
for expression in file_license_expressions
)

file_entry.license_info_in_file.append(
licensing.parse(combined_expression)
)

elif file_license_detections is None:
all_files_have_no_license = False
file_entry.license_info_in_file.append(SpdxNoAssertion())

Expand Down Expand Up @@ -347,6 +437,22 @@ def write_spdx(
relationship = Relationship(package.spdx_id, RelationshipType.CONTAINS, file_entry.spdx_id)
doc.relationships.append(relationship)

# Create extracted license entries after collecting all matched texts.
for extracted_spdx_id, license_data in extracted_license_data.items():
extracted_text = '\n'.join(license_data['matched_texts'])

if not extracted_text:
extracted_text = license_data['comment']

extracted_license = ExtractedLicensingInfo(
license_id=extracted_spdx_id,
extracted_text=extracted_text,
license_name=license_data['license_name'],
comment=license_data['comment'],
)

doc.extracted_licensing_info.append(extracted_license)

if not doc.files:
if as_tagvalue:
msg = "# No results for package '{}'.\n".format(package.name)
Expand All @@ -355,8 +461,11 @@ def write_spdx(
msg = "<!-- No results for package '{}'. -->\n".format(package.name)
output_file.write(msg)

# Remove duplicate licenses from the list for the package.
package.license_info_from_files = list(set(package.license_info_from_files))
# List unique license identifiers found in the files.
package.license_info_from_files = [
licensing.parse(license_id)
for license_id in sorted(package_license_ids)
]
if not package.license_info_from_files:
if all_files_have_no_license:
package.license_info_from_files = [SpdxNone()]
Expand Down
Loading