You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by gn...@apache.org on 2026/08/06 08:53:20 UTC

(maven) 04/14: Add lazy JDK discovery from filesystem for auto-selection fallback

This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch fix-module-name-strategy
in repository https://gitbox.apache.org/repos/asf/maven.git

commit a800a88ca0b81b74854418d735afc0ca6ed20b12
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Fri Jul 31 10:46:19 2026 +0200

    Add lazy JDK discovery from filesystem for auto-selection fallback
    
    When no compatible JDK is found in toolchains.xml, Maven now lazily
    discovers JDKs from the filesystem by scanning well-known locations:
    JAVA*_HOME env vars, SDKMan, IntelliJ .jdks/, Gradle, jEnv, JBang,
    asdf, mise, and OS-specific paths (/usr/lib/jvm, etc.).
    
    Discovery only runs on the failure path (running JDK incompatible
    AND no configured toolchain matches), so normal builds pay zero cost.
    JDK version is read from the release file (no java process spawned).
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
 .../apache/maven/impl/DefaultToolchainManager.java |  76 +++--
 .../apache/maven/impl/JdkSourceLevelSupport.java   |  22 +-
 .../apache/maven/impl/JdkToolchainDiscoverer.java  | 310 +++++++++++++++++++++
 .../maven/impl/JdkToolchainDiscovererTest.java     | 180 ++++++++++++
 4 files changed, 566 insertions(+), 22 deletions(-)

diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultToolchainManager.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultToolchainManager.java
index 88430004eb..45df52a465 100644
--- a/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultToolchainManager.java
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultToolchainManager.java
@@ -51,18 +51,35 @@
 @Singleton
 public class DefaultToolchainManager implements ToolchainManager {
     private final Map<String, ToolchainFactory> factories;
+    private final JdkToolchainDiscoverer discoverer;
     private final Logger logger;
 
     @Inject
-    public DefaultToolchainManager(Map<String, ToolchainFactory> factories) {
-        this(factories, null);
+    public DefaultToolchainManager(Map<String, ToolchainFactory> factories, JdkToolchainDiscoverer discoverer) {
+        this(factories, discoverer, null);
     }
 
     /**
-     * Used for tests only
+     * Used for tests only (no discoverer)
+     */
+    protected DefaultToolchainManager(Map<String, ToolchainFactory> factories) {
+        this(factories, null, null);
+    }
+
+    /**
+     * Used for tests only (no discoverer, custom logger)
      */
     protected DefaultToolchainManager(Map<String, ToolchainFactory> factories, Logger logger) {
+        this(factories, null, logger);
+    }
+
+    /**
+     * Used for tests only (full control)
+     */
+    protected DefaultToolchainManager(
+            Map<String, ToolchainFactory> factories, JdkToolchainDiscoverer discoverer, Logger logger) {
         this.factories = factories;
+        this.discoverer = discoverer;
         this.logger = logger != null ? logger : LoggerFactory.getLogger(DefaultToolchainManager.class);
     }
 
@@ -119,8 +136,9 @@ public void storeToolchainToBuildContext(@Nonnull Session session, @Nonnull Tool
      * Attempts to automatically select a JDK toolchain when the running JDK
      * does not support the project's required {@code --source}/{@code --release} level.
      * <p>
-     * Searches configured toolchains for the newest JDK that supports the required
-     * source level. If found, emits a warning and returns it.
+     * First searches configured toolchains (from {@code toolchains.xml}), then falls back
+     * to lazy filesystem discovery. Normal builds pay zero cost — discovery only runs
+     * when the running JDK is incompatible and no configured toolchain matches.
      */
     Optional<Toolchain> autoSelectJdkToolchain(Session session) {
         int requiredSourceLevel = getProjectRequiredSourceLevel(session);
@@ -138,22 +156,19 @@ Optional<Toolchain> autoSelectJdkToolchain(Session session) {
             return Optional.empty();
         }
 
-        // Search available toolchains for a compatible JDK, preferring the newest
-        List<Toolchain> allToolchains = getToolchains(session, "jdk", null);
-        Toolchain bestMatch = null;
-        int bestVersion = 0;
+        // 1. Search configured toolchains (from toolchains.xml)
+        List<Toolchain> configuredToolchains = getToolchains(session, "jdk", null);
+        Toolchain bestMatch = findNewestCompatible(configuredToolchains, requiredSourceLevel);
 
-        for (Toolchain tc : allToolchains) {
-            if (tc instanceof JavaToolchain jtc && jtc.getJavaVersion() != null) {
-                int tcMajor = JdkSourceLevelSupport.normalizeSourceLevel(
-                        jtc.getJavaVersion().toString());
-                if (tcMajor > 0 && JdkSourceLevelSupport.supportsSourceLevel(tcMajor, requiredSourceLevel)) {
-                    if (tcMajor > bestVersion) {
-                        bestVersion = tcMajor;
-                        bestMatch = tc;
-                    }
-                }
-            }
+        // 2. Fall back to lazy filesystem discovery
+        if (bestMatch == null && discoverer != null) {
+            logger.debug("No compatible JDK in configured toolchains, discovering JDKs from filesystem...");
+            List<ToolchainModel> discoveredModels = discoverer.discoverToolchains();
+            List<Toolchain> discoveredToolchains = discoveredModels.stream()
+                    .map(this::createToolchain)
+                    .flatMap(Optional::stream)
+                    .toList();
+            bestMatch = findNewestCompatible(discoveredToolchains, requiredSourceLevel);
         }
 
         if (bestMatch != null) {
@@ -174,6 +189,27 @@ Optional<Toolchain> autoSelectJdkToolchain(Session session) {
         return Optional.empty();
     }
 
+    /**
+     * Finds the newest JDK toolchain that supports the given source level.
+     */
+    private Toolchain findNewestCompatible(List<Toolchain> toolchains, int requiredSourceLevel) {
+        Toolchain bestMatch = null;
+        int bestVersion = 0;
+        for (Toolchain tc : toolchains) {
+            if (tc instanceof JavaToolchain jtc && jtc.getJavaVersion() != null) {
+                int tcMajor = JdkSourceLevelSupport.normalizeSourceLevel(
+                        jtc.getJavaVersion().toString());
+                if (tcMajor > 0 && JdkSourceLevelSupport.supportsSourceLevel(tcMajor, requiredSourceLevel)) {
+                    if (tcMajor > bestVersion) {
+                        bestVersion = tcMajor;
+                        bestMatch = tc;
+                    }
+                }
+            }
+        }
+        return bestMatch;
+    }
+
     /**
      * Reads the project's required source level from either Model 4.1.0
      * {@code <source><targetVersion>} elements or legacy properties
diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/JdkSourceLevelSupport.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/JdkSourceLevelSupport.java
index 30a1fecac4..3ae3878d0d 100644
--- a/impl/maven-impl/src/main/java/org/apache/maven/impl/JdkSourceLevelSupport.java
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/JdkSourceLevelSupport.java
@@ -85,10 +85,16 @@ static int normalizeSourceLevel(String version) {
             return -1;
         }
         version = version.trim();
-        // Handle "1.x" legacy format (e.g., "1.5", "1.8")
+        // Handle "1.x" legacy format (e.g., "1.5", "1.8", "1.8.0_392")
         if (version.startsWith("1.") && version.length() > 2) {
+            String rest = version.substring(2);
+            // Strip any trailing qualifiers (e.g. "8.0_392" → "8")
+            int sep = indexOfNonDigit(rest);
+            if (sep > 0) {
+                rest = rest.substring(0, sep);
+            }
             try {
-                return Integer.parseInt(version.substring(2));
+                return Integer.parseInt(rest);
             } catch (NumberFormatException e) {
                 return -1;
             }
@@ -105,6 +111,18 @@ static int normalizeSourceLevel(String version) {
         }
     }
 
+    /**
+     * Returns the index of the first non-digit character in the string, or -1 if all characters are digits.
+     */
+    private static int indexOfNonDigit(String s) {
+        for (int i = 0; i < s.length(); i++) {
+            if (!Character.isDigit(s.charAt(i))) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
     /**
      * Returns the major version of the currently running JDK.
      *
diff --git a/impl/maven-impl/src/main/java/org/apache/maven/impl/JdkToolchainDiscoverer.java b/impl/maven-impl/src/main/java/org/apache/maven/impl/JdkToolchainDiscoverer.java
new file mode 100644
index 0000000000..78524a7e6c
--- /dev/null
+++ b/impl/maven-impl/src/main/java/org/apache/maven/impl/JdkToolchainDiscoverer.java
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.impl;
+
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import org.apache.maven.api.di.Named;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.toolchain.ToolchainModel;
+import org.apache.maven.api.xml.XmlNode;
+import org.apache.maven.impl.util.Os;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Discovers JDK installations on the local filesystem by scanning well-known
+ * directories, environment variables, and tool manager locations.
+ * <p>
+ * This is used by {@link DefaultToolchainManager} as a lazy fallback when auto-selection
+ * needs a compatible JDK but none are configured in {@code toolchains.xml}.
+ * Discovery only runs when the running JDK cannot compile the project's source level
+ * and no configured toolchain matches — normal builds pay zero cost.
+ * <p>
+ * JDK version is read from the {@code release} file present in every JDK since Java 9
+ * (and backported to JDK 8u updates), avoiding the need to execute {@code java} processes.
+ */
+@Named
+@Singleton
+public class JdkToolchainDiscoverer {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(JdkToolchainDiscoverer.class);
+
+    private volatile List<ToolchainModel> cachedToolchains;
+
+    /**
+     * Returns discovered JDK toolchain models. Results are cached after first invocation.
+     */
+    public List<ToolchainModel> discoverToolchains() {
+        List<ToolchainModel> result = cachedToolchains;
+        if (result == null) {
+            synchronized (this) {
+                result = cachedToolchains;
+                if (result == null) {
+                    result = doDiscover();
+                    cachedToolchains = result;
+                }
+            }
+        }
+        return result;
+    }
+
+    private List<ToolchainModel> doDiscover() {
+        Set<Path> candidates = new LinkedHashSet<>();
+        collectFromEnvironment(candidates);
+        collectFromToolManagers(candidates);
+        collectFromSystemDirectories(candidates);
+
+        List<ToolchainModel> toolchains = new ArrayList<>();
+        for (Path candidate : candidates) {
+            try {
+                Path jdkHome = resolveJdkHome(candidate);
+                if (jdkHome != null && isValidJdkHome(jdkHome)) {
+                    Optional<ToolchainModel> model = buildToolchainModel(jdkHome);
+                    model.ifPresent(toolchains::add);
+                }
+            } catch (Exception e) {
+                LOGGER.debug("Skipping JDK candidate {}: {}", candidate, e.getMessage());
+            }
+        }
+
+        LOGGER.debug("Discovered {} JDK installation(s) on the filesystem", toolchains.size());
+        return List.copyOf(toolchains);
+    }
+
+    /**
+     * Collects JDK candidates from environment variables matching {@code JAVA*_HOME}.
+     */
+    void collectFromEnvironment(Set<Path> candidates) {
+        // Current JDK
+        String javaHome = System.getProperty("java.home");
+        if (javaHome != null) {
+            addCandidate(candidates, Paths.get(javaHome));
+        }
+
+        // JAVA*_HOME env vars (e.g. JAVA11_HOME, JAVA17_HOME)
+        for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
+            String name = entry.getKey();
+            if (name.startsWith("JAVA") && name.endsWith("_HOME")) {
+                addCandidate(candidates, Paths.get(entry.getValue()));
+            }
+        }
+
+        // JAVA_HOME
+        String envJavaHome = System.getenv("JAVA_HOME");
+        if (envJavaHome != null) {
+            addCandidate(candidates, Paths.get(envJavaHome));
+        }
+    }
+
+    /**
+     * Collects JDK candidates from common tool manager directories under the user's home.
+     */
+    void collectFromToolManagers(Set<Path> candidates) {
+        Path userHome = Paths.get(System.getProperty("user.home"));
+
+        // IntelliJ IDEA / common
+        scanSubdirectories(candidates, userHome.resolve(".jdks"));
+        // Maven-managed JDKs
+        scanSubdirectories(candidates, userHome.resolve(".m2").resolve("jdks"));
+        // SDKMAN
+        scanSubdirectories(
+                candidates, userHome.resolve(".sdkman").resolve("candidates").resolve("java"));
+        // Gradle
+        scanSubdirectories(candidates, userHome.resolve(".gradle").resolve("jdks"));
+        // jEnv
+        scanSubdirectories(candidates, userHome.resolve(".jenv").resolve("versions"));
+        // JBang
+        scanSubdirectories(
+                candidates, userHome.resolve(".jbang").resolve("cache").resolve("jdks"));
+        // asdf
+        scanSubdirectories(
+                candidates, userHome.resolve(".asdf").resolve("installs").resolve("java"));
+        // Jabba
+        scanSubdirectories(candidates, userHome.resolve(".jabba").resolve("jdk"));
+        // mise (formerly rtx)
+        scanSubdirectories(
+                candidates,
+                userHome.resolve(".local")
+                        .resolve("share")
+                        .resolve("mise")
+                        .resolve("installs")
+                        .resolve("java"));
+    }
+
+    /**
+     * Collects JDK candidates from OS-specific system directories.
+     */
+    void collectFromSystemDirectories(Set<Path> candidates) {
+        if (Os.IS_WINDOWS) {
+            collectWindowsDirectories(candidates);
+        } else if (Os.isFamily("mac")) {
+            collectMacDirectories(candidates);
+        } else {
+            collectLinuxDirectories(candidates);
+        }
+    }
+
+    private void collectLinuxDirectories(Set<Path> candidates) {
+        scanSubdirectories(candidates, Paths.get("/usr/lib/jvm"));
+        scanSubdirectories(candidates, Paths.get("/usr/lib64/jvm"));
+        scanSubdirectories(candidates, Paths.get("/usr/jdk"));
+        scanSubdirectories(candidates, Paths.get("/usr/java"));
+        scanSubdirectories(candidates, Paths.get("/usr/local/java"));
+        scanSubdirectories(candidates, Paths.get("/opt/java"));
+        scanSubdirectories(candidates, Paths.get("/opt/hostedtoolcache"));
+    }
+
+    private void collectMacDirectories(Set<Path> candidates) {
+        Path userHome = Paths.get(System.getProperty("user.home"));
+        scanSubdirectories(candidates, Paths.get("/Library/Java/JavaVirtualMachines"));
+        scanSubdirectories(
+                candidates, userHome.resolve("Library").resolve("Java").resolve("JavaVirtualMachines"));
+    }
+
+    private void collectWindowsDirectories(Set<Path> candidates) {
+        Path progFiles = Paths.get("C:\\Program Files");
+        scanSubdirectories(candidates, progFiles.resolve("Java"));
+        scanSubdirectories(candidates, progFiles.resolve("Eclipse Adoptium"));
+        scanSubdirectories(candidates, progFiles.resolve("Zulu"));
+        scanSubdirectories(candidates, progFiles.resolve("Amazon Corretto"));
+        scanSubdirectories(candidates, progFiles.resolve("BellSoft"));
+        // Scoop
+        Path userHome = Paths.get(System.getProperty("user.home"));
+        scanSubdirectories(candidates, userHome.resolve("scoop").resolve("apps"));
+    }
+
+    /**
+     * Lists immediate subdirectories of the given directory and adds them as candidates.
+     */
+    private void scanSubdirectories(Set<Path> candidates, Path directory) {
+        if (!Files.isDirectory(directory)) {
+            return;
+        }
+        try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, Files::isDirectory)) {
+            for (Path child : stream) {
+                addCandidate(candidates, child);
+            }
+        } catch (IOException e) {
+            LOGGER.debug("Cannot scan directory {}: {}", directory, e.getMessage());
+        }
+    }
+
+    private void addCandidate(Set<Path> candidates, Path path) {
+        try {
+            candidates.add(path.toRealPath());
+        } catch (IOException e) {
+            // Broken symlink or inaccessible — add normalized path as fallback
+            candidates.add(path.normalize().toAbsolutePath());
+        }
+    }
+
+    /**
+     * Resolves the actual JDK home from a candidate path.
+     * On macOS, JDKs may be nested under {@code Contents/Home}.
+     */
+    Path resolveJdkHome(Path candidate) {
+        if (isValidJdkHome(candidate)) {
+            return candidate;
+        }
+        // macOS bundle layout: /path/to/jdk-17.jdk/Contents/Home
+        Path contentsHome = candidate.resolve("Contents").resolve("Home");
+        if (isValidJdkHome(contentsHome)) {
+            return contentsHome;
+        }
+        return null;
+    }
+
+    /**
+     * Checks if a directory is a valid JDK home by looking for {@code bin/javac}.
+     */
+    boolean isValidJdkHome(Path jdkHome) {
+        Path bin = jdkHome.resolve("bin");
+        return Files.exists(bin.resolve("javac")) || Files.exists(bin.resolve("javac.exe"));
+    }
+
+    /**
+     * Builds a {@link ToolchainModel} from a validated JDK home by reading the {@code release} file.
+     *
+     * @return the model, or empty if the version cannot be determined
+     */
+    Optional<ToolchainModel> buildToolchainModel(Path jdkHome) {
+        String version = readVersionFromRelease(jdkHome);
+        if (version == null) {
+            LOGGER.debug("Cannot determine version for JDK at {}, skipping", jdkHome);
+            return Optional.empty();
+        }
+
+        int majorVersion = JdkSourceLevelSupport.normalizeSourceLevel(version);
+        if (majorVersion <= 0) {
+            LOGGER.debug("Cannot parse major version from '{}' for JDK at {}, skipping", version, jdkHome);
+            return Optional.empty();
+        }
+
+        XmlNode jdkHomeNode = XmlNode.newInstance("jdkHome", jdkHome.toString());
+        XmlNode configuration = XmlNode.newInstance("configuration", List.of(jdkHomeNode));
+
+        ToolchainModel model = ToolchainModel.newBuilder()
+                .type("jdk")
+                .provides(Map.of("version", String.valueOf(majorVersion)))
+                .configuration(configuration)
+                .build();
+
+        LOGGER.debug("Discovered JDK {} at {}", majorVersion, jdkHome);
+        return Optional.of(model);
+    }
+
+    /**
+     * Reads the {@code JAVA_VERSION} property from the JDK's {@code release} file.
+     * The release file format uses shell-style assignments: {@code JAVA_VERSION="17.0.2"}.
+     *
+     * @return the version string (e.g. "17.0.2"), or null if not found
+     */
+    String readVersionFromRelease(Path jdkHome) {
+        Path releaseFile = jdkHome.resolve("release");
+        if (!Files.exists(releaseFile)) {
+            return null;
+        }
+        try {
+            for (String line : Files.readAllLines(releaseFile)) {
+                if (line.startsWith("JAVA_VERSION=")) {
+                    String value = line.substring("JAVA_VERSION=".length()).trim();
+                    // Remove surrounding quotes
+                    if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
+                        value = value.substring(1, value.length() - 1);
+                    }
+                    return value.isEmpty() ? null : value;
+                }
+            }
+        } catch (IOException e) {
+            LOGGER.debug("Cannot read release file at {}: {}", releaseFile, e.getMessage());
+        }
+        return null;
+    }
+}
diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/JdkToolchainDiscovererTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/JdkToolchainDiscovererTest.java
new file mode 100644
index 0000000000..041a9cce1d
--- /dev/null
+++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/JdkToolchainDiscovererTest.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.impl;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Optional;
+
+import org.apache.maven.api.toolchain.ToolchainModel;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class JdkToolchainDiscovererTest {
+
+    @TempDir
+    Path tempDir;
+
+    private final JdkToolchainDiscoverer discoverer = new JdkToolchainDiscoverer();
+
+    @Test
+    void isValidJdkHomeWithJavac() throws IOException {
+        Path jdkHome = createFakeJdk(tempDir, "jdk-17");
+        assertTrue(discoverer.isValidJdkHome(jdkHome));
+    }
+
+    @Test
+    void isValidJdkHomeWithoutJavac() throws IOException {
+        Path jdkHome = tempDir.resolve("jdk-no-javac");
+        Files.createDirectories(jdkHome.resolve("bin"));
+        assertFalse(discoverer.isValidJdkHome(jdkHome));
+    }
+
+    @Test
+    void isValidJdkHomeNonExistent() {
+        assertFalse(discoverer.isValidJdkHome(tempDir.resolve("nonexistent")));
+    }
+
+    @Test
+    void readVersionFromReleaseFile() throws IOException {
+        Path jdkHome = tempDir.resolve("jdk-17");
+        Files.createDirectories(jdkHome);
+        Files.writeString(jdkHome.resolve("release"), "JAVA_VERSION=\"17.0.2\"\nIMPLEMENTOR=\"Eclipse Adoptium\"\n");
+
+        assertEquals("17.0.2", discoverer.readVersionFromRelease(jdkHome));
+    }
+
+    @Test
+    void readVersionFromReleaseFileJdk8Format() throws IOException {
+        Path jdkHome = tempDir.resolve("jdk-8");
+        Files.createDirectories(jdkHome);
+        Files.writeString(jdkHome.resolve("release"), "JAVA_VERSION=\"1.8.0_392\"\n");
+
+        assertEquals("1.8.0_392", discoverer.readVersionFromRelease(jdkHome));
+    }
+
+    @Test
+    void readVersionFromReleaseFileNoQuotes() throws IOException {
+        Path jdkHome = tempDir.resolve("jdk-11");
+        Files.createDirectories(jdkHome);
+        Files.writeString(jdkHome.resolve("release"), "JAVA_VERSION=11.0.21\n");
+
+        assertEquals("11.0.21", discoverer.readVersionFromRelease(jdkHome));
+    }
+
+    @Test
+    void readVersionFromMissingReleaseFile() {
+        assertNull(discoverer.readVersionFromRelease(tempDir.resolve("no-release")));
+    }
+
+    @Test
+    void readVersionFromReleaseFileWithoutJavaVersion() throws IOException {
+        Path jdkHome = tempDir.resolve("jdk-bad");
+        Files.createDirectories(jdkHome);
+        Files.writeString(jdkHome.resolve("release"), "IMPLEMENTOR=\"Some Vendor\"\n");
+
+        assertNull(discoverer.readVersionFromRelease(jdkHome));
+    }
+
+    @Test
+    void buildToolchainModelFromValidJdk() throws IOException {
+        Path jdkHome = createFakeJdkWithRelease(tempDir, "jdk-17", "17.0.2");
+
+        Optional<ToolchainModel> result = discoverer.buildToolchainModel(jdkHome);
+
+        assertTrue(result.isPresent());
+        ToolchainModel model = result.get();
+        assertEquals("jdk", model.getType());
+        assertEquals("17", model.getProvides().get("version"));
+        assertNotNull(model.getConfiguration());
+        assertEquals(
+                jdkHome.toString(), model.getConfiguration().child("jdkHome").value());
+    }
+
+    @Test
+    void buildToolchainModelFromJdk8() throws IOException {
+        Path jdkHome = createFakeJdkWithRelease(tempDir, "jdk-8", "1.8.0_392");
+
+        Optional<ToolchainModel> result = discoverer.buildToolchainModel(jdkHome);
+
+        assertTrue(result.isPresent());
+        assertEquals("8", result.get().getProvides().get("version"));
+    }
+
+    @Test
+    void buildToolchainModelWithoutReleaseFile() throws IOException {
+        Path jdkHome = createFakeJdk(tempDir, "jdk-old");
+
+        Optional<ToolchainModel> result = discoverer.buildToolchainModel(jdkHome);
+
+        assertFalse(result.isPresent());
+    }
+
+    @Test
+    void resolveJdkHomeDirectPath() throws IOException {
+        Path jdkHome = createFakeJdk(tempDir, "jdk-17");
+
+        assertEquals(jdkHome, discoverer.resolveJdkHome(jdkHome));
+    }
+
+    @Test
+    void resolveJdkHomeMacOsBundle() throws IOException {
+        Path bundleRoot = tempDir.resolve("jdk-17.jdk");
+        Path contentsHome = bundleRoot.resolve("Contents").resolve("Home");
+        Files.createDirectories(contentsHome.resolve("bin"));
+        Files.createFile(contentsHome.resolve("bin").resolve("javac"));
+
+        assertEquals(contentsHome, discoverer.resolveJdkHome(bundleRoot));
+    }
+
+    @Test
+    void resolveJdkHomeInvalidPath() {
+        assertNull(discoverer.resolveJdkHome(tempDir.resolve("nonexistent")));
+    }
+
+    @Test
+    void discoverToolchainsIsCached() {
+        // Two calls should return the same list instance (cached)
+        var first = discoverer.discoverToolchains();
+        var second = discoverer.discoverToolchains();
+        assertNotNull(first);
+        assertTrue(first == second, "Expected cached result (same instance)");
+    }
+
+    private Path createFakeJdk(Path parent, String name) throws IOException {
+        Path jdkHome = parent.resolve(name);
+        Path binDir = jdkHome.resolve("bin");
+        Files.createDirectories(binDir);
+        Files.createFile(binDir.resolve("javac"));
+        return jdkHome;
+    }
+
+    private Path createFakeJdkWithRelease(Path parent, String name, String version) throws IOException {
+        Path jdkHome = createFakeJdk(parent, name);
+        Files.writeString(jdkHome.resolve("release"), "JAVA_VERSION=\"" + version + "\"\n");
+        return jdkHome;
+    }
+}