Skip to content

Commit 2cbbdb0

Browse files
authored
Merge pull request #168 from fosslight/develop
Improve Java version detection logic
2 parents 2bfcf7e + 55ba616 commit 2cbbdb0

1 file changed

Lines changed: 43 additions & 5 deletions

File tree

src/fosslight_binary/binary_analysis.py

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -358,12 +358,50 @@ def check_binary(file_with_path):
358358
def get_java_version():
359359
try:
360360
completed = subprocess.run(["java", "-version"], capture_output=True, text=True)
361-
first_line = (completed.stderr or completed.stdout).splitlines()[0]
361+
# Java typically writes version to stderr, but some envs print notices first.
362+
output = (completed.stderr or "") + "\n" + (completed.stdout or "")
363+
lines = [ln.strip() for ln in output.splitlines() if ln.strip()]
364+
365+
# Look for the first line that resembles a version string.
366+
version_num = None
367+
for ln in lines:
368+
# Skip known non-version notices
369+
if ln.lower().startswith("picked up _java_options"):
370+
continue
371+
372+
m = re.search(r'version\s+"([^"]+)"', ln, re.IGNORECASE)
373+
if not m:
374+
# Some JREs may print like: openjdk 17 2021-09-14 (no "version")
375+
m2 = re.search(r'\b(?:openjdk|java)\b\s+([0-9][^\s"]*)', ln, re.IGNORECASE)
376+
if m2:
377+
ver = m2.group(1)
378+
else:
379+
continue
380+
else:
381+
ver = m.group(1)
382+
383+
# Normalize to major version integer
384+
# If starts with "1." (Java 8 and earlier), major is the next number (e.g., 1.8 -> 8)
385+
try:
386+
if ver.startswith("1."):
387+
parts = re.split(r'[._-]', ver)
388+
if len(parts) >= 2 and parts[1].isdigit():
389+
version_num = int(parts[1])
390+
else:
391+
# Fallback: extract first digit after 1.
392+
m3 = re.search(r'^1\.(\d+)', ver)
393+
version_num = int(m3.group(1)) if m3 else None
394+
else:
395+
# For 11+, take leading integer
396+
m4 = re.search(r'^(\d+)', ver)
397+
version_num = int(m4.group(1)) if m4 else None
398+
except Exception:
399+
version_num = None
362400

363-
m = re.search(r'"(\d+)', first_line)
364-
if not m:
365-
return None
366-
return int(m.group(1))
401+
if version_num is not None:
402+
return version_num
403+
404+
return None
367405
except Exception:
368406
return None
369407

0 commit comments

Comments
 (0)