Unverified Commit 955f34f1 authored by Bruno Borges's avatar Bruno Borges Committed by GitHub
Browse files

Add conditional JDK caching (#1201)

* Add JDK caching

Cache resolved JDK tool-cache entries by exact platform and release identity, with a default-on cache-jdk input and explicit opt-out.

Co-authored-by: default avatarCopilot App <[email protected]>

* Apply batched suggestions from code review

Co-authored-by: default avatarCopilot Autofix powered by AI <[email protected]>

* Fix JDK cache CI validation

Co-authored-by: default avatarCopilot App <[email protected]>

* Update brace-expansion security fix

Co-authored-by: default avatarCopilot App <[email protected]>

* Refresh brace-expansion license metadata

Co-authored-by: default avatarCopilot App <[email protected]>

* Refine JDK cache semantics

Co-authored-by: default avatarCopilot App <[email protected]>

* Refine JDK cache documentation

Co-authored-by: default avatarCopilot App <[email protected]>

* Simplify JDK cache identity

Use one normalized runner OS dimension, reset the internal cache key schema for the unreleased feature, and align documentation, tests, and bundles.

Co-authored-by: default avatarCopilot App <[email protected]>

* Align JDK cache OS identity

Use the established RUNNER_OS value directly and retain process.platform only as a non-Actions fallback.

Co-authored-by: default avatarCopilot App <[email protected]>

* Harden JDK cache saves and document tool-cache reuse

Bind each JDK cache key to the installation identity it was computed for,
keep post-job saves best-effort per entry, and state the real reuse and
verification guarantee in the documentation.

Co-authored-by: default avatarCopilot App <[email protected]>

* docs: restructure README caching section

Rename '## Caching dependencies' to '## Caching' and add a what-gets-cached
overview table covering the dependency, wrapper, and JDK caches. Lead with the
common 'cache: maven' example and the dependency-cache material, and demote JDK
caching into its own subsection.

Also corrects the IMPORTANT callout, which implied JDK caching required an
explicit opt-in; it is enabled implicitly whenever 'cache' is set.

Co-authored-by: default avatarCopilot App <[email protected]>

* docs: fix caching documentation defects

- Remove pull-request framing that compared behavior to `main`; state the
  tool-cache and `jdkfile` behavior directly and unconditionally.
- Clarify that the JDK cache is a separate cache *entry* from the dependency
  and wrapper caches, while its *enablement* is coupled to `cache`, so the
  opening paragraph agrees with the enablement matrix.
- Cite the actions/setup-java-benchmarks repository instead of an open PR and
  a self-referential PR comment, keeping the measured figures and caveats.
- Keep the `cache`/`cache-jdk` matrix only in docs/advanced-usage.md and
  summarize the rules in prose in README.md to avoid divergence.
- Describe the guarantee that a cache key is only saved with the installation
  it was computed for, instead of documenting inode/size/timestamp internals.

Co-authored-by: default avatarCopilot App <[email protected]>

* docs: add V6 what's new entry for JDK caching

Co-authored-by: default avatarCopilot App <[email protected]>
Copilot-Session: e2755464-4e83-47b6-ba71-731bb481b418

---------

Co-authored-by: default avatarCopilot App <[email protected]>
Co-authored-by: default avatarCopilot Autofix powered by AI <[email protected]>
Copilot-Session: e2755464-4e83-47b6-ba71-731bb481b418
parent 7a9a8b1d
Loading
Loading
Loading
Loading
+38 −18
Changes for README.md: 38 added lines, 18 removed lines.
Original line number Diff line number Diff line
@@ -33,7 +33,7 @@ steps:
- [Inputs](#inputs)
- [Supported distributions](#supported-distributions)
- [Supported version syntax](#supported-version-syntax)
- [Caching dependencies](#caching-dependencies)
- [Caching](#caching)
- [Multiple JDKs and Maven toolchains](#multiple-jdks-and-maven-toolchains)
- [Publishing packages](#publishing-packages)
- [Advanced usage](#advanced-usage)
@@ -61,6 +61,7 @@ steps:
- JDK downloads now automatically verify authoritative checksums for [supported distributions](#download-integrity-and-signatures).
- Added `force-download: true` to bypass the tool cache and perform a reproducible fresh install.
- Dependency caching now supports custom paths with `cache-path` and restore-only operation with `cache-read-only: true`.
- Downloaded JDKs are now [cached](#caching-jdk-installations) automatically when `cache` is set; use `cache-jdk` to enable or disable it independently.
- Set `problem-matcher: false` to disable Java compiler and uncaught-exception annotations.
- GraalVM distributions now set `GRAALVM_HOME` in addition to `JAVA_HOME`.
- Invalid boolean values, unsupported distribution/package/platform combinations, and mismatched Maven toolchain ID counts now fail with targeted errors.
@@ -161,9 +162,10 @@ steps:
| `verify-signature-public-key` | ASCII-armored GPG public key to use for signature verification. Overrides the bundled key. | |
| `token` | Token for fetching GitHub.com-hosted version manifests, useful on GitHub Enterprise Server when unauthenticated requests are rate-limited. | `${{ github.token }}` on GitHub.com; empty string on GHES |
| `cache` | Enable dependency caching for `maven`, `gradle`, or `sbt`. | |
| `cache-jdk` | Cache downloaded JDK installations between jobs. When omitted, JDK caching is enabled only if `cache` is set. Set explicitly to `true` or `false` to override. | Enabled when `cache` is set |
| `cache-dependency-path` | Dependency file paths used for cache key hashing. Supports globs and multiline values. | Auto-detected by package manager |
| `cache-path` | Cache paths to use instead of the package manager's default dependency cache path. Supports multiline values and exclusions. | |
| `cache-read-only` | Restore caches without saving changes in the post step. | `false` |
| `cache-read-only` | Restore dependency, wrapper, and JDK caches without saving changes in the post step. | `false` |
| `server-id` | Maven repository ID used in generated `settings.xml`. | `github` |
| `server-username-env-var` | Environment variable name for Maven repository username. | `GITHUB_ACTOR` |
| `server-password-env-var` | Environment variable name for Maven repository password or token. | `GITHUB_TOKEN` |
@@ -175,6 +177,8 @@ steps:
| `mvn-toolchain-vendor` | Maven Toolchain vendor value. | `${distribution}` |
| `show-download-progress` | Keep Maven artifact download and transfer progress in logs. When `false`, the action adds `-ntp` to `MAVEN_ARGS`. | `false` |

- `java-package`: Supported package types are `jdk`, `jre`, `jdk+fx`, `jre+fx`, `jdk+crac`, `jre+crac`, `jdk+jmods`, `jdk+jcef`, `jre+jcef`, `jdk+ft`, and `jre+ft`. Availability varies by distribution.

Deprecated aliases `jdkFile`, `server-username`, `server-password`, and `gpg-passphrase` remain accepted for compatibility, but should be replaced with the current input names.

## Outputs
@@ -238,11 +242,19 @@ GitHub-hosted runners primarily pre-cache Eclipse Temurin JDKs. See the installe

`setup-java` automatically verifies downloaded archive checksums when a selected distribution publishes an authoritative checksum. Automatic checksum verification currently applies to `temurin`, `semeru`, `corretto`, `dragonwell`, `kona`, `sapmachine`, `graalvm`, `graalvm-community`, `zulu`, `oracle`, `oracle-openjdk`, `microsoft`, and `jetbrains`.

Distributions or individual releases without an authoritative checksum continue to install normally, with the omission reported in debug logs. Archives resolved directly from the runner tool cache are not downloaded again and are not reverified.
Distributions or individual releases without an authoritative checksum continue to install normally, with the omission reported in debug logs. Installations resolved directly from the runner tool cache — including JDKs preinstalled on the runner image and JDKs installed by an earlier step of the same job — are not downloaded again and are not reverified, even when `verify-signature: true` is set. Use `force-download: true` to always download and verify the archive.

Use `verify-signature: true` to verify package signatures for distributions that support it. Currently supported distributions are `temurin` and `microsoft`; setting it for an unsupported distribution fails the workflow.

## Caching dependencies
## Caching

`setup-java` manages three kinds of caches. Each one is restored and saved as a separate cache entry.

| Cache | What it stores | Key based on | How it is enabled |
| --- | --- | --- | --- |
| Dependency cache | Downloaded dependencies, such as `~/.m2/repository`, `~/.gradle/caches`, or the sbt cache paths | Runner OS, architecture, package manager, and a hash of the dependency files | Set `cache` to `maven`, `gradle`, or `sbt` |
| Wrapper caches | Maven and Gradle wrapper distributions (`~/.m2/wrapper/dists`, `~/.gradle/wrapper`) | Runner OS, architecture, wrapper cache name, and a hash of the wrapper properties | Set `cache` to `maven` or `gradle` |
| JDK cache | The downloaded JDK installation | Runner OS, architecture, distribution, package type, resolved version, release identity, and signature-verification identity | Enabled implicitly whenever `cache` is set, or explicitly with `cache-jdk: true`. Opt out with `cache-jdk: false` |

Set `cache` to `maven`, `gradle`, or `sbt` to cache dependencies with minimal configuration.

@@ -294,9 +306,30 @@ Use `cache-path` when the build tool stores dependencies outside the default loc

`cache-path` changes what is restored and saved, but not the cache key. Jobs that should share a cache key must use the same OS, architecture, package manager, dependency files, and cache paths.

### Wrapper caches

Maven and Gradle wrapper distributions are restored and saved as additional cache entries, separate from the primary dependency cache. These entries have their own keys in the form `setup-java-<runner-os>-<node-arch>-<wrapper-cache-name>-<file-hash>`.

| Package manager | Wrapper cache name | Cached path | Files used for wrapper-cache key |
| --- | --- | --- | --- |
| Maven | `maven-wrapper` | `~/.m2/wrapper/dists` | `**/.mvn/wrapper/maven-wrapper.properties` |
| Gradle | `gradle-wrapper` | `~/.gradle/wrapper` | `**/gradle-wrapper.properties` |

These wrapper caches are independent from dependency caches, so they remain useful even when dependency files change frequently. The wrapper properties are also part of the Maven and Gradle primary dependency-cache key because wrapper changes can affect how dependencies are resolved, but the wrapper distribution files themselves are stored in the separate wrapper cache entries above.

For advanced Gradle caching features such as build output caching, configuration cache support, encrypted cache storage, cleanup, and fine-grained cache control, consider [`gradle/actions/setup-gradle`](https://github.com/gradle/actions/tree/main/setup-gradle).

### Caching JDK installations

The JDK cache stores the downloaded JDK installation so later runs skip the download. It is enabled implicitly whenever dependency `cache` is set, so most workflows that cache dependencies are already caching the JDK. Set `cache-jdk: true` to enable it without dependency caching, or `cache-jdk: false` to opt out while keeping dependency caching. With neither `cache` nor `cache-jdk` set, nothing is cached.

> [!IMPORTANT]
> Because JDK caching is on by default whenever `cache` is set, review [Caching JDK installations](docs/advanced-usage.md#caching-jdk-installations)
> for the full `cache`/`cache-jdk` matrix, cache identity and storage impact.

### Read-only caches

Set `cache-read-only: true` to restore dependency caches without saving changes in the post action. This is useful for pull requests, merge queues, short-lived branches, and matrix fan-out jobs that should only consume caches produced elsewhere.
Set `cache-read-only: true` to restore dependency, wrapper, and JDK caches without saving changes in the post action. This is useful for pull requests, merge queues, short-lived branches, and matrix fan-out jobs that should only consume caches produced elsewhere.

```yaml
- uses: actions/setup-java@v5
@@ -339,19 +372,6 @@ jobs:
      - run: mvn ${{ matrix.goal }}
```

### Wrapper caches

Maven and Gradle wrapper distributions are restored and saved as additional cache entries, separate from the primary dependency cache. These entries have their own keys in the form `setup-java-<runner-os>-<node-arch>-<wrapper-cache-name>-<file-hash>`.

| Package manager | Wrapper cache name | Cached path | Files used for wrapper-cache key |
| --- | --- | --- | --- |
| Maven | `maven-wrapper` | `~/.m2/wrapper/dists` | `**/.mvn/wrapper/maven-wrapper.properties` |
| Gradle | `gradle-wrapper` | `~/.gradle/wrapper` | `**/gradle-wrapper.properties` |

These wrapper caches are independent from dependency caches, so they remain useful even when dependency files change frequently. The wrapper properties are also part of the Maven and Gradle primary dependency-cache key because wrapper changes can affect how dependencies are resolved, but the wrapper distribution files themselves are stored in the separate wrapper cache entries above.

For advanced Gradle caching features such as build output caching, configuration cache support, encrypted cache storage, cleanup, and fine-grained cache control, consider [`gradle/actions/setup-gradle`](https://github.com/gradle/actions/tree/main/setup-gradle).

### Cache segment restore timeout

Cache downloads are split into segments. To reduce the chance of a stuck segment blocking a workflow, set `SEGMENT_DOWNLOAD_TIMEOUT_MINS`:
+152
Changes for __tests__/cleanup-java.test.ts: 152 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,9 @@ import {
  beforeAll,
  afterAll
} from '@jest/globals';
import fs from 'fs';
import os from 'os';
import path from 'path';

// Mock @actions/cache before importing source modules
const real_cache_module = await import('@actions/cache');
@@ -60,6 +63,9 @@ const core = await import('@actions/core');
const cache = await import('@actions/cache');
const {run: cleanup} = await import('../src/cleanup-java.js');
const util = await import('../src/util.js');
const {registerJdk, buildJdkCacheKey} = await import('../src/jdk-cache.js');

const jdkTempRoots: string[] = [];

describe('cleanup', () => {
  let spyWarning: any;
@@ -88,6 +94,9 @@ describe('cleanup', () => {
  });

  afterEach(() => {
    while (jdkTempRoots.length) {
      fs.rmSync(jdkTempRoots.pop()!, {recursive: true, force: true});
    }
    resetState();
    jest.resetAllMocks();
    jest.clearAllMocks();
@@ -163,6 +172,103 @@ describe('cleanup', () => {

    expect(spyCacheSave).toHaveBeenCalled();
  });

  it('saves the JDK cache without dependency caching', async () => {
    const {key, path: jdkPath, state} = createRegisteredJdk();
    (core.getInput as jest.Mock<any>).mockImplementation((name: string) =>
      name === 'cache-jdk' ? 'true' : ''
    );
    (core.getState as jest.Mock<any>).mockImplementation((name: string) =>
      name === 'jdk-caches' ? state : ''
    );
    spyCacheSave.mockResolvedValue(1);

    await cleanup();

    expect(spyCacheSave).toHaveBeenCalledWith([jdkPath], key);
  });

  it('does not save a JDK cache when cache-jdk is disabled', async () => {
    (core.getInput as jest.Mock<any>).mockImplementation((name: string) =>
      name === 'cache-jdk' ? 'false' : ''
    );

    await cleanup();

    expect(spyCacheSave).not.toHaveBeenCalled();
  });

  it.each([
    ['', '', false],
    ['', 'true', true],
    ['', 'false', false],
    ['maven', '', true],
    ['maven', 'true', true],
    ['maven', 'false', false]
  ])(
    'uses effective JDK caching for cache=%j and cache-jdk=%j',
    async (cacheInput, cacheJdkInput, expectedJdkSave) => {
      const {key: jdkKey, path: jdkPath, state} = createRegisteredJdk();
      (core.getInput as jest.Mock<any>).mockImplementation((name: string) => {
        if (name === 'cache') return cacheInput;
        if (name === 'cache-jdk') return cacheJdkInput;
        return '';
      });
      (core.getState as jest.Mock<any>).mockImplementation((name: string) =>
        name === 'jdk-caches' ? state : ''
      );
      spyCacheSave.mockResolvedValue(1);

      await cleanup();

      const jdkSaveCalls = spyCacheSave.mock.calls.filter(
        ([, key]) => key === jdkKey
      );
      expect(jdkSaveCalls).toHaveLength(expectedJdkSave ? 1 : 0);
      if (expectedJdkSave) {
        expect(spyCacheSave).toHaveBeenCalledWith([jdkPath], jdkKey);
      }
    }
  );

  it('keeps saving the remaining JDK caches when one save fails', async () => {
    const first = createRegisteredJdk();
    const second = createRegisteredJdk('17.0.19+9');
    (core.getInput as jest.Mock<any>).mockImplementation((name: string) =>
      name === 'cache-jdk' ? 'true' : ''
    );
    (core.getState as jest.Mock<any>).mockImplementation((name: string) =>
      name === 'jdk-caches' ? second.state : ''
    );
    spyCacheSave.mockImplementation(async (paths: string[]) => {
      if (paths[0] === first.path) {
        throw new Error('Unexpected save failure');
      }
      return 1;
    });

    await cleanup();

    expect(spyCacheSave).toHaveBeenCalledWith([first.path], first.key);
    expect(spyCacheSave).toHaveBeenCalledWith([second.path], second.key);
    expect(spyCoreError).not.toHaveBeenCalled();
  });

  it('does not save a JDK installation that was replaced after registration', async () => {
    const {key, path: jdkPath, state, replace} = createRegisteredJdk();
    (core.getInput as jest.Mock<any>).mockImplementation((name: string) =>
      name === 'cache-jdk' ? 'true' : ''
    );
    (core.getState as jest.Mock<any>).mockImplementation((name: string) =>
      name === 'jdk-caches' ? state : ''
    );
    spyCacheSave.mockResolvedValue(1);
    replace();

    await cleanup();

    expect(spyCacheSave).not.toHaveBeenCalledWith([jdkPath], key);
  });
});

function resetState() {
@@ -199,3 +305,49 @@ function createStateForSuccessfulRestoreWithWrapper(packageManager: string) {
    }
  });
}

/**
 * Register a real JDK installation in a temporary tool cache so the post-job
 * save sees the same installation identity that setup recorded.
 */
function createRegisteredJdk(version = '21.0.8+9') {
  const root = fs.mkdtempSync(
    path.join(os.tmpdir(), 'setup-java-cleanup-jdk-')
  );
  jdkTempRoots.push(root);
  const jdkPath = path.join(
    root,
    'Java_temurin_jdk',
    version.replace('+', '-')
  );
  const write = (marker: string) => {
    const architecturePath = path.join(jdkPath, 'x64');
    fs.rmSync(architecturePath, {recursive: true, force: true});
    fs.rmSync(`${architecturePath}.complete`, {force: true});
    fs.mkdirSync(architecturePath, {recursive: true});
    fs.writeFileSync(path.join(architecturePath, 'release'), marker);
    fs.writeFileSync(`${architecturePath}.complete`, marker);
  };
  write('installed');

  const jdk = {
    distribution: 'temurin',
    packageType: 'jdk',
    architecture: 'x64',
    version,
    source: `sha256:${path.basename(root)}`,
    verification: 'unverified',
    path: jdkPath
  };
  registerJdk(jdk);
  const state = (
    (core.saveState as jest.Mock).mock.calls.at(-1) as string[]
  )[1];

  return {
    key: buildJdkCacheKey(jdk),
    path: jdkPath,
    state,
    replace: () => write('replaced-by-a-later-step')
  };
}
+121 −1
Changes for __tests__/distributors/base-installer.test.ts: 121 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -70,6 +70,14 @@ jest.unstable_mockModule('@actions/tool-cache', () => ({
  }
}));

jest.unstable_mockModule('../../src/jdk-cache.js', () => ({
  getJdkVerificationIdentity: jest.fn((verified: boolean, key?: string) =>
    verified ? (key ? 'verified:custom' : 'verified:bundled') : 'unverified'
  ),
  registerJdk: jest.fn(),
  restoreJdk: jest.fn()
}));

const real_util_module = await import('../../src/util.js');
jest.unstable_mockModule('../../src/util.js', () => ({
  ...real_util_module,
@@ -86,6 +94,7 @@ jest.unstable_mockModule('../../src/util.js', () => ({
const core = await import('@actions/core');
const tc = await import('@actions/tool-cache');
const util = await import('../../src/util.js');
const jdkCache = await import('../../src/jdk-cache.js');
const {JavaBase} = await import('../../src/distributions/base-installer.js');

class EmptyJavaBase extends JavaBase {
@@ -336,6 +345,10 @@ describe('setupJava', () => {
  let spyCoreError: any;

  beforeEach(() => {
    (jdkCache.getJdkVerificationIdentity as jest.Mock).mockImplementation(
      (verified: boolean, key?: string) =>
        verified ? (key ? 'verified:custom' : 'verified:bundled') : 'unverified'
    );
    spyGetToolcachePath = util.getToolcachePath as jest.Mock;
    spyGetToolcachePath.mockImplementation(
      (toolname: string, javaVersion: string, architecture: string) => {
@@ -463,8 +476,10 @@ describe('setupJava', () => {
      architecture: 'x86',
      packageType: 'jdk',
      checkLatest: false,
      forceDownload: true
      forceDownload: true,
      cacheJdk: true
    });

    const findInToolcache = jest.fn(() => ({
      version: actualJavaVersion,
      path: javaPathInstalled
@@ -484,6 +499,111 @@ describe('setupJava', () => {
    expect(spyCoreInfo).not.toHaveBeenCalledWith(
      `Resolved Java ${actualJavaVersion} from tool-cache`
    );
    expect(jdkCache.restoreJdk).not.toHaveBeenCalled();
    expect(jdkCache.registerJdk).toHaveBeenCalledWith(
      expect.objectContaining({
        version: actualJavaVersion,
        verification: 'unverified'
      })
    );
  });

  it.each([
    [false, false, false, false],
    [false, true, true, true],
    [true, false, false, false],
    [true, true, false, true]
  ])(
    'handles force-download=%s and cache-jdk=%s',
    async (forceDownload, cacheJdkEnabled, restores, registers) => {
      mockJavaBase = new EmptyJavaBase({
        version: actualJavaVersion,
        architecture: 'x86',
        packageType: 'jdk',
        checkLatest: true,
        forceDownload,
        cacheJdk: cacheJdkEnabled
      });
      (jdkCache.restoreJdk as jest.Mock).mockResolvedValue(false);

      await mockJavaBase.setupJava();

      expect(jdkCache.restoreJdk).toHaveBeenCalledTimes(restores ? 1 : 0);
      expect(jdkCache.registerJdk).toHaveBeenCalledTimes(registers ? 1 : 0);
    }
  );

  it('restores the exact resolved JDK before downloading', async () => {
    const toolCachePath = path.join('toolcache');
    jest.replaceProperty(process, 'env', {
      ...process.env,
      RUNNER_TOOL_CACHE: toolCachePath
    });
    mockJavaBase = new EmptyJavaBase({
      version: '11',
      architecture: 'x86',
      packageType: 'jdk',
      checkLatest: true,
      cacheJdk: true
    });
    const downloadTool = jest.spyOn(mockJavaBase as any, 'downloadTool');
    (jdkCache.restoreJdk as jest.Mock).mockResolvedValue(true);
    jest
      .spyOn(mockJavaBase as any, 'getRestoredJdkPath')
      .mockReturnValue(javaPathInstalled);

    await expect(mockJavaBase.setupJava()).resolves.toEqual({
      version: actualJavaVersion,
      path: javaPathInstalled
    });

    expect(jdkCache.restoreJdk).toHaveBeenCalledWith({
      distribution: 'Empty',
      packageType: 'jdk',
      architecture: 'x86',
      version: actualJavaVersion,
      source: `some/random_url/java/${actualJavaVersion}`,
      verification: 'unverified',
      path: path.join(toolCachePath, 'Java_Empty_jdk', actualJavaVersion)
    });
    expect(downloadTool).not.toHaveBeenCalled();
    expect(spyCoreInfo).not.toHaveBeenCalledWith('Trying to download...');
    // A restored entry is already stored under its key; it must not be
    // re-registered for a post-job save.
    expect(jdkCache.registerJdk).not.toHaveBeenCalled();
  });

  it('registers the downloaded JDK identity after a JDK cache miss', async () => {
    const toolCachePath = path.join('toolcache');
    jest.replaceProperty(process, 'env', {
      ...process.env,
      RUNNER_TOOL_CACHE: toolCachePath
    });
    mockJavaBase = new EmptyJavaBase({
      version: '11',
      architecture: 'x86',
      packageType: 'jdk',
      checkLatest: true,
      cacheJdk: true
    });
    (jdkCache.restoreJdk as jest.Mock).mockResolvedValue(false);

    await mockJavaBase.setupJava();

    const expectedIdentity = {
      distribution: 'Empty',
      packageType: 'jdk',
      architecture: 'x86',
      version: actualJavaVersion,
      source: `some/random_url/java/${actualJavaVersion}`,
      verification: 'unverified',
      path: path.join(toolCachePath, 'Java_Empty_jdk', actualJavaVersion)
    };
    expect(jdkCache.restoreJdk).toHaveBeenCalledWith(expectedIdentity);
    // Registration happens after the installation exists, so the post-job save
    // can detect a later step replacing it.
    expect(jdkCache.registerJdk).toHaveBeenCalledWith(expectedIdentity);
    expect(spyCoreInfo).toHaveBeenCalledWith('Trying to download...');
  });

  it.each([
+79
Changes for __tests__/distributors/local-installer.test.ts: 79 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -12,6 +12,9 @@ import fs from 'fs';

import path from 'path';
import * as semver from 'semver';
import os from 'os';

const realStatSync = fs.statSync;

// Mock @actions/core before importing source modules that depend on it
jest.unstable_mockModule('@actions/core', () => ({
@@ -54,6 +57,12 @@ jest.unstable_mockModule('@actions/tool-cache', () => ({
  evaluateVersions: jest.fn()
}));

jest.unstable_mockModule('../../src/jdk-cache.js', () => ({
  getJdkVerificationIdentity: jest.fn(() => 'unverified'),
  registerJdk: jest.fn(),
  restoreJdk: jest.fn()
}));

const real_util_module = await import('../../src/util.js');
jest.unstable_mockModule('../../src/util.js', () => ({
  ...real_util_module,
@@ -70,6 +79,7 @@ jest.unstable_mockModule('../../src/util.js', () => ({
const core = await import('@actions/core');
const tc = await import('@actions/tool-cache');
const util = await import('../../src/util.js');
const jdkCache = await import('../../src/jdk-cache.js');
const {LocalDistribution} =
  await import('../../src/distributions/local/installer.js');

@@ -95,6 +105,9 @@ describe('setupJava', () => {
  const expectedJdkFile = 'JavaLocalJdkFile';

  beforeEach(() => {
    (jdkCache.getJdkVerificationIdentity as jest.Mock).mockReturnValue(
      'unverified'
    );
    spyGetToolcachePath = util.getToolcachePath as jest.Mock;
    spyGetToolcachePath.mockImplementation(
      (toolname: string, javaVersion: string, architecture: string) => {
@@ -231,6 +244,72 @@ describe('setupJava', () => {
    );
  });

  it.each([
    [false, true, true],
    [true, false, true]
  ])(
    'handles jdkfile caching with force-download=%s',
    async (forceDownload, restores, registers) => {
      const temporaryDirectory = fs.mkdtempSync(
        path.join(os.tmpdir(), 'setup-java-local-cache-')
      );
      const jdkFile = path.join(temporaryDirectory, 'java.tar.gz');
      fs.writeFileSync(jdkFile, 'jdk archive');
      spyGetToolcachePath.mockReturnValue('');
      spyFsStat.mockImplementation((file: string) => realStatSync(file));
      (jdkCache.restoreJdk as jest.Mock).mockResolvedValue(false);

      try {
        mockJavaBase = new LocalDistribution(
          {
            version: actualJavaVersion,
            architecture: 'x86',
            packageType: 'jdk',
            checkLatest: false,
            forceDownload,
            cacheJdk: true
          },
          jdkFile
        );

        await mockJavaBase.setupJava();

        expect(jdkCache.restoreJdk).toHaveBeenCalledTimes(restores ? 1 : 0);
        expect(jdkCache.registerJdk).toHaveBeenCalledTimes(registers ? 1 : 0);
        expect(
          (jdkCache.restoreJdk as jest.Mock).mock.calls[0]?.[0] ??
            (jdkCache.registerJdk as jest.Mock).mock.calls[0]?.[0]
        ).toEqual(
          expect.objectContaining({
            distribution: 'jdkfile',
            version: actualJavaVersion,
            verification: 'unverified'
          })
        );
      } finally {
        fs.rmSync(temporaryDirectory, {recursive: true});
      }
    }
  );

  it('rejects signature verification for jdkfile archives', async () => {
    mockJavaBase = new LocalDistribution(
      {
        version: actualJavaVersion,
        architecture: 'x86',
        packageType: 'jdk',
        checkLatest: false,
        verifySignature: true
      },
      expectedJdkFile
    );

    await expect(mockJavaBase.setupJava()).rejects.toThrow(
      "Input 'verify-signature' is not supported for distribution 'jdkfile'."
    );
    expect(spyGetToolcachePath).not.toHaveBeenCalled();
  });

  it("java is resolved from toolcache, jdkfile doesn't exist", async () => {
    const inputs = {
      version: actualJavaVersion,
+325

File added.

Preview size limit exceeded, changes collapsed.

Loading