fosslight-source 2.3.17__tar.gz → 2.3.19__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 (38) hide show
  1. {fosslight_source-2.3.17/src/fosslight_source.egg-info → fosslight_source-2.3.19}/PKG-INFO +2 -2
  2. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/pyproject.toml +2 -2
  3. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_scan_item.py +1 -0
  4. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/cli.py +24 -7
  5. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/run_manifest_extractor.py +80 -1
  6. {fosslight_source-2.3.17 → fosslight_source-2.3.19/src/fosslight_source.egg-info}/PKG-INFO +2 -2
  7. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source.egg-info/SOURCES.txt +1 -1
  8. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source.egg-info/requires.txt +1 -1
  9. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_manifest_android_bp.py +4 -1
  10. fosslight_source-2.3.19/tests/test_manifest_nuspec.py +143 -0
  11. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_multi_value_order.py +1 -1
  12. fosslight_source-2.3.17/src/fosslight_source/_merge.py +0 -270
  13. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/LICENSE +0 -0
  14. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/MANIFEST.in +0 -0
  15. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/README.md +0 -0
  16. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/setup.cfg +0 -0
  17. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/__init__.py +0 -0
  18. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_exclude.py +0 -0
  19. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_help.py +0 -0
  20. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_kb_client.py +0 -0
  21. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_license_matched.py +0 -0
  22. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_parsing_scancode_file_item.py +0 -0
  23. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_parsing_scanoss_file.py +0 -0
  24. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/_scancode_ignore_binaries.py +0 -0
  25. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/run_scancode.py +0 -0
  26. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/run_scanoss.py +0 -0
  27. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source/run_spdx_extractor.py +0 -0
  28. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source.egg-info/dependency_links.txt +0 -0
  29. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source.egg-info/entry_points.txt +0 -0
  30. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/src/fosslight_source.egg-info/top_level.txt +0 -0
  31. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_kb_ssl.py +0 -0
  32. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_manifest_composer.py +0 -0
  33. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_manifest_pyproject.py +0 -0
  34. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_manifest_recommended_scenarios.py +0 -0
  35. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_manifest_setup_cfg.py +0 -0
  36. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_parsing_unknown_spdx.py +0 -0
  37. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_spdx_license_text.py +0 -0
  38. {fosslight_source-2.3.17 → fosslight_source-2.3.19}/tests/test_tox.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fosslight_source
3
- Version: 2.3.17
3
+ Version: 2.3.19
4
4
  Summary: FOSSLight Source Scanner
5
5
  Author: LG Electronics
6
6
  License-Expression: Apache-2.0
@@ -20,7 +20,7 @@ Requires-Dist: setuptools<=80.10.2
20
20
  Requires-Dist: pyparsing
21
21
  Requires-Dist: scanoss>=1.45.0
22
22
  Requires-Dist: XlsxWriter
23
- Requires-Dist: fosslight_util>=2.2.18
23
+ Requires-Dist: fosslight_util>=2.2.21
24
24
  Requires-Dist: PyYAML
25
25
  Requires-Dist: wheel>=0.38.1
26
26
  Requires-Dist: intbitset
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "fosslight_source"
10
- version = "2.3.17"
10
+ version = "2.3.19"
11
11
  description = "FOSSLight Source Scanner"
12
12
  readme = "README.md"
13
13
  license = "Apache-2.0"
@@ -29,7 +29,7 @@ dependencies = [
29
29
  "pyparsing",
30
30
  "scanoss>=1.45.0",
31
31
  "XlsxWriter",
32
- "fosslight_util>=2.2.18",
32
+ "fosslight_util>=2.2.21",
33
33
  "PyYAML",
34
34
  "wheel>=0.38.1",
35
35
  "intbitset",
@@ -18,6 +18,7 @@ _notice_filename = ['licen[cs]e[s]?', 'notice[s]?', 'legal', 'copyright[s]?', 'c
18
18
  'apache[-,_]?[1-2]?[.,-,_]?[0-2]?']
19
19
  _manifest_filename = [
20
20
  r'.*\.pom$',
21
+ r'.*\.nuspec$',
21
22
  r'package\.json$',
22
23
  r'composer\.json$',
23
24
  r'setup\.py$',
@@ -28,7 +28,7 @@ import yaml
28
28
  import tqdm
29
29
  import argparse
30
30
  from .run_spdx_extractor import get_spdx_downloads
31
- from .run_manifest_extractor import get_manifest_licenses
31
+ from .run_manifest_extractor import get_manifest_licenses_and_comment
32
32
  from ._scan_item import SourceItem, resolve_kb_config, is_notice_file, is_manifest_file
33
33
  from ._kb_client import create_kb_ssl_context, fetch_origin_urls_via_scan_job
34
34
  from fosslight_util.cover import dump_result_log
@@ -36,10 +36,7 @@ from fosslight_util.time import current_timestamp_utc, format_running_time, time
36
36
  from fosslight_util.oss_item import ScannerItem
37
37
  from typing import Optional, Tuple
38
38
  import shutil
39
- from ._merge import (
40
- _add_pre_merge_sheet,
41
- merge_results_by_folder
42
- )
39
+ from fosslight_util.merge import _add_pre_merge_sheet, merge_results_by_folder
43
40
 
44
41
 
45
42
  SRC_SHEET_NAME = 'SRC_FL_Source'
@@ -471,7 +468,8 @@ def merge_results(
471
468
  new_result_item.download_location = download_location
472
469
  scancode_result.append(new_result_item)
473
470
  if manifest_licenses:
474
- for file_name, licenses in manifest_licenses.items():
471
+ for file_name, entry in manifest_licenses.items():
472
+ licenses, or_comment = _split_manifest_license_entry(entry)
475
473
  # None: marker-only (keep ScanCode). list (incl. []): overwrite with extracted result.
476
474
  keep_scancode_licenses = licenses is None
477
475
  license_list = [] if keep_scancode_licenses else licenses
@@ -489,6 +487,8 @@ def merge_results(
489
487
  item.licenses = []
490
488
  if valid_licenses:
491
489
  item.licenses = valid_licenses
490
+ if or_comment:
491
+ item.comment = or_comment
492
492
 
493
493
  kb_origin_urls: dict[str, str] = {}
494
494
  kb_status_message: Optional[str] = None
@@ -526,6 +526,18 @@ def merge_results(
526
526
  return scancode_result, kb_status_message, kb_requested_count, kb_returned_count
527
527
 
528
528
 
529
+ def _split_manifest_license_entry(entry):
530
+ """Return (licenses, or_comment). or_comment is the unsplit OR expression."""
531
+ if (
532
+ isinstance(entry, tuple)
533
+ and len(entry) == 2
534
+ and isinstance(entry[1], str)
535
+ and (entry[0] is None or isinstance(entry[0], list))
536
+ ):
537
+ return entry[0], entry[1]
538
+ return entry, ""
539
+
540
+
529
541
  def _get_or_append_source_item(
530
542
  scancode_result: list, file_name: str, append: bool = True
531
543
  ) -> Optional[SourceItem]:
@@ -769,7 +781,12 @@ def metadata_collector(path_to_scan: str, excluded_files: set) -> tuple[dict, di
769
781
 
770
782
  if is_manifest_file(file_path):
771
783
  # Preserve None (marker-only); do not coerce with `or []`.
772
- manifest_licenses[rel_path_file] = get_manifest_licenses(file_path)
784
+ # (licenses, comment) when OR split the SPDX expression.
785
+ licenses, or_comment = get_manifest_licenses_and_comment(file_path)
786
+ if or_comment:
787
+ manifest_licenses[rel_path_file] = (licenses, or_comment)
788
+ else:
789
+ manifest_licenses[rel_path_file] = licenses
773
790
 
774
791
  return spdx_downloads, manifest_licenses
775
792
 
@@ -6,15 +6,30 @@ import os
6
6
  import json
7
7
  import re
8
8
  import logging
9
+ import contextvars
9
10
  from typing import Optional
11
+ from urllib.parse import unquote, urlparse
12
+ from defusedxml.ElementTree import parse as parse_xml
10
13
  from fosslight_util.get_pom_license import get_license_from_pom
11
14
  import fosslight_util.constant as constant
12
15
 
13
16
  logger = logging.getLogger(constant.LOGGER_NAME)
17
+ _OR_OPERATOR = re.compile(r'\s+OR\s+|\|\|', re.IGNORECASE)
18
+ # Set only while get_manifest_licenses_and_comment runs, so each SPDX split
19
+ # can keep the original expression without changing extractor return values.
20
+ _or_expression_comments: contextvars.ContextVar[Optional[list[str]]] = contextvars.ContextVar(
21
+ "manifest_or_expression_comments", default=None
22
+ )
14
23
 
15
24
 
16
25
  def _split_spdx_expression(value: str) -> list[str]:
17
- parts = re.split(r'\s+(?:OR|AND)\s+|[|]{2}|&&', value, flags=re.IGNORECASE)
26
+ text = (value or "").strip()
27
+ comments = _or_expression_comments.get()
28
+ if comments is not None and text and _OR_OPERATOR.search(text):
29
+ comment = re.sub(r'\s*\|\|\s*', ' OR ', text).strip()
30
+ if comment not in comments:
31
+ comments.append(comment)
32
+ parts = re.split(r'\s+(?:OR|AND)\s+|[|]{2}|&&', text, flags=re.IGNORECASE)
18
33
  tokens: list[str] = []
19
34
  for part in parts:
20
35
  token = part.strip().strip('()')
@@ -383,6 +398,64 @@ def get_licenses_from_huggingface_metadata(file_path: str) -> list[str]:
383
398
  return licenses
384
399
 
385
400
 
401
+ def get_licenses_from_nuspec(file_path: str) -> list[str]:
402
+ """Extract licenses from a NuGet .nuspec manifest.
403
+
404
+ type="expression" is an SPDX expression. type="file" names a packaged
405
+ license file and returns [] without reading that file. When license is
406
+ absent, a licenses.nuget.org licenseUrl contributes its SPDX id.
407
+ """
408
+ try:
409
+ root = parse_xml(file_path).getroot()
410
+ except Exception as ex:
411
+ logger.info(f"Failed to read nuspec {file_path}: {ex}")
412
+ return []
413
+
414
+ license_el = None
415
+ license_url_el = None
416
+ for el in root.iter():
417
+ name = el.tag.rsplit('}', 1)[-1] if isinstance(el.tag, str) else ''
418
+ if name == 'license' and license_el is None:
419
+ license_el = el
420
+ elif name == 'licenseUrl' and license_url_el is None:
421
+ license_url_el = el
422
+
423
+ if license_el is not None:
424
+ license_type = (license_el.get('type') or '').strip().lower()
425
+ text = (license_el.text or '').strip()
426
+ if license_type == 'file' or not text or text.upper() == 'UNLICENSED':
427
+ return []
428
+ if license_type not in ('expression', ''):
429
+ return []
430
+ return _split_spdx_expression(text)
431
+
432
+ if license_url_el is None:
433
+ return []
434
+ return _licenses_from_nuget_license_url(license_url_el.text or '')
435
+
436
+
437
+ def _licenses_from_nuget_license_url(url: str) -> list[str]:
438
+ parsed = urlparse((url or '').strip())
439
+ if parsed.hostname != 'licenses.nuget.org':
440
+ return []
441
+ # unquote, not unquote_plus: '+' belongs to SPDX ids such as Apache-2.0+.
442
+ token = unquote(parsed.path.lstrip('/').split('/', 1)[0]).strip()
443
+ if not token or token.upper() == 'UNLICENSED':
444
+ return []
445
+ return _split_spdx_expression(token)
446
+
447
+
448
+ def get_manifest_licenses_and_comment(file_path: str) -> tuple[Optional[list[str]], str]:
449
+ """Licenses plus the original expression when an OR operator split it."""
450
+ comments: list[str] = []
451
+ token = _or_expression_comments.set(comments)
452
+ try:
453
+ licenses = get_manifest_licenses(file_path)
454
+ finally:
455
+ _or_expression_comments.reset(token)
456
+ return licenses, ", ".join(comments)
457
+
458
+
386
459
  def get_manifest_licenses(file_path: str) -> Optional[list[str]]:
387
460
  """Extract licenses from a manifest file.
388
461
 
@@ -401,6 +474,12 @@ def get_manifest_licenses(file_path: str) -> Optional[list[str]]:
401
474
  except Exception as ex:
402
475
  logger.info(f"Failed to extract license from POM {file_path}: {ex}")
403
476
  return []
477
+ elif os.path.basename(file_path).lower().endswith('.nuspec'):
478
+ try:
479
+ return get_licenses_from_nuspec(file_path)
480
+ except Exception as ex:
481
+ logger.info(f"Failed to extract license from nuspec {file_path}: {ex}")
482
+ return []
404
483
  elif os.path.basename(file_path).lower() == 'package.json':
405
484
  try:
406
485
  return get_licenses_from_package_json(file_path)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fosslight_source
3
- Version: 2.3.17
3
+ Version: 2.3.19
4
4
  Summary: FOSSLight Source Scanner
5
5
  Author: LG Electronics
6
6
  License-Expression: Apache-2.0
@@ -20,7 +20,7 @@ Requires-Dist: setuptools<=80.10.2
20
20
  Requires-Dist: pyparsing
21
21
  Requires-Dist: scanoss>=1.45.0
22
22
  Requires-Dist: XlsxWriter
23
- Requires-Dist: fosslight_util>=2.2.18
23
+ Requires-Dist: fosslight_util>=2.2.21
24
24
  Requires-Dist: PyYAML
25
25
  Requires-Dist: wheel>=0.38.1
26
26
  Requires-Dist: intbitset
@@ -7,7 +7,6 @@ src/fosslight_source/_exclude.py
7
7
  src/fosslight_source/_help.py
8
8
  src/fosslight_source/_kb_client.py
9
9
  src/fosslight_source/_license_matched.py
10
- src/fosslight_source/_merge.py
11
10
  src/fosslight_source/_parsing_scancode_file_item.py
12
11
  src/fosslight_source/_parsing_scanoss_file.py
13
12
  src/fosslight_source/_scan_item.py
@@ -26,6 +25,7 @@ src/fosslight_source.egg-info/top_level.txt
26
25
  tests/test_kb_ssl.py
27
26
  tests/test_manifest_android_bp.py
28
27
  tests/test_manifest_composer.py
28
+ tests/test_manifest_nuspec.py
29
29
  tests/test_manifest_pyproject.py
30
30
  tests/test_manifest_recommended_scenarios.py
31
31
  tests/test_manifest_setup_cfg.py
@@ -2,7 +2,7 @@ setuptools<=80.10.2
2
2
  pyparsing
3
3
  scanoss>=1.45.0
4
4
  XlsxWriter
5
- fosslight_util>=2.2.18
5
+ fosslight_util>=2.2.21
6
6
  PyYAML
7
7
  wheel>=0.38.1
8
8
  intbitset
@@ -30,7 +30,10 @@ def test_metadata_collector_adds_android_bp_without_license_extraction(tmp_path)
30
30
  package_json = tmp_path / "package.json"
31
31
  package_json.write_text('{"license": "MIT"}', encoding="utf-8")
32
32
 
33
- with patch("fosslight_source.cli.get_manifest_licenses", wraps=get_manifest_licenses) as mock_get:
33
+ with patch(
34
+ "fosslight_source.run_manifest_extractor.get_manifest_licenses",
35
+ wraps=get_manifest_licenses,
36
+ ) as mock_get:
34
37
  spdx_downloads, manifest_licenses = metadata_collector(str(tmp_path), set())
35
38
 
36
39
  assert spdx_downloads == {}
@@ -0,0 +1,143 @@
1
+ # Copyright (c) 2026 LG Electronics Inc.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Tests for .nuspec manifest license extraction."""
4
+
5
+ from fosslight_source._scan_item import SourceItem, is_manifest_file
6
+ from fosslight_source.cli import merge_results
7
+ from fosslight_source.run_manifest_extractor import (
8
+ get_licenses_from_nuspec,
9
+ get_manifest_licenses,
10
+ get_manifest_licenses_and_comment,
11
+ )
12
+
13
+ _NUSPEC = """<?xml version="1.0" encoding="utf-8"?>
14
+ <package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
15
+ <metadata>
16
+ <id>Example</id>
17
+ <version>1.0.0</version>
18
+ {body}
19
+ </metadata>
20
+ </package>
21
+ """
22
+
23
+
24
+ def _write(tmp_path, body):
25
+ path = tmp_path / "Example.nuspec"
26
+ path.write_text(_NUSPEC.format(body=body), encoding="utf-8")
27
+ return path
28
+
29
+
30
+ def test_is_manifest_file_recognizes_nuspec():
31
+ assert is_manifest_file("/tmp/pkg/Example.nuspec") is True
32
+ assert is_manifest_file("/tmp/pkg/Example.NUSPEC") is True
33
+
34
+
35
+ def test_expression_license(tmp_path):
36
+ path = _write(tmp_path, '<license type="expression">MIT</license>')
37
+ assert get_licenses_from_nuspec(str(path)) == ["MIT"]
38
+
39
+
40
+ def test_expression_or(tmp_path):
41
+ path = _write(
42
+ tmp_path,
43
+ '<license type="expression">(BSD-2-Clause OR MIT)</license>',
44
+ )
45
+ assert get_licenses_from_nuspec(str(path)) == ["BSD-2-Clause", "MIT"]
46
+
47
+
48
+ def test_file_license_is_not_read(tmp_path):
49
+ path = _write(tmp_path, '<license type="file">LICENSE.txt</license>')
50
+ assert get_licenses_from_nuspec(str(path)) == []
51
+
52
+
53
+ def test_license_url_on_nuget(tmp_path):
54
+ path = _write(
55
+ tmp_path,
56
+ "<licenseUrl>https://licenses.nuget.org/Apache-2.0</licenseUrl>",
57
+ )
58
+ assert get_licenses_from_nuspec(str(path)) == ["Apache-2.0"]
59
+
60
+
61
+ def test_other_license_url_is_empty(tmp_path):
62
+ path = _write(
63
+ tmp_path,
64
+ "<licenseUrl>https://opensource.org/licenses/MIT</licenseUrl>",
65
+ )
66
+ assert get_licenses_from_nuspec(str(path)) == []
67
+
68
+
69
+ def test_license_url_decodes_expression_and_keeps_plus(tmp_path):
70
+ encoded = _write(
71
+ tmp_path,
72
+ "<licenseUrl>https://licenses.nuget.org/%28MIT%20OR%20Apache-2.0%29</licenseUrl>",
73
+ )
74
+ licenses, comment = get_manifest_licenses_and_comment(str(encoded))
75
+ assert licenses == ["MIT", "Apache-2.0"]
76
+ assert comment == "(MIT OR Apache-2.0)"
77
+
78
+ plus = _write(
79
+ tmp_path,
80
+ "<licenseUrl>https://licenses.nuget.org/Apache-2.0+</licenseUrl>",
81
+ )
82
+ assert get_licenses_from_nuspec(str(plus)) == ["Apache-2.0+"]
83
+
84
+ embedded = _write(
85
+ tmp_path,
86
+ "<licenseUrl>https://example.org/?target=https://licenses.nuget.org/MIT</licenseUrl>",
87
+ )
88
+ assert get_licenses_from_nuspec(str(embedded)) == []
89
+
90
+
91
+ def test_get_manifest_licenses_dispatches_nuspec(tmp_path):
92
+ path = _write(tmp_path, '<license type="expression">Apache-2.0</license>')
93
+ assert get_manifest_licenses(str(path)) == ["Apache-2.0"]
94
+
95
+
96
+ def test_or_split_keeps_original_expression_for_comment(tmp_path):
97
+ path = _write(tmp_path, '<license type="expression">(BSD-2-Clause OR MIT)</license>')
98
+ licenses, comment = get_manifest_licenses_and_comment(str(path))
99
+ assert licenses == ["BSD-2-Clause", "MIT"]
100
+ assert comment == "(BSD-2-Clause OR MIT)"
101
+
102
+
103
+ def test_double_pipe_is_written_as_or(tmp_path):
104
+ path = _write(tmp_path, '<license type="expression">(MIT||Apache-2.0)</license>')
105
+ licenses, comment = get_manifest_licenses_and_comment(str(path))
106
+ assert licenses == ["MIT", "Apache-2.0"]
107
+ assert comment == "(MIT OR Apache-2.0)"
108
+
109
+
110
+ def test_and_split_has_no_comment(tmp_path):
111
+ path = _write(tmp_path, '<license type="expression">MIT AND Apache-2.0</license>')
112
+ licenses, comment = get_manifest_licenses_and_comment(str(path))
113
+ assert licenses == ["MIT", "Apache-2.0"]
114
+ assert comment == ""
115
+
116
+
117
+ def test_or_inside_license_id_is_not_a_comment(tmp_path):
118
+ path = _write(tmp_path, '<license type="expression">GPL-2.0-or-later</license>')
119
+ licenses, comment = get_manifest_licenses_and_comment(str(path))
120
+ assert licenses == ["GPL-2.0-or-later"]
121
+ assert comment == ""
122
+
123
+
124
+ def test_merge_writes_or_expression_to_comment():
125
+ merged, _, _, _ = merge_results(
126
+ scancode_result=[],
127
+ manifest_licenses={
128
+ "pkg/Example.nuspec": (["BSD-2-Clause", "MIT"], "(BSD-2-Clause OR MIT)")
129
+ },
130
+ )
131
+ assert len(merged) == 1
132
+ assert merged[0].comment == "(BSD-2-Clause OR MIT)"
133
+ assert merged[0].is_manifest_file is True
134
+
135
+
136
+ def test_merge_and_expression_leaves_comment_empty():
137
+ item = SourceItem("pkg/Example.nuspec")
138
+ merged, _, _, _ = merge_results(
139
+ scancode_result=[item],
140
+ manifest_licenses={"pkg/Example.nuspec": ["MIT", "Apache-2.0"]},
141
+ )
142
+ assert merged[0].comment == ""
143
+ assert merged[0].licenses == ["Apache-2.0", "MIT"]
@@ -2,7 +2,7 @@
2
2
  # SPDX-License-Identifier: Apache-2.0
3
3
  """Stable order for multi-value License / Copyright cells."""
4
4
 
5
- from fosslight_source._merge import _get_top_merge_values
5
+ from fosslight_util.merge import _get_top_merge_values
6
6
  from fosslight_source._scan_item import SourceItem
7
7
 
8
8
 
@@ -1,270 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- # Copyright (c) 2020 LG Electronics Inc.
4
- # SPDX-License-Identifier: Apache-2.0
5
-
6
- import os
7
- from collections import Counter
8
-
9
- from fosslight_util.constant import COMMENT_DELIMITER
10
-
11
- from ._scan_item import SourceItem
12
-
13
-
14
- def _get_source_rows_to_print(source_items: list) -> list:
15
- source_rows = []
16
- for source_item in source_items:
17
- source_rows.extend(source_item.get_print_array())
18
- return source_rows
19
-
20
-
21
- def _add_pre_merge_sheet(scan_item, pre_merge_sheet_name: str, header_row: list, pkg_name: str) -> None:
22
- external_sheets = getattr(scan_item, "external_sheets", {}) or {}
23
- external_sheets[pre_merge_sheet_name] = [
24
- header_row,
25
- *_get_source_rows_to_print(scan_item.file_items.get(pkg_name, [])),
26
- ]
27
- scan_item.external_sheets = external_sheets
28
-
29
-
30
- def _normalize_merge_text(value: str) -> str:
31
- return value.strip() if value else ""
32
-
33
-
34
- def _iter_merge_values(values) -> list:
35
- if not values:
36
- return []
37
- if isinstance(values, str):
38
- return [values]
39
- return values
40
-
41
-
42
- def _normalize_merge_licenses(licenses) -> tuple:
43
- return tuple(sorted([lic.strip() for lic in _iter_merge_values(licenses) if lic and lic.strip()]))
44
-
45
-
46
- def _normalize_merge_downloads(downloads) -> tuple:
47
- if not downloads:
48
- return ()
49
- if isinstance(downloads, str):
50
- downloads = [downloads]
51
- return tuple(sorted([dl.strip() for dl in downloads if dl and dl.strip()]))
52
-
53
-
54
- def _iter_merge_rows(item: SourceItem):
55
- if item.oss_items:
56
- for oss_item in item.oss_items:
57
- name = _normalize_merge_text(oss_item.name) or _normalize_merge_text(item.oss_name)
58
- version = _normalize_merge_text(oss_item.version) or _normalize_merge_text(item.oss_version)
59
- licenses = _normalize_merge_licenses(oss_item.license or item.licenses)
60
- downloads = _normalize_merge_downloads(oss_item.download_location or item.download_location)
61
- yield name, version, licenses, downloads
62
- else:
63
- yield (
64
- _normalize_merge_text(item.oss_name),
65
- _normalize_merge_text(item.oss_version),
66
- _normalize_merge_licenses(item.licenses),
67
- _normalize_merge_downloads(item.download_location),
68
- )
69
-
70
-
71
- def _get_item_oss_name(item: SourceItem) -> str:
72
- for name, _, _, _ in _iter_merge_rows(item):
73
- if name:
74
- return name
75
- return ""
76
-
77
-
78
- def _get_item_oss_version(item: SourceItem) -> str:
79
- for _, version, _, _ in _iter_merge_rows(item):
80
- if version:
81
- return version
82
- return ""
83
-
84
-
85
- def _get_merge_licenses(scan_item: SourceItem) -> tuple:
86
- for _, _, licenses, _ in _iter_merge_rows(scan_item):
87
- if licenses:
88
- return licenses
89
- return ()
90
-
91
-
92
- def _get_merge_download_locations(scan_item: SourceItem) -> tuple:
93
- for _, _, _, downloads in _iter_merge_rows(scan_item):
94
- if downloads:
95
- return downloads
96
- return ()
97
-
98
-
99
- def _get_merge_field_value(scan_items: list, value_getter):
100
- for scan_item in scan_items:
101
- value = value_getter(scan_item)
102
- if value:
103
- return value
104
- return ""
105
-
106
-
107
- def _get_top_merge_values(scan_items: list, value_getter) -> list:
108
- values = []
109
- for scan_item in scan_items:
110
- for value in _iter_merge_values(value_getter(scan_item)):
111
- normalized_value = _normalize_merge_text(value)
112
- if normalized_value:
113
- values.append(normalized_value)
114
- ranked = sorted(Counter(values).items(), key=lambda entry: (-entry[1], entry[0]))
115
- return [value for value, _ in ranked[:3]]
116
-
117
-
118
- def _can_merge_folder(scan_items: list) -> bool:
119
- if len(scan_items) <= 1:
120
- return False
121
-
122
- ref_name = None
123
- ref_version = None
124
- ref_licenses = None
125
- ref_downloads = None
126
-
127
- for item in scan_items:
128
- for name, version, licenses, downloads in _iter_merge_rows(item):
129
- if name:
130
- if ref_name is None:
131
- ref_name = name
132
- elif name != ref_name:
133
- return False
134
-
135
- if version:
136
- if ref_version is None:
137
- ref_version = version
138
- elif version != ref_version:
139
- return False
140
-
141
- if licenses:
142
- if ref_licenses is None:
143
- ref_licenses = licenses
144
- elif licenses != ref_licenses:
145
- return False
146
-
147
- if downloads:
148
- if ref_downloads is None:
149
- ref_downloads = downloads
150
- elif downloads != ref_downloads:
151
- return False
152
-
153
- return True
154
-
155
-
156
- def _get_merged_comments(scan_items: list) -> str:
157
- comments = []
158
- for item in scan_items:
159
- val = item.comment
160
- if val:
161
- parts = [p.strip() for p in val.split(COMMENT_DELIMITER) if p.strip()]
162
- for p in parts:
163
- if p not in comments:
164
- comments.append(p)
165
- if not comments:
166
- return ""
167
-
168
- return COMMENT_DELIMITER.join(comments)
169
-
170
-
171
- def _create_merged_item(scan_items: list, merge_path: str) -> SourceItem:
172
- merged_path = f"{merge_path} ({len(scan_items)})"
173
- merged_item = SourceItem(merged_path)
174
- merged_item.oss_name = _get_merge_field_value(scan_items, lambda item: _normalize_merge_text(_get_item_oss_name(item)))
175
- merged_item.oss_version = _get_merge_field_value(scan_items, lambda item: _normalize_merge_text(_get_item_oss_version(item)))
176
- merged_licenses = _get_merge_field_value(scan_items, _get_merge_licenses)
177
- merged_item.licenses = list(merged_licenses) if merged_licenses else []
178
- merged_downloads = _get_merge_field_value(scan_items, _get_merge_download_locations)
179
- merged_item.download_location = list(merged_downloads) if merged_downloads else []
180
- merged_copyrights = _get_top_merge_values(scan_items, lambda item: item.copyright)
181
- merged_item.copyright = merged_copyrights if merged_copyrights else []
182
- merged_comments = _get_merged_comments(scan_items)
183
- if merged_comments:
184
- merged_item.comment = merged_comments
185
- merged_item.set_oss_item()
186
- return merged_item
187
-
188
-
189
- def merge_results_by_folder(scan_result: list) -> list:
190
- """
191
- Merge output rows within the same folder when OSS name, OSS version, license,
192
- and download location are compatible.
193
-
194
- A field is compatible when all non-empty values across rows are identical
195
- (empty values are ignored). Each oss_item is treated as its own row. All eligible
196
- rows in the folder must be compatible together; rows are not grouped by key subsets.
197
- """
198
- # Build a folder tree first so merge never jumps straight to root ".".
199
- merge_tree = {"items": [], "children": {}}
200
-
201
- for scan_item in scan_result:
202
- normalized_path = os.path.normpath(scan_item.source_name_or_path).replace("\\", "/")
203
- path_parts = [part for part in normalized_path.split("/") if part and part != "."]
204
- current_node = merge_tree
205
-
206
- for folder_name in path_parts[:-1]:
207
- current_node = current_node["children"].setdefault(folder_name, {"items": [], "children": {}})
208
- current_node["items"].append(scan_item)
209
-
210
- def merge_node(merge_node_item: dict, merge_path: str = "", depth: int = 0) -> tuple:
211
- child_finalized = []
212
- child_unfinalized = []
213
- for folder_name, child_node in merge_node_item["children"].items():
214
- child_path = f"{merge_path}/{folder_name}" if merge_path else folder_name
215
- fin, unfin = merge_node(child_node, child_path, depth + 1)
216
- child_finalized.extend(fin)
217
- child_unfinalized.extend(unfin)
218
-
219
- local_excluded = [item for item in merge_node_item["items"] if item.exclude]
220
- local_eligible = [item for item in merge_node_item["items"] if not item.exclude]
221
-
222
- all_eligible_candidates = list(local_eligible)
223
- for _, g_items in child_unfinalized:
224
- all_eligible_candidates.extend(g_items)
225
-
226
- # We can merge under the current node if depth > 0 and we are combining multiple sources:
227
- # e.g., local files + child groups, or multiple child groups, or multiple local files.
228
- can_merge_here = (depth > 0) and (len(local_eligible) + len(child_unfinalized) > 1)
229
-
230
- if can_merge_here:
231
- if _can_merge_folder(all_eligible_candidates):
232
- new_finalized = child_finalized + local_excluded
233
- new_unfinalized = [(merge_path, all_eligible_candidates)]
234
- return new_finalized, new_unfinalized
235
- else:
236
- # Compatibility broke at this level. We must finalize the subtrees.
237
- finalized_child_groups = []
238
- for c_path, c_items in child_unfinalized:
239
- if len(c_items) > 1 and _can_merge_folder(c_items):
240
- finalized_child_groups.append(_create_merged_item(c_items, c_path))
241
- else:
242
- finalized_child_groups.extend(c_items)
243
-
244
- finalized_local = []
245
- if len(local_eligible) > 1 and _can_merge_folder(local_eligible):
246
- finalized_local.append(_create_merged_item(local_eligible, merge_path))
247
- else:
248
- finalized_local.extend(local_eligible)
249
-
250
- new_finalized = child_finalized + local_excluded + finalized_child_groups + finalized_local
251
- new_unfinalized = []
252
- return new_finalized, new_unfinalized
253
- else:
254
- # We cannot merge or don't need to merge at this level (e.g. depth == 0 or only 1 source).
255
- # We propagate everything up as unfinalized.
256
- new_finalized = child_finalized + local_excluded
257
- new_unfinalized = list(child_unfinalized)
258
- if local_eligible:
259
- new_unfinalized.append((merge_path, local_eligible))
260
- return new_finalized, new_unfinalized
261
-
262
- fin, unfin = merge_node(merge_tree)
263
- finalized_results = list(fin)
264
- for path, items in unfin:
265
- if path and len(items) > 1 and _can_merge_folder(items):
266
- finalized_results.append(_create_merged_item(items, path))
267
- else:
268
- finalized_results.extend(items)
269
-
270
- return finalized_results