Compare commits

...

6 Commits

Author SHA1 Message Date
Bruno Borges
e1ce3a3428 Fail on mismatched Maven toolchain ID counts (#1161)
* Fail on mismatched Maven toolchain IDs

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 8c821981-7b21-45fe-9463-5bb375d7dce4

* Clarify Maven toolchain ID version counts

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 8c821981-7b21-45fe-9463-5bb375d7dce4

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 8c821981-7b21-45fe-9463-5bb375d7dce4
2026-07-28 23:33:41 -04:00
Bruno Borges
ce75feb3d3 Reject invalid boolean input values (#1160)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: c6daa6b5-31f5-46b2-a994-b8320b50a50d
2026-07-28 22:43:39 -04:00
Bruno Borges
382d4b753d Fix caching when wrapper distributions are absent (#1151)
* Fix missing wrapper cache distributions

Skip optional Maven and Gradle wrapper cache saves when their distribution paths do not exist, while allowing the main dependency cache to save.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: a43181c5-548d-4293-be58-b76c03cece79

* Use resolved paths for wrapper cache saves

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: a43181c5-548d-4293-be58-b76c03cece79

* Rebuild action distributions

Regenerate the setup and cleanup bundles after updating additional cache saves to use resolved paths.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: a43181c5-548d-4293-be58-b76c03cece79

---------

Copilot-Session: a43181c5-548d-4293-be58-b76c03cece79
2026-07-28 19:14:06 -04:00
Bruno Borges
24d1ce4c2b Document Java package compatibility (#1152)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: de5ff500-7ba1-4b07-9805-cfc4036d6155
2026-07-28 18:47:14 -04:00
Copilot
1c3b3d28f0 Support Temurin JDKs with JMOD files (#1149)
* Initial plan

* Add Temurin JMOD installation support

* Rebuild action bundles

* Use java-package for Temurin JMODs

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: e7d8c581-2d14-4ccc-aeca-afc0f3b0c2bc

* Fix Temurin JMOD test paths on Windows

Use platform-aware path construction for the JMOD copy and cache assertions so the Windows test expects backslash-normalized paths.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e7d8c581-2d14-4ccc-aeca-afc0f3b0c2bc
2026-07-28 18:39:15 -04:00
Copilot
0b0bd25927 Add OpenJDK distribution (#1147)
* Initial plan

* Add OpenJDK distribution

* Support archived OpenJDK release formats

* Handle legacy OpenJDK URL layout

* Resolve legacy OpenJDK build metadata

* Rename OpenJDK distribution to oracle-openjdk

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 2c93ae0c-bbf5-40f5-bf6e-40168d0e267f

* Make OpenJDK tests platform independent

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 2c93ae0c-bbf5-40f5-bf6e-40168d0e267f

* Document Oracle OpenJDK early access builds

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 2c93ae0c-bbf5-40f5-bf6e-40168d0e267f

* Clarify Oracle OpenJDK security note

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 2c93ae0c-bbf5-40f5-bf6e-40168d0e267f

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
Copilot-Session: 2c93ae0c-bbf5-40f5-bf6e-40168d0e267f
2026-07-28 15:55:33 -04:00
18 changed files with 1108 additions and 106 deletions

View File

@@ -48,7 +48,7 @@ For more details, see the full release notes on the [releases page](https://git
- `distribution`: Java [distribution](#supported-distributions). Required unless `java-version-file` points to `.sdkmanrc` with a recognized distribution suffix (for example `java=21.0.5-tem`).
- `java-package`: The packaging variant of the chosen distribution. Possible values: `jdk`, `jre`, `jdk+fx`, `jre+fx`. For Azul Zulu, `jdk+crac` and `jre+crac` are also supported. Default value: `jdk`.
- `java-package`: The packaging variant of the chosen distribution. Possible values: `jdk`, `jre`, `jdk+fx`, `jre+fx`. For Azul Zulu, `jdk+crac` and `jre+crac` are also supported. For Eclipse Temurin 24 and later, `jdk+jmods` includes the separately packaged JMOD files. Default value: `jdk`.
- `architecture`: The target architecture of the package. Possible values: `x86`, `x64`, `armv7`, `aarch64`, `ppc64le`. Default value: Derived from the runner machine.
@@ -89,7 +89,7 @@ For more details, see the full release notes on the [releases page](https://git
- `gpg-passphrase-env-var`: Environment variable name for the GPG private key passphrase. Default is GPG\_PASSPHRASE.
- `mvn-toolchain-id`: Name of Maven Toolchain ID if the default name of `${distribution}_${java-version}` is not wanted.
- `mvn-toolchain-id`: Name of Maven Toolchain ID if the default name of `${distribution}_${java-version}` is not wanted. When supplied, the number of IDs must match the number of Java versions.
- `mvn-toolchain-vendor`: Name of Maven Toolchain Vendor if the default name of `${distribution}` is not wanted.
@@ -148,6 +148,7 @@ Currently, the following distributions are supported:
| `corretto` | [Amazon Corretto Build of OpenJDK](https://aws.amazon.com/corretto/) | [`corretto` license](https://aws.amazon.com/corretto/faqs/)
| `semeru` | [IBM Semeru Runtime Open Edition](https://developer.ibm.com/languages/java/semeru-runtimes/downloads/) | [`semeru` license](https://openjdk.java.net/legal/gplv2+ce.html) |
| `oracle` | [Oracle JDK](https://www.oracle.com/java/technologies/downloads/) | [`oracle` license](https://java.com/freeuselicense)
| `oracle-openjdk` | [Oracle OpenJDK](https://jdk.java.net/) | [`oracle-openjdk` license](https://openjdk.org/legal/gplv2+ce.html)
| `dragonwell` | [Alibaba Dragonwell JDK](https://dragonwell-jdk.io/) | [`dragonwell` license](https://www.aliyun.com/product/dragonwell/)
| `sapmachine` | [SAP SapMachine JDK/JRE](https://sapmachine.io/) | [`sapmachine` license](https://github.com/SAP/SapMachine/blob/sapmachine/LICENSE)
| `graalvm` | [Oracle GraalVM](https://www.graalvm.org/) | [`graalvm` license](https://www.oracle.com/downloads/licenses/graal-free-license.html)
@@ -159,6 +160,7 @@ Currently, the following distributions are supported:
> [!NOTE]
> - The different distributors can provide discrepant list of available versions / supported configurations. Please refer to the official documentation to see the list of supported versions.
> - AdoptOpenJDK got moved to Eclipse Temurin and won't be updated anymore. It is highly recommended to migrate workflows from `adopt` and `adopt-openj9`, to `temurin` and `semeru` respectively, to keep receiving software and security updates. See more details in the [Good-bye AdoptOpenJDK post](https://blog.adoptopenjdk.net/2021/08/goodbye-adoptopenjdk-hello-adoptium/).
> - Oracle OpenJDK builds are created and hosted by Oracle. After a limited number of releases, Oracle archives these builds and no longer provides security updates. To continue receiving security patches, users must move to Oracle JDK or choose a different vendor.
> - For Azul Zulu OpenJDK, architecture `arm64` is mapped to `aarch64` when querying the Azul Metadata API.
> - To comply with the GraalVM Free Terms and Conditions (GFTC) license, it is recommended to use GraalVM JDK 17 version 17.0.12, as this is the only version of GraalVM JDK 17 available under the GFTC license. Additionally, it is encouraged to consider upgrading to GraalVM JDK 21, which offers the latest features and improvements.
> - GraalVM Community is available as `distribution: 'graalvm-community'` for stable JDK 17 and later releases published on GitHub.

View File

@@ -458,11 +458,16 @@ describe('dependency cache', () => {
});
describe('save', () => {
let spyCacheSave: any;
let spyGlobCreate: jest.Mock;
beforeEach(() => {
spyCacheSave = (cache.saveCache as any).mockImplementation(
(paths: string[], key: string) => Promise.resolve(0)
);
spyGlobCreate = glob.create as jest.Mock;
spyGlobCreate.mockResolvedValue({
glob: jest.fn(() => Promise.resolve(['wrapper-path']))
});
spyWarning.mockImplementation(() => null);
});
@@ -543,7 +548,7 @@ describe('dependency cache', () => {
await save('maven');
expect(spyCacheSave).toHaveBeenCalledWith(
[join(os.homedir(), '.m2', 'wrapper', 'dists')],
['wrapper-path'],
'setup-java-maven-wrapper-key'
);
expect(spyWarning).not.toHaveBeenCalled();
@@ -572,6 +577,11 @@ describe('dependency cache', () => {
});
it('does not fail the post step when the wrapper distribution path is missing', async () => {
createFile(join(workspace, 'pom.xml'));
createDirectory(join(workspace, '.mvn'));
createDirectory(join(workspace, '.mvn', 'wrapper'));
createFile(
join(workspace, '.mvn', 'wrapper', 'maven-wrapper.properties')
);
(core.getState as jest.Mock<any>).mockImplementation((name: any) => {
switch (name) {
case 'cache-primary-key':
@@ -584,17 +594,19 @@ describe('dependency cache', () => {
return '';
}
});
spyCacheSave.mockImplementation((paths: string[]) =>
paths.includes(join(os.homedir(), '.m2', 'wrapper', 'dists'))
? Promise.reject(
new cache.ValidationError(
'Path Validation Error: Path(s) specified in the action for caching do(es) not exist'
)
)
: Promise.resolve(0)
);
spyGlobCreate.mockResolvedValue({
glob: jest.fn(() => Promise.resolve([]))
});
await expect(save('maven')).resolves.toBeUndefined();
expect(spyCacheSave).not.toHaveBeenCalledWith(
[join(os.homedir(), '.m2', 'wrapper', 'dists')],
expect.any(String)
);
expect(spyCacheSave).toHaveBeenCalledWith(
[join(os.homedir(), '.m2', 'repository')],
'setup-java-cache-primary-key'
);
expect(spyWarning).not.toHaveBeenCalled();
});
});
@@ -666,7 +678,7 @@ describe('dependency cache', () => {
await save('gradle');
expect(spyCacheSave).toHaveBeenCalledWith(
[join(os.homedir(), '.gradle', 'wrapper')],
['wrapper-path'],
'setup-java-gradle-wrapper-key'
);
expect(spyWarning).not.toHaveBeenCalled();
@@ -693,6 +705,36 @@ describe('dependency cache', () => {
expect.any(String)
);
});
it('does not fail the post step when the wrapper distribution path is missing', async () => {
createFile(join(workspace, 'build.gradle'));
createFile(join(workspace, 'gradle-wrapper.properties'));
(core.getState as jest.Mock<any>).mockImplementation((name: any) => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-primary-key';
case 'cache-matched-key':
return 'setup-java-cache-matched-key';
case 'cache-primary-key-gradle-wrapper':
return 'setup-java-gradle-wrapper-key';
default:
return '';
}
});
spyGlobCreate.mockResolvedValue({
glob: jest.fn(() => Promise.resolve([]))
});
await expect(save('gradle')).resolves.toBeUndefined();
expect(spyCacheSave).not.toHaveBeenCalledWith(
[join(os.homedir(), '.gradle', 'wrapper')],
expect.any(String)
);
expect(spyCacheSave).toHaveBeenCalledWith(
[join(os.homedir(), '.gradle', 'caches')],
'setup-java-cache-primary-key'
);
expect(spyWarning).not.toHaveBeenCalled();
});
});
describe('for sbt', () => {
it('uploads cache even if no build.sbt found', async () => {

View File

@@ -0,0 +1,16 @@
import {getJavaDistribution} from '../../src/distributions/distribution-factory.js';
describe('getJavaDistribution', () => {
it("rejects java-package 'jdk+jmods' for non-Temurin distributions", () => {
expect(() =>
getJavaDistribution('zulu', {
version: '25',
architecture: 'x64',
packageType: 'jdk+jmods',
checkLatest: false
})
).toThrow(
"java-package 'jdk+jmods' is only supported for distribution 'temurin'."
);
});
});

View File

@@ -0,0 +1,216 @@
import {afterEach, beforeEach, describe, expect, it, jest} from '@jest/globals';
import {HttpClient} from '@actions/http-client';
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((value: string) => value),
toWin32Path: jest.fn((value: string) => value),
toPosixPath: jest.fn((value: string) => value)
}));
const {OpenJdkDistribution} =
await import('../../src/distributions/openjdk/installer.js');
const {getJavaDistribution} =
await import('../../src/distributions/distribution-factory.js');
const homePage = `
<a href="/26/">JDK 26</a>
<a href="/27/">JDK
27</a>
`;
const currentPage = `
<a href="https://download.java.net/java/GA/jdk26.0.2/hash/10/GPL/openjdk-26.0.2_linux-x64_bin.tar.gz">tar.gz</a>
<a href="https://download.java.net/java/GA/jdk26.0.2/hash/10/GPL/openjdk-26.0.2_linux-aarch64_bin.tar.gz">tar.gz</a>
`;
const earlyAccessPage = `
<a href="https://download.java.net/java/early_access/jdk27/32/GPL/openjdk-27-ea+32_linux-x64_bin.tar.gz">tar.gz</a>
`;
const archivePage = `
<a href="https://download.java.net/java/GA/jdk26.0.1/hash/8/GPL/openjdk-26.0.1_linux-x64_bin.tar.gz">tar.gz</a>
<a href="https://download.java.net/java/GA/jdk25/hash/36/GPL/openjdk-25_linux-x64_bin.tar.gz">tar.gz</a>
<a href="https://download.java.net/java/GA/jdk18.0.1.1/hash/2/GPL/openjdk-18.0.1.1_linux-x64_bin.tar.gz">tar.gz</a>
<th>9.0.4 (build 9.0.4+11)</th>
<a href="https://download.java.net/java/GA/jdk9/9.0.4/binaries/openjdk-9.0.4_linux-x64_bin.tar.gz">tar.gz</a>
`;
function createDistribution(
version = '26',
architecture = 'x64',
packageType = 'jdk',
useFixturePlatform = true
) {
const distribution = new OpenJdkDistribution({
version,
architecture,
packageType,
checkLatest: false
});
if (useFixturePlatform) {
distribution['getPlatform'] = jest.fn(() => 'linux');
}
return distribution;
}
describe('OpenJdkDistribution', () => {
let getSpy: jest.SpiedFunction<HttpClient['get']>;
beforeEach(() => {
getSpy = jest
.spyOn(HttpClient.prototype, 'get')
.mockImplementation(async url => {
const pages: Record<string, string> = {
'https://jdk.java.net/': homePage,
'https://jdk.java.net/26/': currentPage,
'https://jdk.java.net/27/': earlyAccessPage,
'https://jdk.java.net/archive/': archivePage
};
return {
readBody: async () => pages[url] ?? ''
} as Awaited<ReturnType<HttpClient['get']>>;
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it('resolves the newest matching GA release', async () => {
const result = await createDistribution()['findPackageForDownload']('26');
expect(result).toEqual({
version: '26.0.2+10',
url: 'https://download.java.net/java/GA/jdk26.0.2/hash/10/GPL/openjdk-26.0.2_linux-x64_bin.tar.gz'
});
});
it('resolves an archived GA release', async () => {
const result =
await createDistribution('26.0.1')['findPackageForDownload']('26.0.1');
expect(result.version).toBe('26.0.1+8');
expect(result.url).toContain('/openjdk-26.0.1_linux-x64_bin.tar.gz');
});
it('resolves an exact GA build', async () => {
const result =
await createDistribution('26.0.2+10')['findPackageForDownload'](
'26.0.2+10'
);
expect(result.version).toBe('26.0.2+10');
});
it('resolves an exact build from a legacy archive heading', async () => {
const result =
await createDistribution('9.0.4+11')['findPackageForDownload'](
'9.0.4+11'
);
expect(result.version).toBe('9.0.4+11');
expect(result.url).toContain('/binaries/openjdk-9.0.4_linux-x64_bin');
});
it('resolves a four-field Java version', async () => {
const result =
await createDistribution('18.0.1.1')['findPackageForDownload'](
'18.0.1+1'
);
expect(result.version).toBe('18.0.1+1');
expect(result.url).toContain('/openjdk-18.0.1.1_linux-x64_bin.tar.gz');
});
it('resolves an early-access release without requesting the archive', async () => {
const result =
await createDistribution('27-ea')['findPackageForDownload']('27');
expect(result).toEqual({
version: '27.0.0+32',
url: 'https://download.java.net/java/early_access/jdk27/32/GPL/openjdk-27-ea+32_linux-x64_bin.tar.gz'
});
expect(getSpy).not.toHaveBeenCalledWith('https://jdk.java.net/archive/');
});
it('reports available versions when no release matches', async () => {
await expect(
createDistribution()['findPackageForDownload']('24')
).rejects.toThrow(
"No matching version found for SemVer '24'.\nDistribution: Oracle OpenJDK"
);
});
it.each([
['jre', 'Oracle OpenJDK provides only the `jdk` package type'],
['jdk+fx', 'Oracle OpenJDK provides only the `jdk` package type']
])('rejects the %s package type', async (packageType, message) => {
await expect(
createDistribution('26', 'x64', packageType)['findPackageForDownload'](
'26'
)
).rejects.toThrow(message);
});
it('rejects unsupported architectures', async () => {
await expect(
createDistribution('26', 'x86')['findPackageForDownload']('26')
).rejects.toThrow('Unsupported architecture: x86');
});
it('maps supported platforms', () => {
const distribution = createDistribution('26', 'x64', 'jdk', false);
expect(distribution['getPlatform']('linux')).toBe('linux');
expect(distribution['getPlatform']('darwin')).toBe('macos');
expect(distribution['getPlatform']('win32')).toBe('windows');
expect(() => distribution['getPlatform']('freebsd')).toThrow(
"Platform 'freebsd' is not supported"
);
});
it('parses legacy platform names and archive formats', () => {
const distribution = createDistribution();
const macRelease = distribution['parseReleases'](
'<a href="https://download.java.net/java/GA/jdk16/hash/7/GPL/openjdk-16_osx-x64_bin.tar.gz">tar.gz</a>',
'macos',
'x64'
);
const windowsRelease = distribution['parseReleases'](
'<a href="https://download.java.net/java/GA/jdk10/hash/13/openjdk-10.0.2_windows-x64_bin.tar.gz">tar.gz</a>',
'windows',
'x64'
);
expect(macRelease[0].version).toBe('16.0.0+7');
expect(windowsRelease[0].version).toBe('10.0.2+13');
expect(windowsRelease[0].url.endsWith('.tar.gz')).toBe(true);
});
it('is registered in the distribution factory', () => {
const distribution = getJavaDistribution('oracle-openjdk', {
version: '26',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
expect(distribution).toBeInstanceOf(OpenJdkDistribution);
});
});

View File

@@ -13,6 +13,7 @@ import type {TemurinImplementation as TemurinImplementationType} from '../../src
import {HttpClient} from '@actions/http-client';
import fs from 'fs';
import os from 'os';
import path from 'path';
import manifestData from '../data/temurin.json' with {type: 'json'};
@@ -119,6 +120,16 @@ describe('getAvailableVersions', () => {
TemurinImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jdk&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{
version: '25',
architecture: 'x64',
packageType: 'jdk+jmods',
checkLatest: false
},
TemurinImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jdk&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{
version: '16',
@@ -169,6 +180,27 @@ describe('getAvailableVersions', () => {
}
);
it('requests the JMOD image type', async () => {
const distribution = new TemurinDistribution(
{
version: '25',
architecture: 'x64',
packageType: 'jdk+jmods',
checkLatest: false
},
TemurinImplementation.Hotspot
);
distribution['getPlatformOption'] = () => 'linux';
await distribution['getAvailableVersions']('jmods');
expect(spyHttpClient).toHaveBeenCalledWith(
expect.stringContaining(
'os=linux&architecture=x64&image_type=jmods&release_type=ga'
)
);
});
it('load available versions', async () => {
const nextPageUrl =
'https://api.adoptium.net/v3/assets/version/%5B1.0,100.0%5D?page=1&page_size=20';
@@ -229,7 +261,12 @@ describe('getAvailableVersions', () => {
it.each([
[TemurinImplementation.Hotspot, 'jdk', 'Java_Temurin-Hotspot_jdk'],
[TemurinImplementation.Hotspot, 'jre', 'Java_Temurin-Hotspot_jre']
[TemurinImplementation.Hotspot, 'jre', 'Java_Temurin-Hotspot_jre'],
[
TemurinImplementation.Hotspot,
'jdk+jmods',
'Java_Temurin-Hotspot_jdk+jmods'
]
])(
'find right toolchain folder',
(
@@ -386,6 +423,7 @@ describe('downloadTool', () => {
let spyCacheDir: any;
let spyReadDirSync: any;
let spyRenameWinArchive: any;
let spyCopySync: any;
beforeEach(() => {
spyDownloadTool = tc.downloadTool as jest.Mock;
@@ -400,6 +438,8 @@ describe('downloadTool', () => {
spyReadDirSync.mockReturnValue(['jdk-17'] as any);
spyRenameWinArchive = util.renameWinArchive as jest.Mock;
spyRenameWinArchive.mockReturnValue('/tmp/jdk.tar.gz.zip');
spyCopySync = jest.spyOn(fs, 'cpSync');
spyCopySync.mockImplementation(() => undefined);
});
afterEach(() => {
@@ -433,6 +473,60 @@ describe('downloadTool', () => {
);
});
it('downloads and adds matching JMODs to the JDK', async () => {
spyDownloadTool
.mockResolvedValueOnce('/tmp/jdk.tar.gz')
.mockResolvedValueOnce('/tmp/jmods.tar.gz');
spyExtractJdkFile
.mockResolvedValueOnce('/tmp/extracted')
.mockResolvedValueOnce('/tmp/extracted-jmods');
spyReadDirSync
.mockReturnValueOnce(['jdk-25'] as any)
.mockReturnValueOnce(['jdk-25-jmods'] as any);
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
const distribution = new TemurinDistribution(
{
version: '25',
architecture: 'x64',
packageType: 'jdk+jmods',
checkLatest: false
},
TemurinImplementation.Hotspot
);
distribution['resolvePackage'] = jest.fn().mockResolvedValue({
version: '25.0.3+9',
url: 'https://example.com/jmods.tar.gz'
});
await distribution['downloadTool']({
version: '25.0.3+9',
url: 'https://example.com/jdk.tar.gz'
});
expect(distribution['resolvePackage']).toHaveBeenCalledWith(
'25.0.3+9',
'jmods'
);
expect(spyDownloadTool).toHaveBeenNthCalledWith(
2,
'https://example.com/jmods.tar.gz'
);
expect(spyCopySync).toHaveBeenCalledWith(
path.join('/tmp/extracted-jmods', 'jdk-25-jmods'),
process.platform === 'darwin'
? path.join('/tmp/extracted', 'jdk-25', 'Contents', 'Home', 'jmods')
: path.join('/tmp/extracted', 'jdk-25', 'jmods'),
{recursive: true}
);
expect(spyCacheDir).toHaveBeenCalledWith(
path.join('/tmp/extracted', 'jdk-25'),
'Java_Temurin-Hotspot_jdk+jmods',
'25.0.3-9',
'x64'
);
});
it('fails when signature is missing and verification is enabled', async () => {
const distribution = new TemurinDistribution(
{

View File

@@ -1007,3 +1007,67 @@ describe('toolchains tests', () => {
expect((contents.match(/<toolchain>/g) || []).length).toBe(runs.length);
}, 100000);
});
describe('validateToolchainIds', () => {
it.each([
{
name: 'uses generated IDs when no custom IDs are supplied',
versions: ['17', '21'],
versionFile: '',
toolchainIds: []
},
{
name: 'accepts one custom ID for a single Java version',
versions: ['21'],
versionFile: '',
toolchainIds: ['custom-21']
},
{
name: 'accepts one custom ID per Java version',
versions: ['17', '21'],
versionFile: '',
toolchainIds: ['custom-17', 'custom-21']
},
{
name: 'accepts one custom ID with java-version-file',
versions: [],
versionFile: '.java-version',
toolchainIds: ['custom-file-version']
}
])('$name', ({versions, versionFile, toolchainIds}) => {
expect(() =>
toolchains.validateToolchainIds(versions, versionFile, toolchainIds)
).not.toThrow();
});
it.each([
{
name: 'rejects fewer IDs than Java versions',
versions: ['17', '21'],
versionFile: '',
toolchainIds: ['custom-17'],
expectedMessage:
'The number of Maven toolchain IDs (1) must match the number of Java versions (2)'
},
{
name: 'rejects extra IDs for a single Java version',
versions: ['21'],
versionFile: '',
toolchainIds: ['custom-21', 'custom-extra'],
expectedMessage:
'The number of Maven toolchain IDs (2) must match the number of Java versions (1)'
},
{
name: 'rejects extra IDs with java-version-file',
versions: [],
versionFile: '.java-version',
toolchainIds: ['custom-file-version', 'custom-extra'],
expectedMessage:
'The number of Maven toolchain IDs (2) must match the number of Java versions (1)'
}
])('$name', ({versions, versionFile, toolchainIds, expectedMessage}) => {
expect(() =>
toolchains.validateToolchainIds(versions, versionFile, toolchainIds)
).toThrow(expectedMessage);
});
});

View File

@@ -57,9 +57,73 @@ const {
isCacheFeatureAvailable,
isGhes,
validatePaginationUrl,
getLatestMajorVersion
getLatestMajorVersion,
getBooleanInput
} = await import('../src/util.js');
describe('getBooleanInput', () => {
let inputs: Record<string, string>;
beforeEach(() => {
inputs = {};
(core.getInput as jest.Mock).mockImplementation(
(name: string) => inputs[name] ?? ''
);
});
afterEach(() => {
jest.resetAllMocks();
});
it.each([
['true', true],
['TRUE', true],
['TrUe', true],
[' true ', true],
['false', false],
['FALSE', false],
['FaLsE', false],
[' false ', false]
])('parses %j as %s', (value: string, expected: boolean) => {
inputs['boolean-input'] = value;
expect(getBooleanInput('boolean-input')).toBe(expected);
});
it.each([
[undefined, false],
[false, false],
[true, true]
])(
'uses the configured default %s when the input is omitted',
(defaultValue: boolean | undefined, expected: boolean) => {
expect(getBooleanInput('boolean-input', defaultValue)).toBe(expected);
}
);
it('uses the configured default for a whitespace-only input', () => {
inputs['boolean-input'] = ' ';
expect(getBooleanInput('boolean-input', true)).toBe(true);
});
it.each([
'check-latest',
'force-download',
'set-default',
'verify-signature',
'overwrite-settings',
'show-download-progress',
'problem-matcher'
])('rejects an invalid value for %s', inputName => {
inputs[inputName] = 'ture';
expect(() => getBooleanInput(inputName)).toThrow(
`Invalid value 'ture' for boolean input '${inputName}'. Expected 'true' or 'false'.`
);
});
});
describe('isVersionSatisfies', () => {
it.each([
['x', '11.0.0', true],

View File

@@ -13,7 +13,7 @@ inputs:
description: 'Java distribution. See the list of supported distributions in README file. This input is required except when java-version-file points to .sdkmanrc with a recognized distribution suffix (e.g., java=21.0.5-tem).'
required: false
java-package:
description: 'The package type (jdk, jre, jdk+fx, jre+fx, jdk+crac, jre+crac)'
description: 'The package type (jdk, jre, jdk+fx, jre+fx, jdk+crac, jre+crac, jdk+jmods)'
required: false
default: 'jdk'
architecture:
@@ -96,7 +96,7 @@ inputs:
required: false
default: ${{ github.server_url == 'https://github.com' && github.token || '' }}
mvn-toolchain-id:
description: 'Name of Maven Toolchain ID if the default name of "${distribution}_${java-version}" is not wanted. See examples of supported syntax in Advanced Usage file'
description: 'Name of Maven Toolchain ID if the default name of "${distribution}_${java-version}" is not wanted. When supplied, the number of IDs must match the number of Java versions. See examples of supported syntax in Advanced Usage file'
required: false
mvn-toolchain-vendor:
description: 'Name of Maven Toolchain Vendor if the default name of "${distribution}" is not wanted. See examples of supported syntax in Advanced Usage file'

23
dist/cleanup/index.js vendored
View File

@@ -97365,7 +97365,18 @@ function getTempDir() {
return tempDirectory;
}
function util_getBooleanInput(inputName, defaultValue = false) {
return ((core.getInput(inputName) || String(defaultValue)).toUpperCase() === 'TRUE');
const inputValue = core.getInput(inputName);
const normalizedValue = inputValue.trim().toLowerCase();
if (!normalizedValue) {
return defaultValue;
}
if (normalizedValue === 'true') {
return true;
}
if (normalizedValue === 'false') {
return false;
}
throw new Error(`Invalid value '${inputValue}' for boolean input '${inputName}'. Expected 'true' or 'false'.`);
}
function getVersionFromToolcachePath(toolPath) {
if (toolPath) {
@@ -97988,8 +97999,16 @@ async function saveAdditionalCache(packageManager, additionalCache) {
info(`Cache hit occurred on the ${additionalCache.name} primary key ${primaryKey}, not saving cache.`);
return;
}
const globber = await create(additionalCache.path.join('\n'), {
implicitDescendants: false
});
const cachePaths = await globber.glob();
if (cachePaths.length === 0) {
core_debug(`${additionalCache.name} cache paths do not exist, not saving cache.`);
return;
}
try {
const cacheId = await cache_saveCache(additionalCache.path, primaryKey);
const cacheId = await cache_saveCache(cachePaths, primaryKey);
if (cacheId === -1) {
core_debug(`${additionalCache.name} cache was not saved for the key: ${primaryKey}`);
return;

210
dist/setup/index.js vendored
View File

@@ -128364,7 +128364,18 @@ function getTempDir() {
return tempDirectory;
}
function util_getBooleanInput(inputName, defaultValue = false) {
return ((getInput(inputName) || String(defaultValue)).toUpperCase() === 'TRUE');
const inputValue = getInput(inputName);
const normalizedValue = inputValue.trim().toLowerCase();
if (!normalizedValue) {
return defaultValue;
}
if (normalizedValue === 'true') {
return true;
}
if (normalizedValue === 'false') {
return false;
}
throw new Error(`Invalid value '${inputValue}' for boolean input '${inputName}'. Expected 'true' or 'false'.`);
}
function getVersionFromToolcachePath(toolPath) {
if (toolPath) {
@@ -128865,6 +128876,15 @@ async function write(directory, settings, overwriteSettings) {
function validateToolchainIds(versions, versionFile, toolchainIds) {
if (!toolchainIds.length) {
return;
}
const versionCount = versions.length || (versionFile ? 1 : 0);
if (versionCount !== toolchainIds.length) {
throw new Error(`The number of Maven toolchain IDs (${toolchainIds.length}) must match the number of Java versions (${versionCount})`);
}
}
async function configureToolchains(version, distributionName, jdkHome, toolchainId) {
const vendor = getInput(INPUT_MVN_TOOLCHAIN_VENDOR) || distributionName;
const id = toolchainId || `${vendor}_${version}`;
@@ -129229,8 +129249,16 @@ async function saveAdditionalCache(packageManager, additionalCache) {
core.info(`Cache hit occurred on the ${additionalCache.name} primary key ${primaryKey}, not saving cache.`);
return;
}
const globber = await glob.create(additionalCache.path.join('\n'), {
implicitDescendants: false
});
const cachePaths = await globber.glob();
if (cachePaths.length === 0) {
core.debug(`${additionalCache.name} cache paths do not exist, not saving cache.`);
return;
}
try {
const cacheId = await cache.saveCache(additionalCache.path, primaryKey);
const cacheId = await cache.saveCache(cachePaths, primaryKey);
if (cacheId === -1) {
core.debug(`${additionalCache.name} cache was not saved for the key: ${primaryKey}`);
return;
@@ -129873,21 +129901,27 @@ wI4qF/KKq9BfyfucAs0ykA==
var TemurinImplementation;
(function (TemurinImplementation) {
TemurinImplementation["Hotspot"] = "Hotspot";
})(TemurinImplementation || (TemurinImplementation = {}));
class TemurinDistribution extends JavaBase {
jvmImpl;
includeJmods;
constructor(installerOptions, jvmImpl) {
super(`Temurin-${jvmImpl}`, installerOptions);
this.jvmImpl = jvmImpl;
this.includeJmods = this.packageType === 'jdk+jmods';
}
/**
* @internal For cross-distribution reuse only. Not intended as a public API.
*/
async findPackageForDownload(version) {
const availableVersionsRaw = await this.getAvailableVersions();
return this.resolvePackage(version, this.includeJmods ? 'jdk' : this.packageType);
}
async resolvePackage(version, imageType) {
const availableVersionsRaw = await this.getAvailableVersions(imageType);
const availableVersionsWithBinaries = availableVersionsRaw
.filter(item => item.binaries.length > 0)
.map(item => {
@@ -129915,19 +129949,7 @@ class TemurinDistribution extends JavaBase {
}
async downloadTool(javaRelease) {
info(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await downloadTool(javaRelease.url);
if (this.verifySignature) {
if (!javaRelease.signatureUrl) {
throw new Error(`Input 'verify-signature' is enabled, but no signature URL was found for Temurin version ${javaRelease.version}.`);
}
info(`Verifying Java package signature...`);
try {
await verifyPackageSignature(javaArchivePath, javaRelease.signatureUrl, this.verifySignaturePublicKey ?? ADOPTIUM_PUBLIC_KEY);
}
catch (error) {
throw new Error(`Failed to verify signature for Temurin version ${javaRelease.version} from ${javaRelease.signatureUrl}: ${error.message}`, { cause: error });
}
}
let javaArchivePath = await this.downloadPackage(javaRelease);
info(`Extracting Java archive...`);
const extension = getDownloadArchiveExtension();
if (process.platform === 'win32') {
@@ -129936,20 +129958,49 @@ class TemurinDistribution extends JavaBase {
const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const archiveName = external_fs_default().readdirSync(extractedJavaPath)[0];
const archivePath = external_path_default().join(extractedJavaPath, archiveName);
const javaHome = process.platform === 'darwin'
? external_path_default().join(archivePath, MACOS_JAVA_CONTENT_POSTFIX)
: archivePath;
if (this.includeJmods && !external_fs_default().existsSync(external_path_default().join(javaHome, 'jmods'))) {
await this.installJmods(javaRelease.version, javaHome);
}
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await cacheDir(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
get toolcacheFolderName() {
return super.toolcacheFolderName;
}
supportsSignatureVerification() {
return true;
}
async getAvailableVersions() {
async downloadPackage(release) {
const archivePath = await downloadTool(release.url);
if (this.verifySignature) {
if (!release.signatureUrl) {
throw new Error(`Input 'verify-signature' is enabled, but no signature URL was found for Temurin version ${release.version}.`);
}
info(`Verifying Java package signature...`);
try {
await verifyPackageSignature(archivePath, release.signatureUrl, this.verifySignaturePublicKey ?? ADOPTIUM_PUBLIC_KEY);
}
catch (error) {
throw new Error(`Failed to verify signature for Temurin version ${release.version} from ${release.signatureUrl}: ${error.message}`, { cause: error });
}
}
return archivePath;
}
async installJmods(version, javaHome) {
const jmodsRelease = await this.resolvePackage(version, 'jmods');
info(`Downloading JMODs ${jmodsRelease.version} (${this.distribution}) from ${jmodsRelease.url} ...`);
let jmodsArchivePath = await this.downloadPackage(jmodsRelease);
if (process.platform === 'win32') {
jmodsArchivePath = renameWinArchive(jmodsArchivePath);
}
const extractedJmodsPath = await extractJdkFile(jmodsArchivePath, getDownloadArchiveExtension());
const jmodsDirectory = external_path_default().join(extractedJmodsPath, external_fs_default().readdirSync(extractedJmodsPath)[0]);
external_fs_default().cpSync(jmodsDirectory, external_path_default().join(javaHome, 'jmods'), { recursive: true });
}
async getAvailableVersions(imageType = this.includeJmods ? 'jdk' : this.packageType) {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
const imageType = this.packageType;
const versionRange = encodeURI('[1.0,100.0]'); // retrieve all available versions
const releaseType = this.stable ? 'ga' : 'ea';
if (isDebug()) {
@@ -131882,6 +131933,109 @@ class KonaDistribution extends JavaBase {
}
}
;// CONCATENATED MODULE: ./src/distributions/openjdk/installer.ts
const OPENJDK_BASE_URL = 'https://jdk.java.net';
class OpenJdkDistribution extends JavaBase {
constructor(installerOptions) {
super('Oracle OpenJDK', installerOptions);
}
async findPackageForDownload(range) {
if (this.packageType !== 'jdk') {
throw new Error('Oracle OpenJDK provides only the `jdk` package type');
}
const arch = this.distributionArchitecture();
if (!['x64', 'aarch64'].includes(arch)) {
throw new Error(`Unsupported architecture: ${this.architecture}`);
}
const platform = this.getPlatform();
const releases = await this.getAvailableVersions(platform, arch);
const matchingReleases = releases
.filter(release => isVersionSatisfies(range, release.version))
.sort((left, right) => -semver_default().compareBuild(left.version, right.version));
if (!matchingReleases.length) {
throw this.createVersionNotFoundError(range, releases.map(release => release.version), `Platform: ${platform}`);
}
return matchingReleases[0];
}
async downloadTool(javaRelease) {
info(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await downloadTool(javaRelease.url);
info(`Extracting Java archive...`);
const extension = javaRelease.url.endsWith('.zip') ? 'zip' : 'tar.gz';
if (extension === 'zip') {
javaArchivePath = renameWinArchive(javaArchivePath);
}
const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const archiveName = external_fs_default().readdirSync(extractedJavaPath)[0];
const archivePath = external_path_default().join(extractedJavaPath, archiveName);
const javaPath = await cacheDir(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async getAvailableVersions(platform, arch) {
const homePage = await this.fetchPage(`${OPENJDK_BASE_URL}/`);
const releasePageUrls = Array.from(homePage.matchAll(/href="\/(\d+)\/">JDK\s+\d+/g), match => `${OPENJDK_BASE_URL}/${match[1]}/`);
const pages = await Promise.all(releasePageUrls.map(url => this.fetchPage(url)));
if (this.stable) {
pages.push(await this.fetchPage(`${OPENJDK_BASE_URL}/archive/`));
}
const releases = pages.flatMap(page => this.parseReleases(page, platform, arch));
return releases.filter(release => release.url.includes('/early_access/') !== this.stable);
}
async fetchPage(url) {
const response = await this.http.get(url);
return response.readBody();
}
parseReleases(html, platform, arch) {
const platformPattern = platform === 'macos' ? '(?:macos|osx)' : platform;
const extensionPattern = platform === 'windows' ? '(?:zip|tar\\.gz)' : 'tar\\.gz';
const pattern = new RegExp(`href="(https://download\\.java\\.net/[^"]+/openjdk-([^"_]+)_${platformPattern}-${arch}_bin\\.${extensionPattern})"`, 'g');
return Array.from(html.matchAll(pattern), match => {
const url = match[1];
const build = url.match(/\/(\d+)\/(?:GPL\/)?openjdk-/)?.[1] ??
this.findBuildInArchiveHeading(html, match.index, match[2]);
return {
version: this.toSemver(match[2], build),
url
};
});
}
findBuildInArchiveHeading(html, assetIndex, version) {
const headings = Array.from(html.slice(0, assetIndex).matchAll(/\(build\s+([^)]+)\)/g));
const headingVersion = headings.at(-1)?.[1];
if (!headingVersion) {
return undefined;
}
const [javaVersion, build] = headingVersion.split('+');
return javaVersion === version ? build : undefined;
}
toSemver(version, urlBuild) {
const [javaVersion, filenameBuild] = version.replace('-ea', '').split('+');
const versionParts = javaVersion.split('.');
const normalizedVersion = convertVersionToSemver(versionParts.length === 1 ? `${javaVersion}.0.0` : javaVersion);
const build = filenameBuild ?? (versionParts.length <= 3 ? urlBuild : undefined);
return build ? `${normalizedVersion}+${build}` : normalizedVersion;
}
getPlatform(platform = process.platform) {
switch (platform) {
case 'darwin':
return 'macos';
case 'linux':
return 'linux';
case 'win32':
return 'windows';
default:
throw new Error(`Platform '${platform}' is not supported. Supported platforms: 'linux', 'macos', 'windows'`);
}
}
}
;// CONCATENATED MODULE: ./src/distributions/distribution-factory.ts
@@ -131898,6 +132052,7 @@ class KonaDistribution extends JavaBase {
var JavaDistribution;
(function (JavaDistribution) {
JavaDistribution["Adopt"] = "adopt";
@@ -131918,8 +132073,13 @@ var JavaDistribution;
JavaDistribution["GraalVMCommunity"] = "graalvm-community";
JavaDistribution["JetBrains"] = "jetbrains";
JavaDistribution["Kona"] = "kona";
JavaDistribution["OracleOpenJdk"] = "oracle-openjdk";
})(JavaDistribution || (JavaDistribution = {}));
function getJavaDistribution(distributionName, installerOptions, jdkFile) {
if (installerOptions.packageType === 'jdk+jmods' &&
distributionName !== JavaDistribution.Temurin) {
throw new Error("java-package 'jdk+jmods' is only supported for distribution 'temurin'.");
}
switch (distributionName) {
case JavaDistribution.JdkFile:
return new LocalDistribution(installerOptions, jdkFile);
@@ -131956,6 +132116,8 @@ function getJavaDistribution(distributionName, installerOptions, jdkFile) {
return new JetBrainsDistribution(installerOptions);
case JavaDistribution.Kona:
return new KonaDistribution(installerOptions);
case JavaDistribution.OracleOpenJdk:
return new OpenJdkDistribution(installerOptions);
default:
return null;
}
@@ -132049,14 +132211,12 @@ async function run() {
const setDefault = util_getBooleanInput(INPUT_SET_DEFAULT, true);
const verifySignature = util_getBooleanInput(INPUT_VERIFY_SIGNATURE, false);
const verifySignaturePublicKey = getInput(INPUT_VERIFY_SIGNATURE_PUBLIC_KEY) || undefined;
let toolchainIds = getMultilineInput(INPUT_MVN_TOOLCHAIN_ID);
const toolchainIds = getMultilineInput(INPUT_MVN_TOOLCHAIN_ID);
startGroup('Installed distributions');
if (versions.length !== toolchainIds.length) {
toolchainIds = [];
}
if (!versions.length && !versionFile) {
throw new Error('java-version or java-version-file input expected');
}
validateToolchainIds(versions, versionFile, toolchainIds);
if (!versions.length) {
core_debug('java-version input is empty, looking for java-version-file input');
const content = external_fs_default().readFileSync(versionFile).toString().trim();

View File

@@ -15,6 +15,7 @@
- [JetBrains](#JetBrains)
- [Tencent Kona](#Tencent-Kona)
- [Installing custom Java package type](#Installing-custom-Java-package-type)
- [Package compatibility](#Package-compatibility)
- [JavaFX Maven project](#JavaFX-Maven-project)
- [Ensuring the Maven cache is complete (plugin dependencies)](#ensuring-the-maven-cache-is-complete-plugin-dependencies)
- [Installing custom Java architecture](#Installing-custom-Java-architecture)
@@ -44,6 +45,7 @@ steps:
with:
distribution: 'temurin'
java-version: '25'
java-package: 'jdk+jmods' # optional, includes JMOD files with JDK 24 and later
- run: java --version
```
@@ -154,6 +156,21 @@ steps:
- run: java --version
```
### Oracle OpenJDK
Oracle OpenJDK builds are created and hosted by Oracle under GPLv2+CE. To install the latest early-access build for a feature release, append `-ea` to the Java version:
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: 'oracle-openjdk'
java-version: '27-ea'
- run: java --version
```
Using `27` without the `-ea` suffix selects a stable (GA) release. Oracle archives OpenJDK builds after a limited number of releases and no longer provides security updates for them. To continue receiving security patches, move to Oracle JDK or choose a different vendor.
### Alibaba Dragonwell
**NOTE:** Alibaba Dragonwell only provides jdk.
@@ -266,14 +283,59 @@ steps:
```
## Installing custom Java package type
The `java-package` input selects the vendor artifact to install. It defaults to
`jdk`. Package availability is a combination of distribution, Java version,
operating system, and architecture; a package listed below can still be absent
for a particular platform or patch release. Unless a fixed version range is
called out, `setup-java` queries the distribution's catalog and installs the
newest artifact matching `java-version`.
The package types have these meanings:
- `jdk` and `jre` select a development kit or runtime image, respectively.
- `+fx` selects a vendor bundle that includes JavaFX.
- `+crac` selects an Azul Zulu build with CRaC support.
- `+jmods` installs the Temurin JDK and adds its separately published JMOD
archive when the JDK does not already contain a `jmods` directory.
- `+jcef` and `+ft` select JetBrains Runtime bundles with JCEF or FreeType.
### Package compatibility
| Distribution | Supported `java-package` values | Version support and important details |
| --- | --- | --- |
| `temurin` | `jdk`, `jre`, `jdk+jmods` | `jdk` and `jre` follow the Adoptium catalog. `jdk+jmods` is available for Java 24 and later and resolves both artifacts at the exact same Java version. |
| `adopt`, `adopt-hotspot` | `jdk`, `jre` | HotSpot requests check Temurin first, then fall back to the archived AdoptOpenJDK catalog (Java 8 through 16). Migrate to `temurin` for supported releases. |
| `adopt-openj9` | `jdk`, `jre` | Uses the archived AdoptOpenJDK OpenJ9 catalog, which ended at Java 16. Migrate to `semeru`. Some historical JRE/platform combinations were not published. |
| `zulu` | `jdk`, `jre`, `jdk+fx`, `jre+fx`, `jdk+crac`, `jre+crac` | Standard JDK builds go back to Java 6; JRE and JavaFX bundles start at Java 8. The vendor catalog has gaps among older non-LTS releases. CRaC bundles start at Java 17 and have more limited OS and architecture availability. |
| `liberica` | `jdk`, `jre`, `jdk+fx`, `jre+fx` | Standard JDK builds go back to Java 8 in the supported action catalog; JRE and JavaFX "full" bundles also start at Java 8. Exact versions follow BellSoft's catalog for the requested platform. |
| `liberica-nik` | `jdk`, `jdk+fx` | `java-version` selects the embedded JDK version, not the NIK/GraalVM release number. BellSoft currently publishes matching standard and JavaFX "full" bundles for JDK 11 and later, with gaps between feature releases. Other values are not meaningful: they resolve to the standard bundle. |
| `microsoft` | `jdk` | Stable builds only. The bundled manifest contains Java 11, 16, 17, 21, and 25 releases; platform availability varies by release. |
| `semeru` | `jdk`, `jre` | Stable OpenJ9 builds only. IBM publishes both image types for the supported release lines (currently 8, 11, 17, 21, and 25), subject to platform availability. |
| `corretto` | `jdk`, `jre` | Accepts major versions only. JDK availability follows Amazon's platform catalog. For the operating systems directly selected by `setup-java`, JRE downloads are limited to Java 8 on Windows; Linux and macOS use `jdk`. |
| `oracle` | `jdk` | Stable Oracle JDK 17 and later only. |
| `oracle-openjdk` | `jdk` | Installs the GA or early-access JDK builds currently listed or archived on `jdk.java.net`; use a `-ea` version such as `27-ea` for early access. |
| `dragonwell` | `jdk` | Stable builds only. The current vendor catalog provides Java 8, 11, 17, 21, and 25. |
| `sapmachine` | `jdk`, `jre` | Follows the SapMachine catalog. Both editions are represented from Java 10 onward, but individual versions and platforms can differ. |
| `graalvm` | `jdk` | Stable Oracle GraalVM for JDK 17 and later only. |
| `graalvm-community` | `jdk` | Stable GraalVM Community releases for JDK 17 and later only. |
| `jetbrains` | `jdk`, `jre`, `jdk+jcef`, `jre+jcef`, `jdk+ft`, `jre+ft` | JetBrains publishes selected LTS-based releases rather than every OpenJDK patch. JDK/JRE and JCEF bundles start with the Java 11 release family; FreeType bundles start with Java 17. Exact package, LTS family, patch, OS, and architecture availability is determined from release assets. |
| `kona` | `jdk` | Stable Java 8, 11, 17, 21, and 25 releases only. |
| `jdkfile` | `jdk` (recommended) | The package contents and version are supplied by `jdk-file`; `setup-java` does not validate them. `java-package` only separates the local archive's tool-cache entry, so use `jdk` unless separate cache namespaces are required. |
Values outside this table are unsupported even when a distribution forwards the
value to its vendor API instead of rejecting it immediately. In that case, the
action normally fails with a version-not-found error because no matching
artifact exists.
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: '<distribution>'
java-version: '25'
java-package: jdk # optional (jdk or jre) - defaults to jdk
distribution: 'semeru'
java-version: '21'
java-package: jre
- run: java --version
```
@@ -469,7 +531,7 @@ In this example, `JAVA_HOME` and `java` on `PATH` point to Java 17, while Java 2
If your use-case requires a custom distribution or a version that is not provided by setup-java, you can download it manually and setup-java will take care of the installation and caching on the VM:
> [!NOTE]
> This approach also lets you use builds that setup-java does not provide directly, such as **Early Access (EA)** or other unreleased JDK builds (for example, an upcoming feature release or a Loom/Valhalla preview build). Download the desired archive in a prior step and point `jdk-file` at it; setup-java will extract, install, and cache it just like a supported distribution. When targeting multiple architectures, select the correct binary per architecture in your workflow (for example, with a build matrix).
> This approach also lets you use builds that setup-java does not provide directly, such as unreleased Loom/Valhalla preview builds or early-access builds not exposed by a supported distribution. Download the desired archive in a prior step and point `jdk-file` at it; setup-java will extract, install, and cache it just like a supported distribution. When targeting multiple architectures, select the correct binary per architecture in your workflow (for example, with a build matrix).
```yaml
steps:
@@ -486,23 +548,6 @@ steps:
- run: java --version
```
For example, to use an **Early Access** build from [jdk.java.net](https://jdk.java.net/), download the archive for your runner OS/architecture and install it via `distribution: 'jdkfile'` (example below assumes Linux x64):
```yaml
steps:
- run: |
download_url="https://download.java.net/java/early_access/jdk25/36/GPL/openjdk-25-ea+36_linux-x64_bin.tar.gz"
wget -O $RUNNER_TEMP/java_package.tar.gz $download_url
- uses: actions/setup-java@v6
with:
distribution: 'jdkfile'
jdk-file: ${{ runner.temp }}/java_package.tar.gz
java-version: '25.0.0-ea.36'
architecture: x64
- run: java --version
```
If your use-case requires a custom distribution (in the example, alpine-linux is used) or a version that is not provided by setup-java and you want to always install the latest version during runtime, then you can use the following code to auto-download the latest JDK, determine the semver needed for setup-java, and setup-java will take care of the installation and caching on the VM:
```yaml
@@ -935,7 +980,7 @@ steps:
- run: java --version
```
In case you install multiple versions of Java at once you can use the same syntax as used in `java-versions`. Please note that you have to declare an ID for all Java versions that will be installed or the `mvn-toolchain-id` instruction will be skipped wholesale due to mapping ambiguities.
When installing multiple Java versions, use the same multiline syntax as `java-version`. You must declare exactly one ID for every Java version that will be installed. The action fails before installing a JDK unless the number of `mvn-toolchain-id` entries matches the number of `java-version` entries, or is exactly one when `java-version-file` is used.
```yaml
steps:

View File

@@ -319,8 +319,20 @@ async function saveAdditionalCache(
);
return;
}
const globber = await glob.create(additionalCache.path.join('\n'), {
implicitDescendants: false
});
const cachePaths = await globber.glob();
if (cachePaths.length === 0) {
core.debug(
`${additionalCache.name} cache paths do not exist, not saving cache.`
);
return;
}
try {
const cacheId = await cache.saveCache(additionalCache.path, primaryKey);
const cacheId = await cache.saveCache(cachePaths, primaryKey);
if (cacheId === -1) {
core.debug(
`${additionalCache.name} cache was not saved for the key: ${primaryKey}`

View File

@@ -21,6 +21,7 @@ import {
} from './graalvm/installer.js';
import {JetBrainsDistribution} from './jetbrains/installer.js';
import {KonaDistribution} from './kona/installer.js';
import {OpenJdkDistribution} from './openjdk/installer.js';
enum JavaDistribution {
Adopt = 'adopt',
@@ -40,7 +41,8 @@ enum JavaDistribution {
GraalVM = 'graalvm',
GraalVMCommunity = 'graalvm-community',
JetBrains = 'jetbrains',
Kona = 'kona'
Kona = 'kona',
OracleOpenJdk = 'oracle-openjdk'
}
export function getJavaDistribution(
@@ -48,6 +50,15 @@ export function getJavaDistribution(
installerOptions: JavaInstallerOptions,
jdkFile?: string
): JavaBase | null {
if (
installerOptions.packageType === 'jdk+jmods' &&
distributionName !== JavaDistribution.Temurin
) {
throw new Error(
"java-package 'jdk+jmods' is only supported for distribution 'temurin'."
);
}
switch (distributionName) {
case JavaDistribution.JdkFile:
return new LocalDistribution(installerOptions, jdkFile);
@@ -93,6 +104,8 @@ export function getJavaDistribution(
return new JetBrainsDistribution(installerOptions);
case JavaDistribution.Kona:
return new KonaDistribution(installerOptions);
case JavaDistribution.OracleOpenJdk:
return new OpenJdkDistribution(installerOptions);
default:
return null;
}

View File

@@ -0,0 +1,181 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
import semver from 'semver';
import {JavaBase} from '../base-installer.js';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models.js';
import {
convertVersionToSemver,
extractJdkFile,
isVersionSatisfies,
renameWinArchive
} from '../../util.js';
const OPENJDK_BASE_URL = 'https://jdk.java.net';
export class OpenJdkDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('Oracle OpenJDK', installerOptions);
}
protected async findPackageForDownload(
range: string
): Promise<JavaDownloadRelease> {
if (this.packageType !== 'jdk') {
throw new Error('Oracle OpenJDK provides only the `jdk` package type');
}
const arch = this.distributionArchitecture();
if (!['x64', 'aarch64'].includes(arch)) {
throw new Error(`Unsupported architecture: ${this.architecture}`);
}
const platform = this.getPlatform();
const releases = await this.getAvailableVersions(platform, arch);
const matchingReleases = releases
.filter(release => isVersionSatisfies(range, release.version))
.sort((left, right) => -semver.compareBuild(left.version, right.version));
if (!matchingReleases.length) {
throw this.createVersionNotFoundError(
range,
releases.map(release => release.version),
`Platform: ${platform}`
);
}
return matchingReleases[0];
}
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
let javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
const extension = javaRelease.url.endsWith('.zip') ? 'zip' : 'tar.gz';
if (extension === 'zip') {
javaArchivePath = renameWinArchive(javaArchivePath);
}
const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaRelease.version),
this.architecture
);
return {version: javaRelease.version, path: javaPath};
}
private async getAvailableVersions(
platform: string,
arch: string
): Promise<JavaDownloadRelease[]> {
const homePage = await this.fetchPage(`${OPENJDK_BASE_URL}/`);
const releasePageUrls = Array.from(
homePage.matchAll(/href="\/(\d+)\/">JDK\s+\d+/g),
match => `${OPENJDK_BASE_URL}/${match[1]}/`
);
const pages = await Promise.all(
releasePageUrls.map(url => this.fetchPage(url))
);
if (this.stable) {
pages.push(await this.fetchPage(`${OPENJDK_BASE_URL}/archive/`));
}
const releases = pages.flatMap(page =>
this.parseReleases(page, platform, arch)
);
return releases.filter(
release => release.url.includes('/early_access/') !== this.stable
);
}
private async fetchPage(url: string): Promise<string> {
const response = await this.http.get(url);
return response.readBody();
}
private parseReleases(
html: string,
platform: string,
arch: string
): JavaDownloadRelease[] {
const platformPattern = platform === 'macos' ? '(?:macos|osx)' : platform;
const extensionPattern =
platform === 'windows' ? '(?:zip|tar\\.gz)' : 'tar\\.gz';
const pattern = new RegExp(
`href="(https://download\\.java\\.net/[^"]+/openjdk-([^"_]+)_${platformPattern}-${arch}_bin\\.${extensionPattern})"`,
'g'
);
return Array.from(html.matchAll(pattern), match => {
const url = match[1];
const build =
url.match(/\/(\d+)\/(?:GPL\/)?openjdk-/)?.[1] ??
this.findBuildInArchiveHeading(html, match.index, match[2]);
return {
version: this.toSemver(match[2], build),
url
};
});
}
private findBuildInArchiveHeading(
html: string,
assetIndex: number,
version: string
): string | undefined {
const headings = Array.from(
html.slice(0, assetIndex).matchAll(/\(build\s+([^)]+)\)/g)
);
const headingVersion = headings.at(-1)?.[1];
if (!headingVersion) {
return undefined;
}
const [javaVersion, build] = headingVersion.split('+');
return javaVersion === version ? build : undefined;
}
private toSemver(version: string, urlBuild?: string): string {
const [javaVersion, filenameBuild] = version.replace('-ea', '').split('+');
const versionParts = javaVersion.split('.');
const normalizedVersion = convertVersionToSemver(
versionParts.length === 1 ? `${javaVersion}.0.0` : javaVersion
);
const build =
filenameBuild ?? (versionParts.length <= 3 ? urlBuild : undefined);
return build ? `${normalizedVersion}+${build}` : normalizedVersion;
}
private getPlatform(platform: NodeJS.Platform = process.platform): string {
switch (platform) {
case 'darwin':
return 'macos';
case 'linux':
return 'linux';
case 'win32':
return 'windows';
default:
throw new Error(
`Platform '${platform}' is not supported. Supported platforms: 'linux', 'macos', 'windows'`
);
}
}
}

View File

@@ -9,6 +9,7 @@ import * as gpg from '../../gpg.js';
import {ADOPTIUM_PUBLIC_KEY} from './adoptium-key.js';
import {JavaBase} from '../base-installer.js';
import {ITemurinAvailableVersions} from './models.js';
import {MACOS_JAVA_CONTENT_POSTFIX} from '../../constants.js';
import {
JavaDownloadRelease,
JavaInstallerOptions,
@@ -31,11 +32,14 @@ export enum TemurinImplementation {
}
export class TemurinDistribution extends JavaBase {
private readonly includeJmods: boolean;
constructor(
installerOptions: JavaInstallerOptions,
private readonly jvmImpl: TemurinImplementation
) {
super(`Temurin-${jvmImpl}`, installerOptions);
this.includeJmods = this.packageType === 'jdk+jmods';
}
/**
@@ -44,7 +48,17 @@ export class TemurinDistribution extends JavaBase {
public async findPackageForDownload(
version: string
): Promise<JavaDownloadRelease> {
const availableVersionsRaw = await this.getAvailableVersions();
return this.resolvePackage(
version,
this.includeJmods ? 'jdk' : this.packageType
);
}
private async resolvePackage(
version: string,
imageType: string
): Promise<JavaDownloadRelease> {
const availableVersionsRaw = await this.getAvailableVersions(imageType);
const availableVersionsWithBinaries = availableVersionsRaw
.filter(item => item.binaries.length > 0)
.map(item => {
@@ -83,30 +97,7 @@ export class TemurinDistribution extends JavaBase {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
let javaArchivePath = await tc.downloadTool(javaRelease.url);
if (this.verifySignature) {
if (!javaRelease.signatureUrl) {
throw new Error(
`Input 'verify-signature' is enabled, but no signature URL was found for Temurin version ${javaRelease.version}.`
);
}
core.info(`Verifying Java package signature...`);
try {
await gpg.verifyPackageSignature(
javaArchivePath,
javaRelease.signatureUrl,
this.verifySignaturePublicKey ?? ADOPTIUM_PUBLIC_KEY
);
} catch (error) {
throw new Error(
`Failed to verify signature for Temurin version ${javaRelease.version} from ${javaRelease.signatureUrl}: ${
(error as Error).message
}`,
{cause: error}
);
}
}
let javaArchivePath = await this.downloadPackage(javaRelease);
core.info(`Extracting Java archive...`);
const extension = getDownloadArchiveExtension();
@@ -117,6 +108,13 @@ export class TemurinDistribution extends JavaBase {
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaHome =
process.platform === 'darwin'
? path.join(archivePath, MACOS_JAVA_CONTENT_POSTFIX)
: archivePath;
if (this.includeJmods && !fs.existsSync(path.join(javaHome, 'jmods'))) {
await this.installJmods(javaRelease.version, javaHome);
}
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tc.cacheDir(
@@ -129,18 +127,64 @@ export class TemurinDistribution extends JavaBase {
return {version: javaRelease.version, path: javaPath};
}
protected get toolcacheFolderName(): string {
return super.toolcacheFolderName;
}
protected supportsSignatureVerification(): boolean {
return true;
}
private async getAvailableVersions(): Promise<ITemurinAvailableVersions[]> {
private async downloadPackage(release: JavaDownloadRelease): Promise<string> {
const archivePath = await tc.downloadTool(release.url);
if (this.verifySignature) {
if (!release.signatureUrl) {
throw new Error(
`Input 'verify-signature' is enabled, but no signature URL was found for Temurin version ${release.version}.`
);
}
core.info(`Verifying Java package signature...`);
try {
await gpg.verifyPackageSignature(
archivePath,
release.signatureUrl,
this.verifySignaturePublicKey ?? ADOPTIUM_PUBLIC_KEY
);
} catch (error) {
throw new Error(
`Failed to verify signature for Temurin version ${release.version} from ${release.signatureUrl}: ${
(error as Error).message
}`,
{cause: error}
);
}
}
return archivePath;
}
private async installJmods(version: string, javaHome: string): Promise<void> {
const jmodsRelease = await this.resolvePackage(version, 'jmods');
core.info(
`Downloading JMODs ${jmodsRelease.version} (${this.distribution}) from ${jmodsRelease.url} ...`
);
let jmodsArchivePath = await this.downloadPackage(jmodsRelease);
if (process.platform === 'win32') {
jmodsArchivePath = renameWinArchive(jmodsArchivePath);
}
const extractedJmodsPath = await extractJdkFile(
jmodsArchivePath,
getDownloadArchiveExtension()
);
const jmodsDirectory = path.join(
extractedJmodsPath,
fs.readdirSync(extractedJmodsPath)[0]
);
fs.cpSync(jmodsDirectory, path.join(javaHome, 'jmods'), {recursive: true});
}
private async getAvailableVersions(
imageType = this.includeJmods ? 'jdk' : this.packageType
): Promise<ITemurinAvailableVersions[]> {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
const imageType = this.packageType;
const versionRange = encodeURI('[1.0,100.0]'); // retrieve all available versions
const releaseType = this.stable ? 'ga' : 'ea';

View File

@@ -40,18 +40,18 @@ async function run() {
);
const verifySignaturePublicKey =
core.getInput(constants.INPUT_VERIFY_SIGNATURE_PUBLIC_KEY) || undefined;
let toolchainIds = core.getMultilineInput(constants.INPUT_MVN_TOOLCHAIN_ID);
const toolchainIds = core.getMultilineInput(
constants.INPUT_MVN_TOOLCHAIN_ID
);
core.startGroup('Installed distributions');
if (versions.length !== toolchainIds.length) {
toolchainIds = [];
}
if (!versions.length && !versionFile) {
throw new Error('java-version or java-version-file input expected');
}
toolchains.validateToolchainIds(versions, versionFile, toolchainIds);
if (!versions.length) {
core.debug(
'java-version input is empty, looking for java-version-file input'

View File

@@ -14,6 +14,23 @@ interface JdkInfo {
jdkHome: string;
}
export function validateToolchainIds(
versions: string[],
versionFile: string,
toolchainIds: string[]
) {
if (!toolchainIds.length) {
return;
}
const versionCount = versions.length || (versionFile ? 1 : 0);
if (versionCount !== toolchainIds.length) {
throw new Error(
`The number of Maven toolchain IDs (${toolchainIds.length}) must match the number of Java versions (${versionCount})`
);
}
}
export async function configureToolchains(
version: string,
distributionName: string,

View File

@@ -20,8 +20,21 @@ export function getTempDir() {
}
export function getBooleanInput(inputName: string, defaultValue = false) {
return (
(core.getInput(inputName) || String(defaultValue)).toUpperCase() === 'TRUE'
const inputValue = core.getInput(inputName);
const normalizedValue = inputValue.trim().toLowerCase();
if (!normalizedValue) {
return defaultValue;
}
if (normalizedValue === 'true') {
return true;
}
if (normalizedValue === 'false') {
return false;
}
throw new Error(
`Invalid value '${inputValue}' for boolean input '${inputName}'. Expected 'true' or 'false'.`
);
}