fosslight-util 2.2.18__tar.gz → 2.2.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 (55) hide show
  1. {fosslight_util-2.2.18/src/fosslight_util.egg-info → fosslight_util-2.2.19}/PKG-INFO +1 -1
  2. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/pyproject.toml +1 -1
  3. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/_get_downloadable_url.py +121 -10
  4. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/download.py +79 -45
  5. {fosslight_util-2.2.18 → fosslight_util-2.2.19/src/fosslight_util.egg-info}/PKG-INFO +1 -1
  6. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util.egg-info/SOURCES.txt +1 -0
  7. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_download_timeout.py +1 -1
  8. fosslight_util-2.2.19/tests/test_download_version_attempts.py +225 -0
  9. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/LICENSE +0 -0
  10. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/MANIFEST.in +0 -0
  11. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/README.md +0 -0
  12. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/setup.cfg +0 -0
  13. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/__init__.py +0 -0
  14. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/compare_yaml.py +0 -0
  15. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/constant.py +0 -0
  16. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/correct.py +0 -0
  17. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/cover.py +0 -0
  18. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/exclude.py +0 -0
  19. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/get_pom_license.py +0 -0
  20. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/help.py +0 -0
  21. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/oss_item.py +0 -0
  22. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/output_format.py +0 -0
  23. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/parsing_yaml.py +0 -0
  24. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/read_excel.py +0 -0
  25. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/resources/frequentLicenselist.json +0 -0
  26. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/resources/frequent_license_nick_list.json +0 -0
  27. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/resources/licenses.json +0 -0
  28. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/set_log.py +0 -0
  29. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/spdx_licenses.py +0 -0
  30. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/time.py +0 -0
  31. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/timer_thread.py +0 -0
  32. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/write_cyclonedx.py +0 -0
  33. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/write_excel.py +0 -0
  34. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/write_opossum.py +0 -0
  35. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/write_scancodejson.py +0 -0
  36. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/write_spdx.py +0 -0
  37. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/write_txt.py +0 -0
  38. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util/write_yaml.py +0 -0
  39. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util.egg-info/dependency_links.txt +0 -0
  40. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util.egg-info/entry_points.txt +0 -0
  41. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util.egg-info/requires.txt +0 -0
  42. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/src/fosslight_util.egg-info/top_level.txt +0 -0
  43. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_cyclonedx.py +0 -0
  44. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_decide_checkout.py +0 -0
  45. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_download.py +0 -0
  46. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_download_maven.py +0 -0
  47. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_download_packagist.py +0 -0
  48. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_download_version_hint.py +0 -0
  49. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_opossum.py +0 -0
  50. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_spdx.py +0 -0
  51. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_spdx_licenses.py +0 -0
  52. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_text.py +0 -0
  53. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_write_excel_hidden_sheet.py +0 -0
  54. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/tests/test_write_output.py +0 -0
  55. {fosslight_util-2.2.18 → fosslight_util-2.2.19}/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.18
3
+ Version: 2.2.19
4
4
  Summary: FOSSLight Util
5
5
  Author: LG Electronics
6
6
  License-Expression: Apache-2.0
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "fosslight_util"
10
- version = "2.2.18"
10
+ version = "2.2.19"
11
11
  description = "FOSSLight Util"
12
12
  readme = "README.md"
13
13
  license = "Apache-2.0"
@@ -368,7 +368,8 @@ def version_exists(pkg_type, origin_name, version):
368
368
  elif pkg_type == 'go':
369
369
  if not version.startswith('v'):
370
370
  version = f'v{version}'
371
- r = requests.get(f'https://proxy.golang.org/{origin_name}/@v/list', timeout=5)
371
+ module_path = _go_proxy_escape(origin_name)
372
+ r = requests.get(f'https://proxy.golang.org/{module_path}/@v/list', timeout=5)
372
373
  if r.status_code == 200:
373
374
  listed = r.text.splitlines()
374
375
  return version in listed
@@ -381,7 +382,99 @@ def version_exists(pkg_type, origin_name, version):
381
382
  return False
382
383
 
383
384
 
384
- def extract_name_version_from_link(link, checkout_version):
385
+ def _go_proxy_escape(module_path):
386
+ """Encode a Go module path for proxy.golang.org.
387
+
388
+ Each uppercase letter becomes an exclamation mark plus its lowercase form,
389
+ so DataDog is requested as !data!dog.
390
+ """
391
+ escaped = []
392
+ for char in module_path or "":
393
+ if char.isupper():
394
+ escaped.append("!")
395
+ escaped.append(char.lower())
396
+ else:
397
+ escaped.append(char)
398
+ return "".join(escaped)
399
+
400
+
401
+ def split_pkg_link_version(link):
402
+ """Return (url without version, version) for a recognized package URL.
403
+
404
+ The version is empty when the URL has no version component.
405
+ """
406
+ text = (link or "").strip()
407
+ if not text:
408
+ return text, ""
409
+ for key, value in constant.PKG_PATTERN.items():
410
+ if key in ("maven_repo1", "maven_google", "cocoapods", "pypi2"):
411
+ continue
412
+ match = re.match(value, text)
413
+ if not match:
414
+ continue
415
+ if key == "go":
416
+ name = match.group(1)
417
+ if name.endswith("/"):
418
+ name = name[:-1]
419
+ version = (match.group(2) or "").strip()
420
+ if not version:
421
+ return text, ""
422
+ return f"https://pkg.go.dev/{name}", version
423
+ if key == "pypi":
424
+ version = (match.group(2) or "").strip()
425
+ if not version:
426
+ return text, ""
427
+ return f"https://pypi.org/project/{match.group(1)}", version
428
+ if key == "maven":
429
+ version = (match.group(3) or "").strip()
430
+ if not version:
431
+ return text, ""
432
+ return (
433
+ f"https://mvnrepository.com/artifact/{match.group(1)}/{match.group(2)}",
434
+ version,
435
+ )
436
+ if key in ("npm", "npm2"):
437
+ version = (match.group(2) or "").strip()
438
+ if not version:
439
+ return text, ""
440
+ return f"https://www.npmjs.com/package/{match.group(1)}", version
441
+ if key == "pub":
442
+ version = (match.group(2) or "").strip()
443
+ if not version:
444
+ return text, ""
445
+ return f"https://pub.dev/packages/{match.group(1)}", version
446
+ if key == "cargo":
447
+ version = (match.group(2) or "").strip()
448
+ if not version:
449
+ return text, ""
450
+ return f"https://crates.io/crates/{match.group(1)}", version
451
+ if key == "packagist":
452
+ version = (match.group(2) or match.group(3) or "").strip()
453
+ if not version:
454
+ return text, ""
455
+ return f"https://packagist.org/packages/{match.group(1)}", version
456
+ return text, ""
457
+
458
+
459
+ def download_version_attempts(link, checkout_to):
460
+ """Plan download attempts as (link, checkout_to, allow_latest).
461
+
462
+ A package URL that already has a version is tried as-is, without replacing
463
+ a missing version by the latest release. When that attempt fails and
464
+ checkout_to is set, the version is removed from the URL and checkout_to is
465
+ used. That second attempt may fall back to the latest version.
466
+ """
467
+ bare_link, embedded_version = split_pkg_link_version(link)
468
+ checkout_text = (checkout_to or "").strip()
469
+ if embedded_version and checkout_text:
470
+ return [
471
+ (link, "", False),
472
+ (bare_link, checkout_text, True),
473
+ ]
474
+ return [(link, checkout_to, True)]
475
+
476
+
477
+ def extract_name_version_from_link(link, checkout_version, allow_latest=True):
385
478
  oss_name = ""
386
479
  oss_version = ""
387
480
  matched = False
@@ -474,13 +567,24 @@ def extract_name_version_from_link(link, checkout_version):
474
567
  if oss_version.startswith('v') and version_exists(pkg_type, origin_name, oss_version[1:]):
475
568
  logger.info(f'Version {oss_version} not found; using without leading v: {oss_version[1:]}')
476
569
  oss_version = oss_version[1:]
477
- else:
570
+ elif allow_latest:
478
571
  logger.info(f'Version {oss_version} not found for {oss_name}; will attempt latest fallback')
479
572
  need_latest = True
573
+ else:
574
+ logger.info(
575
+ f'Version {oss_version} not found for {oss_name}; '
576
+ 'not replacing it with latest on this attempt'
577
+ )
480
578
  except Exception as e:
481
- logger.info(f'Version validation failed ({oss_name}:{oss_version}) {e}; will attempt latest fallback')
482
- need_latest = True
483
- else:
579
+ if allow_latest:
580
+ logger.info(f'Version validation failed ({oss_name}:{oss_version}) {e}; will attempt latest fallback')
581
+ need_latest = True
582
+ else:
583
+ logger.info(
584
+ f'Version validation failed ({oss_name}:{oss_version}) {e}; '
585
+ 'not replacing it with latest on this attempt'
586
+ )
587
+ elif allow_latest:
484
588
  need_latest = True
485
589
  if need_latest:
486
590
  latest_ver = get_latest_package_version(link, pkg_type, origin_name)
@@ -670,7 +774,10 @@ def get_latest_package_version(link, pkg_type, oss_name):
670
774
  if pub_response.status_code == 200:
671
775
  find_version = pub_response.json().get('latest').get('version')
672
776
  elif pkg_type == 'go':
673
- go_response = requests.get(f'https://proxy.golang.org/{oss_name}/@latest', timeout=_HTTP_TIMEOUT)
777
+ module_path = _go_proxy_escape(oss_name)
778
+ go_response = requests.get(
779
+ f'https://proxy.golang.org/{module_path}/@latest', timeout=_HTTP_TIMEOUT
780
+ )
674
781
  if go_response.status_code == 200:
675
782
  find_version = go_response.json().get('Version')
676
783
  if find_version.startswith('v'):
@@ -685,7 +792,7 @@ def get_latest_package_version(link, pkg_type, oss_name):
685
792
  return find_version
686
793
 
687
794
 
688
- def get_downloadable_url(link, checkout_version):
795
+ def get_downloadable_url(link, checkout_version, allow_latest=True):
689
796
 
690
797
  ret = False
691
798
  result_link = link
@@ -697,7 +804,9 @@ def get_downloadable_url(link, checkout_version):
697
804
  if resolved:
698
805
  return True, resolved, "", debian_version, "deb"
699
806
 
700
- oss_name, oss_version, new_link, pkg_type = extract_name_version_from_link(link, checkout_version)
807
+ oss_name, oss_version, new_link, pkg_type = extract_name_version_from_link(
808
+ link, checkout_version, allow_latest=allow_latest
809
+ )
701
810
  new_link = new_link.replace('http://', '')
702
811
  new_link = new_link.replace('https://', '')
703
812
 
@@ -811,8 +920,10 @@ def get_download_location_for_go(link):
811
920
  if oss_name.endswith('/'):
812
921
  oss_name = oss_name[:-1]
813
922
  oss_version = dn_loc_re[0][1]
923
+ if oss_version and not oss_version.startswith('v'):
924
+ oss_version = f'v{oss_version}'
814
925
 
815
- new_link = f'{host}/{oss_name}/@v/{oss_version}.zip'
926
+ new_link = f'{host}/{_go_proxy_escape(oss_name)}/@v/{oss_version}.zip'
816
927
  try:
817
928
  res = urlopen(new_link, timeout=_HTTP_TIMEOUT)
818
929
  if res.getcode() == 200:
@@ -16,7 +16,10 @@ import contextlib
16
16
  from contextvars import ContextVar
17
17
  from datetime import datetime
18
18
  from pathlib import Path
19
- from fosslight_util._get_downloadable_url import get_downloadable_url
19
+ from fosslight_util._get_downloadable_url import (
20
+ download_version_attempts,
21
+ get_downloadable_url,
22
+ )
20
23
  from fosslight_util.help import print_help_msg_download
21
24
  import fosslight_util.constant as constant
22
25
  from fosslight_util.set_log import init_log
@@ -370,6 +373,7 @@ def cli_download_and_extract(link: str, target_dir: str, log_dir: str, checkout_
370
373
  logger, log_item = init_log(os.path.join(log_dir, log_file_name))
371
374
  link = link.strip()
372
375
  is_rubygems = False
376
+ link_version_failure = ""
373
377
  # One overall deadline for the whole download: git clone, then HTTP/wget.
374
378
  owner = _enter_download_watchdog(timeout, new_operation=True)
375
379
 
@@ -389,51 +393,76 @@ def cli_download_and_extract(link: str, target_dir: str, log_dir: str, checkout_
389
393
  tag = ''.join(src_info.get("tag", "")).split('=')[-1]
390
394
  branch = ''.join(src_info.get("branch", "")).split('=')[-1]
391
395
  is_rubygems = src_info.get("rubygems", False)
392
-
393
- # General download: git clone → requests → system wget
394
- success_git, msg, oss_name, oss_version, clarified_from_git = download_git_clone(
395
- link, target_dir, checkout_to, tag, branch,
396
- ssh_key, id, git_token, called_cli, size_limit_gb=size_limit_gb)
397
- link = change_ssh_link_to_https(link)
398
- if success_git:
399
- downloaded_link = link
400
- success = True
401
- size_limit_blocked = _is_size_limit_block_message(msg)
402
- if size_limit_blocked:
403
- success = False
404
- elif (not is_rubygems) and (not success_git):
405
- success, downloaded_file, msg_wget, oss_name, oss_version, resolved_link = download_wget(
406
- link, target_dir, compressed_only, checkout_to,
407
- size_limit_gb=size_limit_gb,
408
- )
409
- if _is_size_limit_block_message(msg_wget):
410
- size_limit_blocked = True
396
+ attempts = download_version_attempts(link, checkout_to)
397
+
398
+ for attempt_index, (attempt_link, attempt_checkout, allow_latest) in enumerate(attempts):
399
+ if attempt_index:
400
+ parts = []
401
+ if msg:
402
+ parts.append(f"git fail: {msg}")
403
+ if msg_wget:
404
+ parts.append(f"wget fail: {msg_wget}")
405
+ link_version_failure = ", ".join(parts)
406
+ logger.info(
407
+ "Link version download failed; retry with checkout version "
408
+ f"{attempt_checkout}. {link_version_failure}"
409
+ )
410
+ success = True
411
+ msg = ""
412
+ msg_wget = ""
413
+ oss_name = ""
414
+ oss_version = ""
415
+ clarified_from_git = ""
416
+ downloaded_link = ""
417
+ size_limit_blocked = False
418
+
419
+ # General download: git clone → requests → system wget
420
+ success_git, msg, oss_name, oss_version, clarified_from_git = download_git_clone(
421
+ attempt_link, target_dir, attempt_checkout, tag, branch,
422
+ ssh_key, id, git_token, called_cli, size_limit_gb=size_limit_gb)
423
+ link = change_ssh_link_to_https(attempt_link)
424
+ if success_git:
425
+ downloaded_link = link
426
+ success = True
427
+ size_limit_blocked = _is_size_limit_block_message(msg)
428
+ if size_limit_blocked:
411
429
  success = False
412
- msg = msg_wget
413
- elif success and downloaded_file:
414
- success = extract_compressed_file(
415
- downloaded_file, target_dir, True, compressed_only
430
+ elif (not is_rubygems) and (not success_git):
431
+ success, downloaded_file, msg_wget, oss_name, oss_version, resolved_link = download_wget(
432
+ link, target_dir, compressed_only, attempt_checkout,
433
+ size_limit_gb=size_limit_gb,
434
+ allow_latest=allow_latest,
416
435
  )
417
- if success:
418
- downloaded_link = resolved_link
419
- else:
420
- # Extract failed (e.g. non-archive when compressed_only): fail
421
- msg_wget = (
422
- f"Failed to extract downloaded file: {downloaded_file}"
436
+ if _is_size_limit_block_message(msg_wget):
437
+ size_limit_blocked = True
438
+ success = False
439
+ msg = msg_wget
440
+ elif success and downloaded_file:
441
+ success = extract_compressed_file(
442
+ downloaded_file, target_dir, True, compressed_only
423
443
  )
424
- try:
425
- if os.path.isfile(downloaded_file):
426
- os.remove(downloaded_file)
427
- except OSError:
428
- pass
429
- # Download from rubygems.org
430
- elif is_rubygems and shutil.which("gem"):
431
- _raise_if_download_timed_out()
432
- success = gem_download(link, target_dir, checkout_to)
433
- # Do not accept a gem that finished, or was stopped, after the deadline.
434
- _raise_if_download_timed_out()
435
- if success:
436
- downloaded_link = link
444
+ if success:
445
+ downloaded_link = resolved_link
446
+ else:
447
+ # Extract failed (e.g. non-archive when compressed_only): fail
448
+ msg_wget = (
449
+ f"Failed to extract downloaded file: {downloaded_file}"
450
+ )
451
+ try:
452
+ if os.path.isfile(downloaded_file):
453
+ os.remove(downloaded_file)
454
+ except OSError:
455
+ pass
456
+ # Download from rubygems.org
457
+ elif is_rubygems and shutil.which("gem"):
458
+ _raise_if_download_timed_out()
459
+ success = gem_download(link, target_dir, attempt_checkout)
460
+ # Do not accept a gem that finished, or was stopped, after the deadline.
461
+ _raise_if_download_timed_out()
462
+ if success:
463
+ downloaded_link = link
464
+ if success or size_limit_blocked:
465
+ break
437
466
  if size_limit_blocked:
438
467
  # Keep a clear size-limit message for callers/UI (do not wrap as git/wget fail)
439
468
  pass
@@ -448,6 +477,8 @@ def cli_download_and_extract(link: str, target_dir: str, log_dir: str, checkout_
448
477
  msg = f'{msg}, wget fail: {msg_wget}'
449
478
  elif msg_wget:
450
479
  msg = f'wget fail: {msg_wget}'
480
+ if link_version_failure and not success and not size_limit_blocked and msg:
481
+ msg = f"link version failed ({link_version_failure}); {msg}"
451
482
 
452
483
  except Exception as error:
453
484
  success = False
@@ -1355,7 +1386,8 @@ def _download_with_system_wget(url, target_dir, size_limit_gb=None):
1355
1386
  return local_path
1356
1387
 
1357
1388
 
1358
- def download_wget(link, target_dir, compressed_only, checkout_to, size_limit_gb=None):
1389
+ def download_wget(link, target_dir, compressed_only, checkout_to, size_limit_gb=None,
1390
+ allow_latest=True):
1359
1391
  success = False
1360
1392
  msg = ""
1361
1393
  oss_name = ""
@@ -1369,7 +1401,9 @@ def download_wget(link, target_dir, compressed_only, checkout_to, size_limit_gb=
1369
1401
 
1370
1402
  # The git step may have used up the time; the lookup below may use up the rest.
1371
1403
  _raise_if_download_timed_out()
1372
- ret, new_link, oss_name, oss_version, pkg_type = get_downloadable_url(link, checkout_to)
1404
+ ret, new_link, oss_name, oss_version, pkg_type = get_downloadable_url(
1405
+ link, checkout_to, allow_latest=allow_latest
1406
+ )
1373
1407
  _raise_if_download_timed_out()
1374
1408
  if ret and new_link:
1375
1409
  link = new_link
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fosslight_util
3
- Version: 2.2.18
3
+ Version: 2.2.19
4
4
  Summary: FOSSLight Util
5
5
  Author: LG Electronics
6
6
  License-Expression: Apache-2.0
@@ -42,6 +42,7 @@ tests/test_download.py
42
42
  tests/test_download_maven.py
43
43
  tests/test_download_packagist.py
44
44
  tests/test_download_timeout.py
45
+ tests/test_download_version_attempts.py
45
46
  tests/test_download_version_hint.py
46
47
  tests/test_opossum.py
47
48
  tests/test_spdx.py
@@ -303,7 +303,7 @@ def test_timeout_stops_after_a_slow_package_lookup(tmp_path, monkeypatch, no_sys
303
303
  def git_failed(*args, **kwargs):
304
304
  return False, "git failed", "", "", ""
305
305
 
306
- def slow_lookup(link, checkout_to):
306
+ def slow_lookup(link, checkout_to, allow_latest=True):
307
307
  time.sleep(1.5)
308
308
  return True, link, "pkg", "1.0", "pypi"
309
309
 
@@ -0,0 +1,225 @@
1
+ # Copyright (c) 2026 LG Electronics Inc.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Tests for link-version then checkout-version download attempts."""
4
+
5
+ import logging
6
+
7
+ import pytest
8
+
9
+ from fosslight_util import _get_downloadable_url as downloadable_url
10
+ from fosslight_util import download as download_module
11
+
12
+
13
+ GO_LINK = (
14
+ "https://pkg.go.dev/github.com/DataDog/datadog-agent/"
15
+ "comp/core/tagger/origindetection/@0.77.0"
16
+ )
17
+ GO_BARE = (
18
+ "https://pkg.go.dev/github.com/DataDog/datadog-agent/"
19
+ "comp/core/tagger/origindetection"
20
+ )
21
+ GO_MODULE = (
22
+ "github.com/DataDog/datadog-agent/comp/core/tagger/origindetection"
23
+ )
24
+
25
+
26
+ class _FakeResponse:
27
+ def __init__(self, status_code=200, text="", payload=None):
28
+ self.status_code = status_code
29
+ self.text = text
30
+ self._payload = payload if payload is not None else {}
31
+
32
+ def json(self):
33
+ return self._payload
34
+
35
+
36
+ def test_go_proxy_escape_encodes_uppercase():
37
+ assert downloadable_url._go_proxy_escape(GO_MODULE) == (
38
+ "github.com/!data!dog/datadog-agent/comp/core/tagger/origindetection"
39
+ )
40
+
41
+
42
+ def test_split_pkg_link_version_reads_slash_at_version():
43
+ bare, version = downloadable_url.split_pkg_link_version(GO_LINK)
44
+ assert bare == GO_BARE
45
+ assert version == "0.77.0"
46
+
47
+
48
+ def test_split_pkg_link_version_reads_at_v_version():
49
+ bare, version = downloadable_url.split_pkg_link_version(
50
+ "https://pkg.go.dev/github.com/go-openapi/jsonreference@v0.20.2"
51
+ )
52
+ assert bare == "https://pkg.go.dev/github.com/go-openapi/jsonreference"
53
+ assert version == "0.20.2"
54
+
55
+
56
+ def test_split_pkg_link_version_keeps_url_without_version():
57
+ bare, version = downloadable_url.split_pkg_link_version(GO_BARE)
58
+ assert bare == GO_BARE
59
+ assert version == ""
60
+
61
+
62
+ def test_download_version_attempts_tries_link_then_checkout():
63
+ attempts = downloadable_url.download_version_attempts(GO_LINK, "0.77.0")
64
+ assert attempts == [
65
+ (GO_LINK, "", False),
66
+ (GO_BARE, "0.77.0", True),
67
+ ]
68
+
69
+
70
+ def test_download_version_attempts_single_try_without_embedded_version():
71
+ attempts = downloadable_url.download_version_attempts(
72
+ "https://github.com/foo/bar", "1.2.3"
73
+ )
74
+ assert attempts == [("https://github.com/foo/bar", "1.2.3", True)]
75
+
76
+
77
+ def test_go_version_exists_uses_proxy_case_encoding(monkeypatch):
78
+ seen = {}
79
+
80
+ def fake_get(url, timeout=5):
81
+ seen["url"] = url
82
+ return _FakeResponse(200, text="v0.76.0\nv0.77.0\n")
83
+
84
+ monkeypatch.setattr(downloadable_url.requests, "get", fake_get)
85
+ assert downloadable_url.version_exists("go", GO_MODULE, "0.77.0") is True
86
+ assert "!data!dog" in seen["url"]
87
+ assert seen["url"].endswith("/@v/list")
88
+
89
+
90
+ def test_go_zip_url_case_encodes_module(monkeypatch):
91
+ seen = {}
92
+
93
+ class _Response:
94
+ def getcode(self):
95
+ return 200
96
+
97
+ def fake_urlopen(url, timeout=None):
98
+ seen["url"] = url
99
+ return _Response()
100
+
101
+ monkeypatch.setattr(downloadable_url, "urlopen", fake_urlopen)
102
+ ok, link = downloadable_url.get_download_location_for_go(
103
+ "https://pkg.go.dev/" + GO_MODULE + "@v0.77.0"
104
+ )
105
+ assert ok is True
106
+ assert link == (
107
+ "https://proxy.golang.org/github.com/!data!dog/datadog-agent/"
108
+ "comp/core/tagger/origindetection/@v/v0.77.0.zip"
109
+ )
110
+ assert seen["url"] == link
111
+
112
+
113
+ def test_missing_link_version_is_not_replaced_when_latest_is_disabled(monkeypatch):
114
+ monkeypatch.setattr(downloadable_url, "version_exists", lambda *args, **kwargs: False)
115
+
116
+ def fail_latest(*args, **kwargs):
117
+ raise AssertionError("latest version must not be queried")
118
+
119
+ monkeypatch.setattr(downloadable_url, "get_latest_package_version", fail_latest)
120
+ _name, version, link, pkg_type = downloadable_url.extract_name_version_from_link(
121
+ GO_LINK, "", allow_latest=False
122
+ )
123
+ assert pkg_type == "go"
124
+ assert version == "0.77.0"
125
+ assert link.endswith("@v0.77.0")
126
+ assert "DataDog" in link
127
+
128
+
129
+ def test_missing_checkout_version_falls_back_to_latest(monkeypatch):
130
+ monkeypatch.setattr(downloadable_url, "version_exists", lambda *args, **kwargs: False)
131
+ monkeypatch.setattr(
132
+ downloadable_url,
133
+ "get_latest_package_version",
134
+ lambda *args, **kwargs: "9.9.9",
135
+ )
136
+ _name, version, link, _pkg = downloadable_url.extract_name_version_from_link(
137
+ GO_BARE, "0.1.0", allow_latest=True
138
+ )
139
+ assert version == "9.9.9"
140
+ assert link.endswith("@v9.9.9")
141
+
142
+
143
+ def test_cli_retries_checkout_after_link_version_fails(tmp_path, monkeypatch):
144
+ calls = []
145
+
146
+ def fake_git(git_url, target_dir, checkout_to="", *args, **kwargs):
147
+ calls.append(("git", git_url, checkout_to))
148
+ return False, "git failed", "", "", ""
149
+
150
+ def fake_wget(link, target_dir, compressed_only, checkout_to, size_limit_gb=None,
151
+ allow_latest=True):
152
+ calls.append(("wget", link, checkout_to, allow_latest))
153
+ if not allow_latest:
154
+ return False, "", "Not a downloadable link", "", "", ""
155
+ return True, str(tmp_path / "mod.zip"), "", "go:" + GO_MODULE, "0.77.0", link
156
+
157
+ monkeypatch.setattr(download_module, "download_git_clone", fake_git)
158
+ monkeypatch.setattr(download_module, "download_wget", fake_wget)
159
+ monkeypatch.setattr(download_module, "extract_compressed_file", lambda *args, **kwargs: True)
160
+ monkeypatch.setattr(
161
+ download_module,
162
+ "init_log",
163
+ lambda *args, **kwargs: (logging.getLogger("fosslight_download_test"), None),
164
+ )
165
+ target = tmp_path / "out"
166
+ target.mkdir()
167
+ kept = target / "kept.txt"
168
+ kept.write_text("keep")
169
+
170
+ success, msg, oss_name, oss_version, _clarified = download_module.cli_download_and_extract(
171
+ GO_LINK,
172
+ str(target),
173
+ str(tmp_path / "log"),
174
+ checkout_to="0.77.0",
175
+ called_cli=False,
176
+ )
177
+ assert kept.read_text() == "keep"
178
+
179
+ assert success is True
180
+ assert msg == ""
181
+ assert oss_version == "0.77.0"
182
+ assert oss_name == "go:" + GO_MODULE
183
+ assert calls == [
184
+ ("git", GO_LINK, ""),
185
+ ("wget", GO_LINK, "", False),
186
+ ("git", GO_BARE, "0.77.0"),
187
+ ("wget", GO_BARE, "0.77.0", True),
188
+ ]
189
+
190
+
191
+ def test_cli_does_not_retry_after_size_limit(tmp_path, monkeypatch):
192
+ calls = []
193
+
194
+ def fake_git(git_url, target_dir, checkout_to="", *args, **kwargs):
195
+ calls.append(checkout_to)
196
+ return False, "Download aborted due to size limit", "", "", ""
197
+
198
+ def fake_wget(*args, **kwargs):
199
+ raise AssertionError("wget must not run after a size-limit failure")
200
+
201
+ monkeypatch.setattr(download_module, "download_git_clone", fake_git)
202
+ monkeypatch.setattr(download_module, "download_wget", fake_wget)
203
+ monkeypatch.setattr(
204
+ download_module,
205
+ "init_log",
206
+ lambda *args, **kwargs: (logging.getLogger("fosslight_download_test"), None),
207
+ )
208
+
209
+ success, msg, *_rest = download_module.cli_download_and_extract(
210
+ GO_LINK,
211
+ str(tmp_path / "out"),
212
+ str(tmp_path / "log"),
213
+ checkout_to="0.77.0",
214
+ called_cli=False,
215
+ )
216
+
217
+ assert success is False
218
+ assert "size limit" in msg
219
+ assert calls == [""]
220
+
221
+
222
+ @pytest.mark.parametrize("checkout_to", ["", " "])
223
+ def test_download_version_attempts_without_checkout_is_one_try(checkout_to):
224
+ attempts = downloadable_url.download_version_attempts(GO_LINK, checkout_to)
225
+ assert attempts == [(GO_LINK, checkout_to, True)]
File without changes