fosslight-util 2.2.18__tar.gz → 2.2.20__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 (56) hide show
  1. {fosslight_util-2.2.18/src/fosslight_util.egg-info → fosslight_util-2.2.20}/PKG-INFO +1 -1
  2. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/pyproject.toml +1 -1
  3. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/_get_downloadable_url.py +121 -10
  4. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/download.py +105 -57
  5. {fosslight_util-2.2.18 → fosslight_util-2.2.20/src/fosslight_util.egg-info}/PKG-INFO +1 -1
  6. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util.egg-info/SOURCES.txt +2 -0
  7. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_download_timeout.py +1 -1
  8. fosslight_util-2.2.20/tests/test_download_user_agent.py +141 -0
  9. fosslight_util-2.2.20/tests/test_download_version_attempts.py +225 -0
  10. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/LICENSE +0 -0
  11. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/MANIFEST.in +0 -0
  12. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/README.md +0 -0
  13. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/setup.cfg +0 -0
  14. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/__init__.py +0 -0
  15. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/compare_yaml.py +0 -0
  16. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/constant.py +0 -0
  17. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/correct.py +0 -0
  18. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/cover.py +0 -0
  19. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/exclude.py +0 -0
  20. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/get_pom_license.py +0 -0
  21. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/help.py +0 -0
  22. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/oss_item.py +0 -0
  23. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/output_format.py +0 -0
  24. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/parsing_yaml.py +0 -0
  25. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/read_excel.py +0 -0
  26. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/resources/frequentLicenselist.json +0 -0
  27. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/resources/frequent_license_nick_list.json +0 -0
  28. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/resources/licenses.json +0 -0
  29. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/set_log.py +0 -0
  30. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/spdx_licenses.py +0 -0
  31. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/time.py +0 -0
  32. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/timer_thread.py +0 -0
  33. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/write_cyclonedx.py +0 -0
  34. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/write_excel.py +0 -0
  35. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/write_opossum.py +0 -0
  36. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/write_scancodejson.py +0 -0
  37. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/write_spdx.py +0 -0
  38. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/write_txt.py +0 -0
  39. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util/write_yaml.py +0 -0
  40. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util.egg-info/dependency_links.txt +0 -0
  41. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util.egg-info/entry_points.txt +0 -0
  42. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util.egg-info/requires.txt +0 -0
  43. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/src/fosslight_util.egg-info/top_level.txt +0 -0
  44. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_cyclonedx.py +0 -0
  45. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_decide_checkout.py +0 -0
  46. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_download.py +0 -0
  47. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_download_maven.py +0 -0
  48. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_download_packagist.py +0 -0
  49. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_download_version_hint.py +0 -0
  50. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_opossum.py +0 -0
  51. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_spdx.py +0 -0
  52. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_spdx_licenses.py +0 -0
  53. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_text.py +0 -0
  54. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_write_excel_hidden_sheet.py +0 -0
  55. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/tests/test_write_output.py +0 -0
  56. {fosslight_util-2.2.18 → fosslight_util-2.2.20}/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.20
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.20"
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
@@ -58,8 +61,10 @@ _active_download_alarm = ContextVar("active_download_alarm", default=None)
58
61
  _download_watchdog_owned = ContextVar("download_watchdog_owned", default=False)
59
62
 
60
63
  # Some mirrors (e.g. mirrors.ustc.edu.cn) return 403 for python-requests' default
61
- # User-Agent, or 200 with a small text/html interstitial. Start with a curl-style UA
62
- # (widely accepted for file downloads), then browser, then default requests as fallback.
64
+ # User-Agent, or 200 with a small text/html interstitial. Others (e.g.
65
+ # maven.egovframe.go.kr) return 400 Request Blocked for a non-browser User-Agent.
66
+ # Start with a curl-style UA (widely accepted for file downloads), then browser,
67
+ # then default requests as fallback.
63
68
  _HTTP_BROWSER_USER_AGENT = (
64
69
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
65
70
  "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
@@ -95,6 +100,15 @@ def _download_http_header_attempts():
95
100
  ]
96
101
 
97
102
 
103
+ def _status_retries_with_user_agent(status_code) -> bool:
104
+ """True when another User-Agent may pass a client block.
105
+
106
+ 403 is the usual block. Some hosts return 400 Request Blocked for a
107
+ non-browser User-Agent instead of 403.
108
+ """
109
+ return status_code in (400, 403)
110
+
111
+
98
112
  class Alarm(threading.Thread):
99
113
  """Download watchdog; call ``cancel()`` to stop before timeout.
100
114
 
@@ -226,7 +240,7 @@ def _shutdown_response_socket(response):
226
240
 
227
241
 
228
242
  def is_downloadable(url):
229
- """Probe URL; retry with alternate User-Agents on 403 or HTML body for archive URLs."""
243
+ """Probe URL; retry with alternate User-Agents on 400/403 or HTML for archives."""
230
244
  attempts = _download_http_header_attempts()
231
245
  last_i = len(attempts) - 1
232
246
  for i, headers in enumerate(attempts):
@@ -234,7 +248,7 @@ def is_downloadable(url):
234
248
  with requests.get(
235
249
  url, stream=True, allow_redirects=True, timeout=10, headers=headers
236
250
  ) as r:
237
- if r.status_code == 403 and i < last_i:
251
+ if _status_retries_with_user_agent(r.status_code) and i < last_i:
238
252
  continue
239
253
  if r.status_code >= 400:
240
254
  return False
@@ -370,6 +384,7 @@ def cli_download_and_extract(link: str, target_dir: str, log_dir: str, checkout_
370
384
  logger, log_item = init_log(os.path.join(log_dir, log_file_name))
371
385
  link = link.strip()
372
386
  is_rubygems = False
387
+ link_version_failure = ""
373
388
  # One overall deadline for the whole download: git clone, then HTTP/wget.
374
389
  owner = _enter_download_watchdog(timeout, new_operation=True)
375
390
 
@@ -389,51 +404,76 @@ def cli_download_and_extract(link: str, target_dir: str, log_dir: str, checkout_
389
404
  tag = ''.join(src_info.get("tag", "")).split('=')[-1]
390
405
  branch = ''.join(src_info.get("branch", "")).split('=')[-1]
391
406
  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
407
+ attempts = download_version_attempts(link, checkout_to)
408
+
409
+ for attempt_index, (attempt_link, attempt_checkout, allow_latest) in enumerate(attempts):
410
+ if attempt_index:
411
+ parts = []
412
+ if msg:
413
+ parts.append(f"git fail: {msg}")
414
+ if msg_wget:
415
+ parts.append(f"wget fail: {msg_wget}")
416
+ link_version_failure = ", ".join(parts)
417
+ logger.info(
418
+ "Link version download failed; retry with checkout version "
419
+ f"{attempt_checkout}. {link_version_failure}"
420
+ )
421
+ success = True
422
+ msg = ""
423
+ msg_wget = ""
424
+ oss_name = ""
425
+ oss_version = ""
426
+ clarified_from_git = ""
427
+ downloaded_link = ""
428
+ size_limit_blocked = False
429
+
430
+ # General download: git clone → requests → system wget
431
+ success_git, msg, oss_name, oss_version, clarified_from_git = download_git_clone(
432
+ attempt_link, target_dir, attempt_checkout, tag, branch,
433
+ ssh_key, id, git_token, called_cli, size_limit_gb=size_limit_gb)
434
+ link = change_ssh_link_to_https(attempt_link)
435
+ if success_git:
436
+ downloaded_link = link
437
+ success = True
438
+ size_limit_blocked = _is_size_limit_block_message(msg)
439
+ if size_limit_blocked:
411
440
  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
441
+ elif (not is_rubygems) and (not success_git):
442
+ success, downloaded_file, msg_wget, oss_name, oss_version, resolved_link = download_wget(
443
+ link, target_dir, compressed_only, attempt_checkout,
444
+ size_limit_gb=size_limit_gb,
445
+ allow_latest=allow_latest,
416
446
  )
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}"
447
+ if _is_size_limit_block_message(msg_wget):
448
+ size_limit_blocked = True
449
+ success = False
450
+ msg = msg_wget
451
+ elif success and downloaded_file:
452
+ success = extract_compressed_file(
453
+ downloaded_file, target_dir, True, compressed_only
423
454
  )
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
455
+ if success:
456
+ downloaded_link = resolved_link
457
+ else:
458
+ # Extract failed (e.g. non-archive when compressed_only): fail
459
+ msg_wget = (
460
+ f"Failed to extract downloaded file: {downloaded_file}"
461
+ )
462
+ try:
463
+ if os.path.isfile(downloaded_file):
464
+ os.remove(downloaded_file)
465
+ except OSError:
466
+ pass
467
+ # Download from rubygems.org
468
+ elif is_rubygems and shutil.which("gem"):
469
+ _raise_if_download_timed_out()
470
+ success = gem_download(link, target_dir, attempt_checkout)
471
+ # Do not accept a gem that finished, or was stopped, after the deadline.
472
+ _raise_if_download_timed_out()
473
+ if success:
474
+ downloaded_link = link
475
+ if success or size_limit_blocked:
476
+ break
437
477
  if size_limit_blocked:
438
478
  # Keep a clear size-limit message for callers/UI (do not wrap as git/wget fail)
439
479
  pass
@@ -448,6 +488,8 @@ def cli_download_and_extract(link: str, target_dir: str, log_dir: str, checkout_
448
488
  msg = f'{msg}, wget fail: {msg_wget}'
449
489
  elif msg_wget:
450
490
  msg = f'wget fail: {msg_wget}'
491
+ if link_version_failure and not success and not size_limit_blocked and msg:
492
+ msg = f"link version failed ({link_version_failure}); {msg}"
451
493
 
452
494
  except Exception as error:
453
495
  success = False
@@ -1263,7 +1305,10 @@ def _download_with_system_wget(url, target_dir, size_limit_gb=None):
1263
1305
  # Before download: best-effort Content-Length check
1264
1306
  try:
1265
1307
  head = requests.head(
1266
- url, timeout=_download_request_timeout(10), allow_redirects=True
1308
+ url,
1309
+ timeout=_download_request_timeout(10),
1310
+ allow_redirects=True,
1311
+ headers={"User-Agent": _HTTP_BROWSER_USER_AGENT, "Accept": "*/*"},
1267
1312
  )
1268
1313
  if head.status_code < 400:
1269
1314
  _raise_if_content_length_over_limit(
@@ -1288,6 +1333,8 @@ def _download_with_system_wget(url, target_dir, size_limit_gb=None):
1288
1333
  "--tries=20",
1289
1334
  "--timeout=60",
1290
1335
  "--waitretry=5",
1336
+ "--user-agent",
1337
+ _HTTP_BROWSER_USER_AGENT,
1291
1338
  "-c",
1292
1339
  "-P", str(target_dir),
1293
1340
  url,
@@ -1355,7 +1402,8 @@ def _download_with_system_wget(url, target_dir, size_limit_gb=None):
1355
1402
  return local_path
1356
1403
 
1357
1404
 
1358
- def download_wget(link, target_dir, compressed_only, checkout_to, size_limit_gb=None):
1405
+ def download_wget(link, target_dir, compressed_only, checkout_to, size_limit_gb=None,
1406
+ allow_latest=True):
1359
1407
  success = False
1360
1408
  msg = ""
1361
1409
  oss_name = ""
@@ -1369,7 +1417,9 @@ def download_wget(link, target_dir, compressed_only, checkout_to, size_limit_gb=
1369
1417
 
1370
1418
  # The git step may have used up the time; the lookup below may use up the rest.
1371
1419
  _raise_if_download_timed_out()
1372
- ret, new_link, oss_name, oss_version, pkg_type = get_downloadable_url(link, checkout_to)
1420
+ ret, new_link, oss_name, oss_version, pkg_type = get_downloadable_url(
1421
+ link, checkout_to, allow_latest=allow_latest
1422
+ )
1373
1423
  _raise_if_download_timed_out()
1374
1424
  if ret and new_link:
1375
1425
  link = new_link
@@ -1574,7 +1624,7 @@ def _download_file_once(url, target_dir, request_headers=None, size_limit_gb=Non
1574
1624
 
1575
1625
 
1576
1626
  def download_file(url, target_dir, size_limit_gb=None):
1577
- """Download via HTTP(S); retry on 403 or HTML interstitial for archive URLs."""
1627
+ """Download via HTTP(S); retry on 400/403 or HTML interstitial for archives."""
1578
1628
  attempts = _download_http_header_attempts()
1579
1629
  last_i = len(attempts) - 1
1580
1630
  for i, req_headers in enumerate(attempts):
@@ -1585,13 +1635,11 @@ def download_file(url, target_dir, size_limit_gb=None):
1585
1635
  except (SizeLimitExceeded, TimeOutException):
1586
1636
  raise
1587
1637
  except requests.exceptions.HTTPError as e:
1588
- if (
1589
- e.response is not None
1590
- and e.response.status_code == 403
1591
- and i < last_i
1592
- ):
1638
+ status_code = e.response.status_code if e.response is not None else None
1639
+ if _status_retries_with_user_agent(status_code) and i < last_i:
1593
1640
  logger.info(
1594
- "download_file: HTTP 403; retrying with alternate User-Agent"
1641
+ "download_file: HTTP %s; retrying with alternate User-Agent",
1642
+ status_code,
1595
1643
  )
1596
1644
  continue
1597
1645
  logger.warning(f"download_file - failed: {e}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fosslight_util
3
- Version: 2.2.18
3
+ Version: 2.2.20
4
4
  Summary: FOSSLight Util
5
5
  Author: LG Electronics
6
6
  License-Expression: Apache-2.0
@@ -42,6 +42,8 @@ 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_user_agent.py
46
+ tests/test_download_version_attempts.py
45
47
  tests/test_download_version_hint.py
46
48
  tests/test_opossum.py
47
49
  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,141 @@
1
+ # Copyright (c) 2026 LG Electronics Inc.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """User-Agent retry when a host blocks non-browser clients with HTTP 400."""
4
+
5
+ import requests
6
+
7
+ import fosslight_util.download as download
8
+
9
+ _JAR_URL = (
10
+ "https://maven.egovframe.go.kr/maven/org/egovframe/rte/"
11
+ "org.egovframe.rte.fdl.cmmn/4.1.0/org.egovframe.rte.fdl.cmmn-4.1.0.jar"
12
+ )
13
+
14
+
15
+ class _Response:
16
+ def __init__(self, status_code, body=b"PK\x03\x04", headers=None):
17
+ self.status_code = status_code
18
+ self._body = body
19
+ self.headers = headers or {"content-type": "application/java-archive"}
20
+ self.url = _JAR_URL
21
+
22
+ def raise_for_status(self):
23
+ if self.status_code >= 400:
24
+ raise requests.HTTPError(response=self)
25
+
26
+ def iter_content(self, chunk_size=8192):
27
+ yield self._body
28
+
29
+ def __enter__(self):
30
+ return self
31
+
32
+ def __exit__(self, exc_type, exc, tb):
33
+ return False
34
+
35
+
36
+ def _user_agent(kwargs):
37
+ headers = kwargs.get("headers") or {}
38
+ return headers.get("User-Agent")
39
+
40
+
41
+ def test_download_file_retries_http_400_with_browser_user_agent(tmp_path, monkeypatch):
42
+ seen = []
43
+
44
+ def fake_head(url, **kwargs):
45
+ seen.append(("head", _user_agent(kwargs)))
46
+ status = 400 if _user_agent(kwargs) == download._HTTP_CURL_LIKE_USER_AGENT else 200
47
+ return _Response(status)
48
+
49
+ def fake_get(url, **kwargs):
50
+ seen.append(("get", _user_agent(kwargs)))
51
+ status = 400 if _user_agent(kwargs) == download._HTTP_CURL_LIKE_USER_AGENT else 200
52
+ return _Response(status, body=b"PK\x03\x04jar")
53
+
54
+ monkeypatch.setattr(download.requests, "head", fake_head)
55
+ monkeypatch.setattr(download.requests, "get", fake_get)
56
+
57
+ path = download.download_file(_JAR_URL, str(tmp_path))
58
+
59
+ assert path is not None
60
+ with open(path, "rb") as downloaded:
61
+ assert downloaded.read() == b"PK\x03\x04jar"
62
+ assert seen == [
63
+ ("head", download._HTTP_CURL_LIKE_USER_AGENT),
64
+ ("get", download._HTTP_CURL_LIKE_USER_AGENT),
65
+ ("head", download._HTTP_BROWSER_USER_AGENT),
66
+ ("get", download._HTTP_BROWSER_USER_AGENT),
67
+ ]
68
+
69
+
70
+ def test_download_file_does_not_retry_http_404(tmp_path, monkeypatch):
71
+ seen = []
72
+
73
+ def fake_head(url, **kwargs):
74
+ seen.append("head")
75
+ return _Response(404)
76
+
77
+ def fake_get(url, **kwargs):
78
+ seen.append("get")
79
+ return _Response(404)
80
+
81
+ monkeypatch.setattr(download.requests, "head", fake_head)
82
+ monkeypatch.setattr(download.requests, "get", fake_get)
83
+
84
+ assert download.download_file(_JAR_URL, str(tmp_path)) is None
85
+ assert seen == ["head", "get"]
86
+
87
+
88
+ def test_is_downloadable_retries_http_400(monkeypatch):
89
+ seen = []
90
+
91
+ def fake_get(url, **kwargs):
92
+ ua = _user_agent(kwargs)
93
+ seen.append(ua)
94
+ status = 400 if ua == download._HTTP_CURL_LIKE_USER_AGENT else 200
95
+ return _Response(status)
96
+
97
+ monkeypatch.setattr(download.requests, "get", fake_get)
98
+
99
+ assert download.is_downloadable(_JAR_URL) is True
100
+ assert seen == [
101
+ download._HTTP_CURL_LIKE_USER_AGENT,
102
+ download._HTTP_BROWSER_USER_AGENT,
103
+ ]
104
+
105
+
106
+ def test_system_wget_sends_browser_user_agent(tmp_path, monkeypatch):
107
+ captured = {}
108
+
109
+ class _Proc:
110
+ returncode = 0
111
+
112
+ def poll(self):
113
+ return 0
114
+
115
+ def communicate(self):
116
+ return ("", "")
117
+
118
+ def fake_popen(cmd, **kwargs):
119
+ captured["cmd"] = cmd
120
+ (tmp_path / "org.egovframe.rte.fdl.cmmn-4.1.0.jar").write_bytes(b"PK")
121
+ return _Proc()
122
+
123
+ class _Head:
124
+ status_code = 200
125
+ headers = {}
126
+
127
+ def fake_head(url, **kwargs):
128
+ captured["head_headers"] = kwargs.get("headers")
129
+ return _Head()
130
+
131
+ monkeypatch.setattr(download.shutil, "which", lambda name: "/usr/bin/wget")
132
+ monkeypatch.setattr(download.requests, "head", fake_head)
133
+ monkeypatch.setattr(download.subprocess, "Popen", fake_popen)
134
+
135
+ path = download._download_with_system_wget(_JAR_URL, str(tmp_path))
136
+
137
+ assert path.endswith("org.egovframe.rte.fdl.cmmn-4.1.0.jar")
138
+ cmd = captured["cmd"]
139
+ agent_index = cmd.index("--user-agent")
140
+ assert cmd[agent_index + 1] == download._HTTP_BROWSER_USER_AGENT
141
+ assert captured["head_headers"]["User-Agent"] == download._HTTP_BROWSER_USER_AGENT
@@ -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