From aced0fb5befb3ef8a56e0adbf92bb4585bfe923c Mon Sep 17 00:00:00 2001 From: Chin Yeung Li Date: Wed, 2 Dec 2026 21:54:28 +0800 Subject: [PATCH 1/2] Handle multiple LicenseID entries in SPDX #3258 - Use detection-level license expressions instead of individual match expressions. - Append detection UUIDs to non-official SPDX license identifiers to distinguish different detections. - Use complete license expressions for `LicenseInfoInFile`. - Deduplicate license identifiers in `PackageLicenseInfoFromFiles`. Signed-off-by: Chin Yeung Li --- src/formattedcode/output_spdx.py | 178 ++++++++++++++++++++++++------- 1 file changed, 138 insertions(+), 40 deletions(-) diff --git a/src/formattedcode/output_spdx.py b/src/formattedcode/output_spdx.py index 88039c7f2e9..ae709692aa1 100644 --- a/src/formattedcode/output_spdx.py +++ b/src/formattedcode/output_spdx.py @@ -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 @@ -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, @@ -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): @@ -271,49 +285,114 @@ 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 + + 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_entry.license_info_in_file.append(updated_detected_license_expr) + + for symbol in licensing.license_symbols( + updated_detected_license_expr, + unique=True, + ): + package_license_ids.add(symbol.key) + + elif file_license_detections is None: all_files_have_no_license = False file_entry.license_info_in_file.append(SpdxNoAssertion()) @@ -347,6 +426,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) @@ -355,8 +450,11 @@ def write_spdx( msg = "\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()] From 8175649eec1f2394e97ddcc3774018eef75ba6ae Mon Sep 17 00:00:00 2001 From: Chin Yeung Li Date: Wed, 2 Dec 2026 22:15:39 +0800 Subject: [PATCH 2/2] Fix to have single license expression for `LicenseInfoInFile` #3258 Signed-off-by: Chin Yeung Li --- src/formattedcode/output_spdx.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/formattedcode/output_spdx.py b/src/formattedcode/output_spdx.py index ae709692aa1..22ff752ec2a 100644 --- a/src/formattedcode/output_spdx.py +++ b/src/formattedcode/output_spdx.py @@ -287,6 +287,7 @@ def write_spdx( file_license_detections = file_data.get('license_detections') if file_license_detections: all_files_have_no_license = False + file_license_expressions = [] for detection in file_license_detections: license_expression = detection.get("license_expression") @@ -384,7 +385,7 @@ def write_spdx( licensing.parse(updated_license_expression_spdx) ) - file_entry.license_info_in_file.append(updated_detected_license_expr) + file_license_expressions.append(str(updated_detected_license_expr)) for symbol in licensing.license_symbols( updated_detected_license_expr, @@ -392,6 +393,16 @@ def write_spdx( ): 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())