Compare commits

..
Author SHA1 Message Date
Bruno BorgesandGitHub ff99aa1c87 Fix Oracle macOS E2E version (#1243)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: d4f1997e-98a5-4dec-b5fc-2f0fcf1abd27
2026-08-17 21:23:19 -04:00
416c6d1e8a Add Red Hat Build of OpenJDK support (#1241)
* Add Red Hat Build of OpenJDK support

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

* Fix Red Hat tests on Windows

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

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Update compiled Red Hat distribution

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

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-17 20:39:36 -04:00
5f75b27283 Add Maven dependency-resolution repositories (#1240)
* Add Maven dependency repositories

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

Copilot-Session: 8897ad63-2d05-4a6d-8ccd-c1155348b59e

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot-Session: 8897ad63-2d05-4a6d-8ccd-c1155348b59e
2026-08-17 18:18:45 -04:00
a42a52cfb5 Add multiple Maven server credentials (#1239)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-17 17:05:55 -04:00
fb4abd7a70 test: cover JDK 26 from SDKMAN (#1238)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-17 17:05:27 -04:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
d4f69b3990 chore(deps-dev): bump @typescript-eslint/eslint-plugin (#1232)
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 8.65.0 to 8.67.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.66.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-17 14:58:47 -04:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
7d5d4a7f19 chore(deps-dev): bump lint-staged from 17.2.0 to 17.3.0 (#1231)
Bumps [lint-staged](https://github.com/lint-staged/lint-staged) from 17.2.0 to 17.3.0.
- [Release notes](https://github.com/lint-staged/lint-staged/releases)
- [Changelog](https://github.com/lint-staged/lint-staged/blob/main/CHANGELOG.md)
- [Commits](https://github.com/lint-staged/lint-staged/compare/v17.2.0...v17.3.0)

---
updated-dependencies:
- dependency-name: lint-staged
  dependency-version: 17.3.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-17 14:48:50 -04:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
f974fff346 chore(deps-dev): bump @types/semver from 7.7.1 to 7.8.0 (#1229)
Bumps [@types/semver](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/semver) from 7.7.1 to 7.8.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/semver)

---
updated-dependencies:
- dependency-name: "@types/semver"
  dependency-version: 7.8.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-17 14:48:25 -04:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>Bruno Borges
e96da06a44 chore(deps-dev): bump globals from 17.8.0 to 17.9.0 (#1233)
Bumps [globals](https://github.com/sindresorhus/globals) from 17.8.0 to 17.9.0.
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v17.8.0...v17.9.0)

---
updated-dependencies:
- dependency-name: globals
  dependency-version: 17.9.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-17 14:47:55 -04:00
3487f54461 Update setup-java for Microsoft's Build of OpenJDK: now pointing task to CDN that is always up-to-date (#1236)
* Updated microsoft openjdk setup-java action

* Update generated distribution

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Applied new fixes from npm run check

* Update generated distribution

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-14 01:10:57 -04:00
CopilotGitHubcopilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>brunoborgesBruno Borges
d2bb5a81bf Fix failing GitHub Actions job for graalvm 24-ea (#1227)
* Initial plan

* Normalize EA setup-java version output in verify-java.sh

Co-authored-by: brunoborges <129743+brunoborges@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: brunoborges <129743+brunoborges@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-06 23:43:55 -04:00
Bruno BorgesandGitHub a52a3de678 Fix js-yaml audit vulnerability (#1228)
Upgrade the transitive js-yaml dependency to 3.15.1 to resolve GHSA-5p4m-2wfm-xmqj.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-06 23:15:19 -04:00
d17a685945 Handle early dependency cache failures during Java setup (#1226)
* Handle cache restore promise rejections

Validate dependency cache providers before Java installation and settle cache restore failures immediately while preserving setup error precedence.

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

* Make cache-rejection regression test deterministic

Reject the cache restore only after it has started and while the Java
installation is still pending, instead of relying on event-loop timing.
Verified the test fails against the pre-fix implementation.

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

* Validate cache input after required input checks

Move the package-manager validation out of the top of run() so that
missing java-version/java-version-file and toolchain id errors keep
their original precedence. Validation now happens immediately before
the cache restore is started, which still fails fast before any JDK
download.

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

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-06 23:04:13 -04:00
0b0c385478 Include gradle.properties in Gradle cache key (#1225)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-06 23:00:23 -04:00
143564d5b9 Fix JetBrains GitHub token resolution (#1224)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-06 11:46:13 -04:00
5580b78434 Fix SapMachine early-access filtering (#1217)
* Fix SapMachine early-access filtering

Ensure SapMachine EA requests exclude stable releases and cover string and boolean release metadata with competing fixture candidates.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Update distribution bundle

Regenerate the setup bundle for SapMachine release-class filtering.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Format SapMachine regression tests

Apply the repository Prettier format to the focused test additions.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-05 12:59:08 -04:00
4fbd0bd19d fix: select musl JDK artifacts on Alpine for five distributions (#1220)
On Alpine, `getPlatformOption()` returned the glibc platform key for
Dragonwell, Corretto, Zulu, Liberica and Liberica NIK, so the action
resolved and installed a glibc JDK that cannot run under musl.

Add a shared `isAlpineLinux()` helper and use it to select each vendor's
musl artifacts:

| distribution | glibc         | musl           |
| ------------ | ------------- | -------------- |
| Dragonwell   | `linux`       | `alpine-linux` |
| Corretto     | `linux`       | `alpine`       |
| Zulu         | `linux_glibc` | `linux_musl`   |
| Liberica     | `linux`       | `linux-musl`   |
| Liberica NIK | `linux`       | `linux-musl`   |

Each key was verified against the vendor's live metadata API or manifest.

There is deliberately no silent fallback to glibc when a vendor has no
musl build for the requested version or architecture: the existing "could
not find a version that satisfies" error fires instead. This matches the
behaviour Temurin and SapMachine already have, and a glibc JDK would not
run on musl anyway.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 74248bb0-72af-41d8-b85d-b0f5836e68db
2026-08-05 12:54:41 -04:00
d0e61fe743 Fix JDK resolution cache platform identity (#1210)
* Fix JDK resolution cache platform identity

Include the effective Linux libc platform in JDK resolution cache keys so Alpine/musl and glibc runners cannot restore each other's release metadata. Bump the cache namespace and share Alpine detection with affected distributors.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>\nCopilot-Session: 4f95577c-567c-47a8-92f2-b4dced527866

* Update generated action bundles

Regenerate setup and cleanup distributions for the platform-aware JDK resolution cache.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>\nCopilot-Session: 4f95577c-567c-47a8-92f2-b4dced527866

* Cover the platform-identity fallback and Alpine short-circuit

getJavaPlatformIdentity's `?? platform` fallback and the alias path for
platforms other than linux/darwin/win32 had no coverage, and isAlpineLinux
had no direct test at all.

Verified by mutation: replacing the fallback with a constant, and dropping
the `platform === 'linux'` short-circuit from isAlpineLinux, both left the
existing suite fully green. The added cases fail on each.

The short-circuit case matters beyond coverage bookkeeping: it is what keeps
the /etc/alpine-release probe from running on non-Linux runners, so a stray
file can never make Windows or macOS resolve as musl.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 74248bb0-72af-41d8-b85d-b0f5836e68db

* Carry the platform identity into the floating resolution request

Merging main brought in #1219, which added getFloatingResolutionRequest
as a second construction site for JdkResolutionRequest. It predates the
required `platform` field, so the merged tree did not compile.

The floating request already carries `source`, which pins the artifact
bytes, so this changes no lookup behaviour on its own -- it keeps the two
request builders consistent and the tree building.

Also refreshes dist/, which the textual merge left stale.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 74248bb0-72af-41d8-b85d-b0f5836e68db

---------

Co-authored-by: Bruno Borges <brborges@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 74248bb0-72af-41d8-b85d-b0f5836e68db
2026-08-05 12:45:11 -04:00
fb58a661f3 Fix JetBrains Runtime release pagination (#1218)
* Fix JetBrains release pagination

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

* Update setup distribution

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

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-05 12:32:52 -04:00
2b61aea53d Reuse the tool cache for floating versions the resolution cache identified (#1219)
A floating Oracle JDK or Oracle GraalVM request now skips the tool-cache
short-circuit entirely, so every job re-downloads and re-extracts the JDK
even when the exact bytes the mutable URL currently serves are already
installed locally.

The JDK resolution cache is keyed on the artifact's checksum (or, failing
that, its HTTP response fingerprint), so a hit proves which concrete
version the URL is serving right now. Once it has vouched for that
version, an existing tool-cache installation of exactly that version is
the artifact the download would have produced, and can be reused.

Reuse is therefore gated on the resolution cache hit, never on the
requested major: an unidentified floating artifact still downloads, as
does an explicit force-download.

Co-authored-by: Bruno Borges <brunoborges@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: f2d9a891-a680-4b35-9644-cf2450f76f6d
2026-08-05 12:08:32 -04:00
634b0f0d18 Import Maven signing keys into an isolated GPG home (#1214)
* Isolate Maven signing keys

Import signing keys into an action-owned temporary GPG home, export GNUPGHOME, and remove the owned directory in the post action. Cover import failure, multiple keys and invocations, unrelated keyrings, missing state, and Windows path conversion.

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

* Fix cleanup state assertion

Account for isolated GPG-home cleanup when cache saving is disabled.

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

* Update generated action bundles

Apply repository formatting and commit the setup and cleanup bundles produced by the validated Node 24 build.

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

* Address isolated GPG home review feedback

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

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-05 12:05:36 -04:00
f4bfb3ddea Report concrete versions for floating Oracle JDK downloads (#1213)
* Fix floating Oracle JDK version resolution

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

* Update generated distribution bundles

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

* Harden floating artifact cache identity

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

* Regenerate setup bundle after cache hardening

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

* Temporarily enable hosted full validation

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

* Export hosted formatting results

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

* Apply repository formatting

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

* Run hosted validation after formatting

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

* Correct floating version regression tests

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

* Remove temporary validation wiring

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

* Cache checksum-less floating artifacts by their response fingerprint

Oracle and Oracle GraalVM do not always publish a `.sha256` sibling next
to a `/latest/` artifact. Those floating releases were excluded from both
the resolution cache and the JDK cache, so `cache-jdk` users lost caching
entirely for them.

A floating URL is a constant string, so it cannot serve as a cache
identity on its own — a stale entry would be reused forever. Instead,
derive a validator from the headers of the HEAD request that already
resolves the artifact: the ETag when present, otherwise `Last-Modified`
combined with `Content-Length`. Republishing changes the validator, which
changes the cache key, so a new build is downloaded rather than masked.

`getJdkReleaseIdentity` now falls back to that fingerprint before the
URL, and the floating cache gates ask whether the release has a stable
identity (checksum or fingerprint) rather than a checksum specifically. A
floating release with neither is still left uncached.

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

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
2026-08-05 11:57:27 -04:00
ab597f914a Cache resolved JDK releases to remove the vendor API from warm jobs (#1208)
* Cache resolved JDK releases to remove the vendor API from warm jobs

Only Temurin is preinstalled in the runner tool cache, so for every other
distribution `findInToolcache()` misses on essentially every job. That
forces a call to the distribution's metadata API before the JDK cache key
can even be computed, which makes the vendor a hard per-job dependency
even when the JDK bytes are already cached, and turns a vendor 403, 429,
or outage into a job failure.

Store the resolved release in a small companion cache entry keyed only on
inputs known before any network call: runner OS, architecture,
distribution, package type, requested version, and stability. A job that
finds a current entry installs the JDK without contacting the metadata API
at all.

`@actions/cache` derives a cache version by hashing the requested paths, so
save and restore paths must match. The entry therefore uses a path that
excludes the date bucket while the key includes it, which lets restore keys
fall back to an older bucket. An entry older than the current day is not
used directly: the metadata API is still queried so floating requests such
as `java-version: 21` keep picking up new releases, and the older entry is
used only when that query fails. Because the entry also carries the
download URL and checksum, that fallback works even when the JDK itself is
not cached.

Releases whose URL is not content-addressed are never stored. Oracle JDK
and Oracle GraalVM build a `/latest/` URL for a major-only version, and its
bytes change when a new build is published, so the URL and checksum are
only consistent at the moment they are resolved. Mark those releases
floating and skip recording them.

Restored payloads are validated as untrusted input, and the post-job save
rewrites the payload the key was computed for rather than uploading
whatever is on disk, since a restore in a later step targets the same path.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b76d8cb0-f629-46e1-bf9a-ffde06948644

* Widen the resolution freshness window from a day to a week

A daily window gives no benefit to the repositories that need it most.
A repository whose workflows run once a day would re-resolve on every job,
and one running weekly would never see a current entry at all, yet those
are exactly the repositories with nothing warm in the tool cache.

Seven days is also the ceiling. GitHub removes cache entries that have not
been accessed for seven days, so a longer window would leave the previous
entry evicted by the time the window rolls over, removing the stale
fallback at the moment it is most likely to be needed. It comfortably
covers JDK release cadence, which is monthly at its fastest and usually
quarterly.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b76d8cb0-f629-46e1-bf9a-ffde06948644

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Rebuild dist to match the linted source

The pre-commit hook runs `eslint --fix` after `npm run check` has already
built `dist/`, so the fix it applied to the resolution fallback warning in
`base-installer.ts` never reached the bundle.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b76d8cb0-f629-46e1-bf9a-ffde06948644

* Rebuild dist to match the linted source

The autofix accepted on the pull request edited the resolution fallback
warning in `base-installer.ts` through the GitHub UI, which does not run
`npm run build`, so `dist/` still carried the pre-fix bundle.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b76d8cb0-f629-46e1-bf9a-ffde06948644

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot-Session: b76d8cb0-f629-46e1-bf9a-ffde06948644
2026-08-04 23:58:03 -04:00
ef9440a2b8 docs: correct the mvn-toolchain-id default in README and action.yml (#1207)
The generated toolchain ID is `${vendor}_${version}`, where vendor is the
mvn-toolchain-vendor input falling back to distribution. Two places described
this incorrectly.

action.yml claimed the default was "${distribution}_${java-version}", which
is wrong whenever mvn-toolchain-vendor is set, since overriding the vendor
also changes the generated ID.

The README used `${vendor}`, which is accurate but names something that is
not an action input, leaving readers to guess where the value comes from.

Both now name mvn-toolchain-vendor and state that it falls back to
distribution.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 664777db-7250-417d-b94d-d5529ec3fec2
2026-08-04 23:29:25 -04:00
2dd851a56a docs: cite reproducible JDK cache benchmark numbers (#1205)
The JDK caching section quoted informal figures from the feature PR. The
setup-java-benchmarks repository now has a JDK cache scenario workflow that
reproduces the comparison end to end, so cite its numbers across two
independent runs and name the workflow instead.

Also record the cold-run cost, the flat build-step control, and the fact
that the job-level median is noisier than the setup-step median, so the
tradeoff is explicit rather than implying the speedup is free or precise.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 664777db-7250-417d-b94d-d5529ec3fec2
2026-08-04 23:28:41 -04:00
885218c5e4 Move the extracted JDK into the tool-cache and speed up extraction (#1206)
Two wall-clock optimizations on the JDK install path.

`tc.cacheDir` recursively copies the extracted tree into RUNNER_TOOL_CACHE,
so a 200-600MB JDK is written to disk twice. The extraction directory and
the tool-cache normally share a filesystem, so `cacheJdkDir` renames it
instead and writes the `.complete` marker itself, mirroring the destination
layout `tc.cacheDir` produces. It falls back to the copy when the tool-cache
location is unknown, when the source is not a real directory (a symlinked
source would otherwise leave a dangling entry once RUNNER_TEMP is cleaned),
or when the rename fails - a cross-device tool-cache, or anti-virus holding
a handle on Windows. The rename is atomic, so the source is still intact
for the fallback.

Extraction now uses `pigz` for tarballs when the runner provides it, and
Windows zips go through the bundled `tar.exe` rather than `tc.extractZip`,
which shells out to PowerShell's much slower `Expand-Archive`. Both fall
back to the stock extraction and clean up the abandoned directory first.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b76d8cb0-f629-46e1-bf9a-ffde06948644
2026-08-04 23:05:06 -04:00
2924169ccc docs: correct README and advanced usage inconsistencies (#1204)
- Fix stale claim that java-version and distribution are always mandatory
- Fix security note that claimed no checksum/signature verification exists
- Fix jdkfile toolchain example ID (jdkfile_1.6, not Oracle_1.6)
- Clarify default toolchain ID derives from the vendor, not the distribution
- Drop stale liberica-nik fallback claim; unsupported packages are rejected
- Document IBM Semeru and add missing TOC/nav entries
- Note that advanced-usage examples target the unreleased v6 on main
- Replace retired ubuntu-20.04 runner and fix a heading level

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-04 22:08:10 -04:00
955f34f16f 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: Copilot App <223556219+Copilot@users.noreply.github.com>

* Apply batched suggestions from code review

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix JDK cache CI validation

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

* Update brace-expansion security fix

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

* Refresh brace-expansion license metadata

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

* Refine JDK cache semantics

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

* Refine JDK cache documentation

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

* 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: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e2755464-4e83-47b6-ba71-731bb481b418

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot-Session: e2755464-4e83-47b6-ba71-731bb481b418
2026-08-04 21:54:10 -04:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>Bruno BorgesCopilot App
7a9a8b1dcc chore(deps): bump brace-expansion from 5.0.8 to 5.0.9 (#1202)
* chore(deps): bump brace-expansion from 5.0.8 to 5.0.9

Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 5.0.8 to 5.0.9.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v5.0.8...v5.0.9)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 5.0.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore: rebuild distribution

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

* chore: refresh dependency metadata

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

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-04 21:15:15 -04:00
f48de5f4c7 Highlight major changes in setup-java v6 (#1203)
* docs: highlight major v6 changes

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

* docs: separate JDK download highlights

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

* docs: clarify v6 distribution highlights

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

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-04 19:57:24 -04:00
Bruno BorgesandGitHub 881ee1636f docs: highlight major v5 changes (#1200)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 8e3b1604-55ad-4a37-91dd-65e424e71ba7
2026-08-04 18:53:31 -04:00
Bruno BorgesandGitHub 60b1ab8234 Update setup-java README action from v6 to v5 (#1199) 2026-08-04 17:06:55 -04:00
Bruno BorgesandGitHub dd7dc10522 Document deprecation of legacy action versions (#1198)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 62a37470-ba42-40e1-8fb4-f644cf05da02
2026-08-04 14:06:02 -04:00
Bruno BorgesandGitHub 7c6f629e2f Reimagine setup-java README (#1192)
* Implement new feature for user authentication and improve error handling

* Clarify README review feedback

Clarify distribution case sensitivity, GHES token defaults, and cache key placeholder notation in the README.

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

Copilot-Session: f0ff1923-c6ca-472e-83b2-3a813ec6d781

* Update README to clarify V6 development status and enhance contributions section

* Update README to recommend permissions for setup-java action in GitHub Actions

* Restore README usage heading

Rename the quick-start section to the conventional Usage heading used by setup actions.

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

Copilot-Session: f0ff1923-c6ca-472e-83b2-3a813ec6d781

---------

Copilot-Session: f0ff1923-c6ca-472e-83b2-3a813ec6d781
2026-08-03 13:40:46 -04:00
110 changed files with 127098 additions and 2496 deletions
-3
View File
@@ -12,9 +12,6 @@ updates:
# Check the npm registry for updates every day (weekdays)
schedule:
interval: 'weekly'
ignore:
- dependency-name: 'typescript'
update-types: ['version-update:semver-major']
# Enable version updates for GitHub Actions
- package-ecosystem: 'github-actions'
+24 -2
View File
@@ -71,7 +71,7 @@ jobs:
version: 25
- distribution: oracle
os: macos-15-intel
version: 17
version: 21
- distribution: oracle
os: windows-latest
version: 21
@@ -117,7 +117,9 @@ jobs:
env:
JAVA_VERSION: ${{ matrix.version }}
JAVA_PATH: ${{ steps.setup-java.outputs.path }}
run: bash __tests__/verify-java.sh "$JAVA_VERSION" "$JAVA_PATH"
SETUP_JAVA_VERSION: ${{ steps.setup-java.outputs.version }}
REQUIRE_CONCRETE_VERSION: ${{ (matrix.distribution == 'oracle' || matrix.distribution == 'graalvm') && !contains(matrix.version, '.') && !contains(matrix.version, '-ea') }}
run: bash __tests__/verify-java.sh "$JAVA_VERSION" "$JAVA_PATH" "$SETUP_JAVA_VERSION" "$REQUIRE_CONCRETE_VERSION"
shell: bash
setup-java-checksum-verification:
@@ -634,6 +636,26 @@ jobs:
run: bash __tests__/verify-java.sh "17.0.10" "$JAVA_PATH"
shell: bash
setup-java-version-from-sdkman-major:
name: temurin 26 from .sdkmanrc - ubuntu-latest
runs-on: ubuntu-latest
steps:
- *checkout_step
- name: Create SDKMAN and Gradle files
run: |
echo "java=26-tem" > .sdkmanrc
touch build.gradle
- name: setup-java
uses: ./
id: setup-java
with:
java-version-file: .sdkmanrc
cache: gradle
- name: Verify Java
env:
JAVA_PATH: ${{ steps.setup-java.outputs.path }}
run: bash __tests__/verify-java.sh "26" "$JAVA_PATH"
setup-java-set-default:
name: set-default option - ${{ matrix.os }}
needs: setup-java-major-versions
-32
View File
@@ -1,32 +0,0 @@
---
name: "@oozcitak/dom"
version: 2.0.2
type: npm
summary: A modern DOM implementation
homepage: http://github.com/oozcitak/dom
license: mit
licenses:
- sources: LICENSE
text: |
MIT License
Copyright (c) 2019 Ozgur Ozcitak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
notices: []
-32
View File
@@ -1,32 +0,0 @@
---
name: "@oozcitak/infra"
version: 2.0.2
type: npm
summary: An implementation of the Infra Living Standard
homepage: http://github.com/oozcitak/infra
license: mit
licenses:
- sources: LICENSE
text: |
MIT License
Copyright (c) 2019 Ozgur Ozcitak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
notices: []
-32
View File
@@ -1,32 +0,0 @@
---
name: "@oozcitak/url"
version: 3.0.0
type: npm
summary: An implementation of the URL Living Standard
homepage: http://github.com/oozcitak/url
license: mit
licenses:
- sources: LICENSE
text: |
MIT License
Copyright (c) 2019 Ozgur Ozcitak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
notices: []
-32
View File
@@ -1,32 +0,0 @@
---
name: "@oozcitak/util"
version: 10.0.0
type: npm
summary: Utility functions
homepage: http://github.com/oozcitak/util
license: mit
licenses:
- sources: LICENSE
text: |
MIT License
Copyright (c) 2019 Ozgur Ozcitak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
notices: []
-265
View File
@@ -1,265 +0,0 @@
---
name: argparse
version: 2.0.1
type: npm
summary: CLI arguments parser. Native port of python's argparse.
homepage:
license: other
licenses:
- sources: LICENSE
text: |
A. HISTORY OF THE SOFTWARE
==========================
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations, which became
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.
All Python releases are Open Source (see http://www.opensource.org for
the Open Source Definition). Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.
Release Derived Year Owner GPL-
from compatible? (1)
0.9.0 thru 1.2 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI yes (2)
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2 and above 2.1.1 2001-now PSF yes
Footnotes:
(1) GPL-compatible doesn't mean that we're distributing Python under
the GPL. All Python licenses, unlike the GPL, let you distribute
a modified version without making your changes open source. The
GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
because its license has a choice of law clause. According to
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
is "not incompatible" with the GPL.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation;
All Rights Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS"
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee. Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement. This Agreement together with
Python 1.6.1 may be located on the Internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the Internet
using the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
notices: []
+1 -1
View File
@@ -1,6 +1,6 @@
---
name: brace-expansion
version: 5.0.8
version: 5.0.9
type: npm
summary: Brace expansion as known from sh/bash
homepage:
-32
View File
@@ -1,32 +0,0 @@
---
name: js-yaml
version: 4.3.0
type: npm
summary: YAML 1.2 parser and serializer
homepage:
license: mit
licenses:
- sources: LICENSE
text: |
(The MIT License)
Copyright (C) 2011-2015 by Vitaly Puzrin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
notices: []
-32
View File
@@ -1,32 +0,0 @@
---
name: xmlbuilder2
version: 4.0.3
type: npm
summary: An XML builder for node.js
homepage: https://github.com/oozcitak/xmlbuilder2
license: mit
licenses:
- sources: LICENSE.txt
text: |
MIT License
Copyright (c) 2019 Ozgur Ozcitak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
notices: []
+398 -322
View File
@@ -4,242 +4,349 @@
[![Validate Java e2e](https://github.com/actions/setup-java/actions/workflows/e2e-versions.yml/badge.svg?branch=main)](https://github.com/actions/setup-java/actions/workflows/e2e-versions.yml)
[![Validate cache](https://github.com/actions/setup-java/actions/workflows/e2e-cache.yml/badge.svg?branch=main)](https://github.com/actions/setup-java/actions/workflows/e2e-cache.yml)
The `setup-java` action provides the following functionality for GitHub Actions runners:
- Downloading and setting up a requested version of Java. See [Usage](#usage) for a list of supported distributions.
- Extracting and caching custom version of Java from a local file.
- Configuring runner for publishing using Apache Maven.
- Configuring runner for publishing using Gradle.
- Configuring runner for using GPG private key.
- Registering problem matchers for error output.
- Caching dependencies managed by Apache Maven.
- Caching dependencies managed by Gradle.
- Caching dependencies managed by sbt.
- [Maven Toolchains declaration](https://maven.apache.org/guides/mini/guide-using-toolchains.html) for specified JDK versions.
Set up Java for GitHub Actions workflows. `setup-java` installs a requested Java distribution, adds it to `PATH`, configures `JAVA_HOME`, and can optionally cache build dependencies for Apache Maven, Gradle, and sbt; generate Maven publishing configuration, verify JDK package signatures, manage multiple JDKs, and manage Maven toolchains.
This action allows you to work with Java and Scala projects.
## What's new in V6
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '25'
- run: java --version
```
> [!NOTE]
> V6 is still in development (`main` branch) and is not yet recommended for production workflows.
> V6 is still in development on the `main` branch and is not yet recommended for production workflows. To use it, you must explicitly reference the `main` branch in your workflow, as in
>
> ```yaml
> - uses: actions/setup-java@main
> ```
>
> For production workflows, it is recommended to use the latest stable release `v5`.
- **Migrated to ESM** to enable support for the latest `@actions/*` package versions. This is an internal implementation change.
## Contents
## Breaking changes in V6
- [What it does](#what-it-does)
- [What's new](#whats-new)
- [Usage](#usage)
- [Inputs](#inputs)
- [Supported distributions](#supported-distributions)
- [Supported version syntax](#supported-version-syntax)
- [Caching](#caching)
- [Multiple JDKs and Maven toolchains](#multiple-jdks-and-maven-toolchains)
- [Publishing packages](#publishing-packages)
- [Advanced usage](#advanced-usage)
- **Renamed inputs that accept environment-variable names** to make it clear that their values are not credentials. Replace `server-username`, `server-password`, and `gpg-passphrase` with `server-username-env-var`, `server-password-env-var`, and `gpg-passphrase-env-var`, respectively. The old names remain as deprecated aliases and emit a warning when used.
## What it does
- **The GPG passphrase is now passed to the Maven GPG Plugin through an environment variable (`gpg.passphraseEnvName`) instead of the deprecated `gpg.passphrase` server in `settings.xml`.** Set the environment variable name with `gpg-passphrase-env-var`, which defaults to `GPG_PASSPHRASE`. This requires `maven-gpg-plugin` **3.2.0 or newer**; older versions do not honor `gpg.passphraseEnvName` and, because the `gpg.passphrase` server is no longer written, will not pick up the passphrase. Upgrade the plugin to 3.2.0+.
- Downloads and installs Java from a supported distribution.
- Uses a requested Java version, a version file, or the `latest` stable release alias.
- Extracts and caches a custom JDK archive from a local file.
- Configures Maven `settings.xml`, Maven Toolchains, Maven GPG signing inputs, and environment-variable based credentials for publishing workflows.
- Registers Java problem matchers for compiler diagnostics and uncaught exceptions.
- Caches dependencies for Maven, Gradle, and sbt.
- Caches downloaded JDK installations between jobs.
- Verifies downloaded archive checksums when a distribution publishes authoritative checksums.
- Optionally verifies package signatures for supported distributions.
See [GPG](docs/advanced-usage.md#gpg) for details.
`setup-java` works with Java, Scala, Kotlin, Gradle, Maven, and sbt projects.
- **Legacy AdoptOpenJDK distributions were removed.** Replace `adopt` or `adopt-hotspot` with `temurin`, and replace `adopt-openj9` with `semeru`.
## What's new
## Breaking changes in V5
### V6 (in development)
- Upgraded action from node20 to node24
> Make sure your runner is on version v2.327.1 or later to ensure compatibility with this release [Release Notes](https://github.com/actions/runner/releases/tag/v2.327.1)
- Migrated the action implementation to ESM to support the latest `@actions/*` packages.
- Added the `oracle-openjdk` distribution for OpenJDK builds from Oracle.
- Added `java-version: latest` to resolve the newest stable GA release from the distribution's remote metadata.
- 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.
- Renamed environment-variable-name inputs so they are not mistaken for secret values:
- `server-username` -> `server-username-env-var`
- `server-password` -> `server-password-env-var`
- `gpg-passphrase` -> `gpg-passphrase-env-var`
- Deprecated aliases still work, but emit warnings.
- Maven GPG passphrases are now passed through `gpg.passphraseEnvName` instead of a deprecated `gpg.passphrase` server entry in `settings.xml`. This requires `maven-gpg-plugin` 3.2.0 or newer. See [GPG](docs/advanced-usage.md#gpg).
- Legacy AdoptOpenJDK distributions were removed. Use `temurin` instead of `adopt` or `adopt-hotspot`, and `semeru` instead of `adopt-openj9`.
For more details, see the full release notes on the [releases page](https://github.com/actions/setup-java/releases/tag/v5.0.0)
### V5
- Upgraded the action runtime from Node 20 to Node 24. Self-hosted runners must use version `v2.327.1` or later. See the [runner release notes](https://github.com/actions/runner/releases/tag/v2.327.1).
- Added support for [GraalVM Community](#supported-distributions) and [Tencent Kona](#supported-distributions).
- Expanded `java-version-file` support with `.sdkmanrc` files and automatic distribution detection from SDKMAN and asdf vendor identifiers.
- Added optional package-signature verification for Eclipse Temurin and Microsoft Build of OpenJDK downloads.
- Added `set-default: false` for installing a JDK without changing `JAVA_HOME` or `PATH`.
- Improved dependency caching with separate Maven and Gradle wrapper caches, Maven extension-aware cache keys, and the `cache-primary-key` output.
- Improved Maven and Java build behavior by preserving toolchain entries across repeated action invocations, suppressing transfer progress by default, generating non-interactive Maven settings, and matching `javac` compiler errors.
- Renamed the `jdkFile` input to `jdk-file`; the old name remains available as a deprecated alias.
- See the [complete V5 release history](https://github.com/actions/setup-java/releases?q=v5&expanded=true) for enhancements and fixes across all V5 releases.
### Older versions
> [!WARNING]
> `actions/setup-java` versions `v1` through `v4` are deprecated. Upgrade workflows to `actions/setup-java@v5`, the latest stable release.
## Usage
- `java-version`: The Java version that is going to be set up. Takes a whole or [semver](#supported-version-syntax) Java version. If not specified, the action will expect `java-version-file` input to be specified.
### Install Eclipse Temurin
- `java-version-file`: The path to a file containing java version. Supported file types are `.java-version`, `.tool-versions`, and `.sdkmanrc`. See more details in [about .java-version-file](docs/advanced-usage.md#Java-version-file).
- `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 across all distributions are `jdk`, `jre`, `jdk+fx`, `jre+fx`, `jdk+crac`, `jre+crac`, `jdk+jmods`, `jdk+jcef`, `jre+jcef`, `jdk+ft`, and `jre+ft`. Supported values vary by distribution; see the [package compatibility table](docs/advanced-usage.md#package-compatibility). Default value: `jdk`.
- `architecture`: The target architecture of the package. Canonical values are `x86`, `x64`, `armv7`, `aarch64`, `ppc64le`, `ppc64`, and `s390x`; the aliases `ia32`, `amd64`, `arm`, and `arm64` normalize to `x86`, `x64`, `armv7`, and `aarch64`. Supported values vary by distribution and operating system. Default value: Derived from the runner machine.
- `jdk-file`: If a use-case requires a custom distribution setup-java uses the compressed JDK from the location pointed by this input and will take care of the installation and caching on the VM. Note: `distribution` must be set to 'jdkfile' (case-sensitive; all lowercase) when using this option. (The camelCase `jdkFile` input is still accepted as a deprecated alias and may be removed in a future release.)
- `check-latest`: Setting this option makes the action to check for the latest available version for the version spec.
- `force-download`: Set to `true` to always download Java and replace any matching version in the tool cache. This can help make builds reproducible when a runner image has modified a pre-installed JDK, such as its `cacerts` file. Default value: `false`.
- `set-default`: Set to `false` to install a JDK without making it the default. When `false`, `JAVA_HOME` and `PATH` are not updated, but `JAVA_HOME_<major>_<arch>` is still set so the JDK remains discoverable. Default value: `true`. See [Installing JDK without setting as default](docs/advanced-usage.md#Installing-JDK-without-setting-as-default) for more details.
- `problem-matcher`: Set to `false` to disable Java problem matcher annotations (compiler diagnostics and uncaught exceptions). Default value: `true`. See [Java problem matcher](docs/advanced-usage.md#java-problem-matcher-compiler-annotations) for details and annotation limits.
- `verify-signature`: Verifies downloaded Java package signatures when supported by the selected distribution. Currently supported for `temurin` and `microsoft`. If set to `true` for unsupported distributions, the action fails.
- `verify-signature-public-key`: ASCII-armored GPG public key used to verify the downloaded package signature. Overrides the default bundled key for the selected distribution.
- `token`: The token used to authenticate when fetching version manifests hosted on GitHub.com. Defaults to `${{ github.token }}` when running on GitHub.com; defaults to an empty string on GitHub Enterprise Server. On GHES, provide a GitHub.com personal access token if manifest requests are rate-limited. See [Using Microsoft distribution on GHES](docs/advanced-usage.md#using-microsoft-distribution-on-ghes) for more details.
- `cache`: Quick [setup caching](#caching-packages-dependencies) for the dependencies managed through one of the predefined package managers. It can be one of "maven", "gradle" or "sbt".
- `cache-dependency-path`: The path to a dependency file: pom.xml, build.gradle, build.sbt, etc. This option can be used with the `cache` option. If this option is omitted, the action searches for the dependency file in the entire repository. This option supports wildcards and a list of file names for caching multiple dependencies.
- `cache-path`: The dependency cache path to use instead of the default path for the package manager selected by `cache`. This option supports a list of paths and exclusion patterns. The build tool must be configured to use the same location.
- `cache-read-only`: Restore dependency caches without saving changes in the post action. Defaults to `false`. Use this for pull requests, merge queues, short-lived branches, and fan-out jobs that should consume caches populated by a default-branch or seed job.
#### Maven options
The action has a bunch of inputs to generate maven's [settings.xml](https://maven.apache.org/settings.html) on the fly and pass the values to Apache Maven GPG Plugin as well as Apache Maven Toolchains. See [advanced usage](docs/advanced-usage.md) for more.
- `overwrite-settings`: By default action overwrites the settings.xml. In order to skip generation of file if it exists, set this to `false`.
- `server-id`: ID of the distributionManagement repository in the pom.xml file. Default is `github`.
- `server-username-env-var`: Environment variable name for the username for authentication to the Apache Maven repository. Default is GITHUB\_ACTOR.
- `server-password-env-var`: Environment variable name for password or token for authentication to the Apache Maven repository. Default is GITHUB\_TOKEN.
- `settings-path`: Maven related setting to point to the directory where the settings.xml file will be written. Default is \~/.m2.
- `gpg-private-key`: GPG private key to import. Default is empty string.
- `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. 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.
- `show-download-progress`: Set to `true` to keep Maven artifact download and transfer progress in build logs. Default value: `false`. By default, the action adds `-ntp` (`--no-transfer-progress`) to `MAVEN_ARGS`. This input has no effect on non-Maven builds. See [Maven transfer progress](docs/advanced-usage.md#maven-transfer-progress-download-logs) for more details.
### Download integrity verification
When a selected distribution publishes an authoritative checksum for an archive, `setup-java` automatically verifies each downloaded JDK, JRE, or JMOD archive before extraction and caching. No input is required. Automatic checksum verification is currently available for `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 only in debug logs. Archives resolved directly from the runner tool cache are not downloaded again and therefore are not reverified.
Checksums detect corrupted or unexpectedly modified downloads before they are persisted in the runner tool cache.
### Basic Configuration
#### Eclipse Temurin
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
with:
distribution: 'temurin' # See 'Supported distributions' for available options
distribution: temurin
java-version: '25'
- run: java --version
```
#### Azul Zulu OpenJDK
### Install Microsoft Build of OpenJDK
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
with:
distribution: 'zulu' # See 'Supported distributions' for available options
distribution: microsoft
java-version: '25'
- run: java --version
```
#### Supported version syntax
The `java-version` input supports an exact version or a version range using [SemVer](https://semver.org/) notation. The values below are examples, not an exhaustive list:
- major versions, such as: `8`, `11`, `16`, `17`, `21`, `25`
- more specific versions: `8.0.282+8`, `8.0.232`, `11.0`, `11.0.4`, `17.0`
- multi-field Java versions (JEP 322), such as: `11.0.9.1`, `18.0.1.1`
- early access (EA) versions: `15-ea`, `15.0.0-ea`
- the `latest` alias, which floats to the newest available stable (GA) release
> [!NOTE]
> - `latest` always resolves the newest version from the distribution's remote metadata (it behaves like `check-latest: true`), so it ignores any older version already present in the runner tool cache. This has the same performance trade-off described in [Check latest](#check-latest).
> - `latest` is only supported through the `java-version` input, not through `java-version-file`, and it resolves stable (GA) releases only — it cannot be combined with `-ea`.
> - The `jdkfile` distribution does not support `latest`, as it installs from a local file.
> - For `oracle` and `graalvm` (Oracle GraalVM), `latest` uses the Adoptium API only to determine the newest GA **major version number** — the JDK binary itself is still downloaded from the Oracle / GraalVM servers for that major. Because these distributions have no endpoint to list their own releases, if their servers haven't published the resolved major yet, the action fails and asks you to specify a concrete version. Note the Oracle JDK license caveat below still applies to a floating `latest`.
> - For `graalvm-community`, `latest` floats to the newest GA release published on GitHub, so it never depends on the Adoptium API and always resolves to the newest major that GraalVM Community actually ships.
#### Supported distributions
Currently, the following distributions are supported:
| Keyword | Distribution / Official site | License
|-|-|-|
| `temurin` | [Eclipse Temurin](https://adoptium.net/) | [`temurin` license](https://adoptium.net/about.html)
| `zulu` | [Azul Zulu OpenJDK](https://www.azul.com/downloads/zulu-community/?package=jdk) | [`zulu` license](https://www.azul.com/products/zulu-and-zulu-enterprise/zulu-terms-of-use/) |
| `liberica` | [Liberica JDK](https://bell-sw.com/) | [`liberica` license](https://bell-sw.com/liberica_eula/) |
| `liberica-nik` | [Liberica Native Image Kit](https://bell-sw.com/pages/downloads/native-image-kit/) | [`liberica-nik` license](https://bell-sw.com/liberica_nik_eula/) |
| `microsoft` | [Microsoft Build of OpenJDK](https://www.microsoft.com/openjdk) | [`microsoft` license](https://docs.microsoft.com/java/openjdk/faq)
| `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)
| `graalvm-community` | [GraalVM Community](https://github.com/graalvm/graalvm-ce-builds/releases) | [`graalvm-community` license](https://github.com/oracle/graal/blob/master/LICENSE)
| `jetbrains` | [JetBrains Runtime](https://github.com/JetBrains/JetBrainsRuntime/) | [`jetbrains` license](https://github.com/JetBrains/JetBrainsRuntime/blob/main/LICENSE)
| `kona` | [Tencent Kona JDK](https://tencent.github.io/konajdk/) | [`kona` license](https://tencent.github.io/konajdk/LICENSE.txt)
| `jdkfile` | Custom JDK Installation | |
> [!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.
> - 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.
**NOTE:** Oracle JDK 17 licensing varies by patch level. As shown on the [JDK 17 Archive](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html) (versions up to 17.0.12 are under the [NFTC](https://www.oracle.com/downloads/licenses/no-fee-license.html) license) and the [JDK 17.0.13+ Archive](https://www.oracle.com/java/technologies/javase/jdk17-0-13-later-archive-downloads.html) (versions 17.0.13 and later are under the [OTN](https://www.oracle.com/downloads/licenses/javase-license1.html) license). To stay on the free NFTC license, use `distribution: 'oracle'` with `java-version: '17.0.12'` (or earlier) instead of the floating `'17'`. Alternatively, upgrade to Oracle JDK 21+, which remains under the NFTC license.
**NOTE:** On Ubuntu runners, commands executed via `sudo` do not inherit the `JAVA_HOME` and `PATH` set by `setup-java` and will fall back to the runner image's system-default JDK.
### Caching packages dependencies
The action has a built-in functionality for caching and restoring dependencies. It uses [toolkit/cache](https://github.com/actions/toolkit/tree/main/packages/cache) under hood for caching dependencies but requires less configuration settings. Supported package managers are gradle, maven and sbt. The format of the used cache key is `setup-java-${{ platform }}-${{ packageManager }}-${{ fileHash }}`, where the hash is based on the following files:
- gradle: `**/*.gradle*`, `**/gradle-wrapper.properties`, `buildSrc/**/Versions.kt`, `buildSrc/**/Dependencies.kt`, `gradle/*.versions.toml`, and `**/versions.properties`
- maven: `**/pom.xml`, `**/.mvn/wrapper/maven-wrapper.properties`, and `**/.mvn/extensions.xml`
- sbt: all sbt build definition files `**/*.sbt`, `**/project/build.properties`, `**/project/**.scala`, `**/project/**.sbt`
When the option `cache-dependency-path` is specified, the hash is based on the matching file. This option supports wildcards and a list of file names, and is especially useful for monorepos.
Use `cache-path` to replace the selected package manager's default dependency
cache paths. Each non-empty line is passed to `actions/cache`, including
supported exclusion patterns. `setup-java` does not configure the build tool,
so the build must use the same paths:
### Read the version from a file
```yaml
- uses: actions/setup-java@v6
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version-file: .java-version
- run: java --version
```
Supported version files are `.java-version`, `.tool-versions`, and `.sdkmanrc`. A `.sdkmanrc` file can also provide the distribution when it contains a recognized suffix, such as `java=21.0.5-tem`.
### Use the newest stable Java
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: latest
- run: java --version
```
`latest` resolves the newest stable GA release from remote metadata rather than from the runner tool cache. Distributions that do not publish a release listing (such as `oracle` and `graalvm`) resolve the newest GA feature version from the Adoptium available-releases API and then request that version from their own catalog. `latest` is not supported with `java-version-file`, early-access versions, or `distribution: jdkfile`.
## Inputs
| Input | Description | Default |
| --- | --- | --- |
| `java-version` | Java version to install. Supports whole versions, semver ranges, early-access versions, and `latest`. Required unless `java-version-file` is set. | |
| `java-version-file` | Path to `.java-version`, `.tool-versions`, or `.sdkmanrc`. Used when `java-version` is not set. | |
| `distribution` | Java distribution keyword. Values are case-sensitive and must match one of the supported keywords below. Required unless `java-version-file` points to `.sdkmanrc` with a recognized distribution suffix. | |
| `java-package` | Package variant such as `jdk`, `jre`, `jdk+fx`, `jre+fx`, `jdk+crac`, `jre+crac`, `jdk+jmods`, `jdk+jcef`, `jre+jcef`, `jdk+ft`, or `jre+ft`. Support varies by distribution. | `jdk` |
| `architecture` | Package architecture. Canonical values are `x86`, `x64`, `armv7`, `aarch64`, `ppc64le`, `ppc64`, and `s390x`. Aliases `ia32`, `amd64`, `arm`, and `arm64` are normalized. | Runner architecture |
| `jdk-file` | Local compressed JDK archive. Requires `distribution: jdkfile`. | |
| `check-latest` | Check remote metadata for the latest version satisfying the version spec before using the runner tool cache. | `false` |
| `force-download` | Always download Java and replace any matching version in the tool cache. | `false` |
| `set-default` | Add Java to `PATH` and set `JAVA_HOME`. When `false`, only version-specific `JAVA_HOME_<major>_<arch>` variables are set. | `true` |
| `problem-matcher` | Register Java compiler and uncaught exception problem matchers. | `true` |
| `verify-signature` | Verify downloaded Java package signatures when supported. Currently supported for `temurin` and `microsoft`. | `false` |
| `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 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` |
| `mvn-server-credentials` | Multiline Maven server credentials in the format `server-id:USERNAME_ENV:PASSWORD_ENV`. Replaces the single server configured by the three inputs above when set. | |
| `mvn-repositories` | Multiline Maven dependency repositories in the format `repository-id:repository-url:snapshots-enabled`. | |
| `mvn-repositories-include-central` | Include Maven Central in the generated dependency repositories profile. When `false`, Central is disabled unless an explicit `central` repository is declared. | `true` |
| `mvn-repositories-prioritize-central` | Place Maven Central before custom dependency repositories. Has no effect when Maven Central is excluded. | `true` |
| `settings-path` | Directory where `settings.xml` is written. | `~/.m2` |
| `overwrite-settings` | Overwrite an existing `settings.xml`. | `true` |
| `gpg-private-key` | GPG private key to import into an isolated temporary keyring. | |
| `gpg-passphrase-env-var` | Environment variable name for the GPG private key passphrase. | `GPG_PASSPHRASE` when a key is set |
| `mvn-toolchain-id` | Maven Toolchain ID. When multiple Java versions are installed, the number of IDs must match the number of versions. | `${mvn-toolchain-vendor}_${java-version}` |
| `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
| Output | Description |
| --- | --- |
| `distribution` | Distribution that was installed. |
| `version` | Actual Java version that was installed. |
| `path` | Installation path, also used for `JAVA_HOME` when `set-default` is enabled. |
| `cache-hit` | Whether an exact dependency cache match was restored. |
| `cache-primary-key` | Primary cache key computed for the selected package manager. Empty when caching is disabled or skipped. |
## Supported distributions
| Keyword | Distribution | License |
| --- | --- | --- |
| `corretto` | [Amazon Corretto](https://aws.amazon.com/corretto/) | [License](https://aws.amazon.com/corretto/faqs/) |
| `dragonwell` | [Alibaba Dragonwell JDK](https://dragonwell-jdk.io/) | [License](https://www.aliyun.com/product/dragonwell/) |
| `graalvm` | [Oracle GraalVM](https://www.graalvm.org/) | [License](https://www.oracle.com/downloads/licenses/graal-free-license.html) |
| `graalvm-community` | [GraalVM Community](https://github.com/graalvm/graalvm-ce-builds/releases) | [License](https://github.com/oracle/graal/blob/master/LICENSE) |
| `jetbrains` | [JetBrains Runtime](https://github.com/JetBrains/JetBrainsRuntime/) | [License](https://github.com/JetBrains/JetBrainsRuntime/blob/main/LICENSE) |
| `kona` | [Tencent Kona JDK](https://tencent.github.io/konajdk/) | [License](https://tencent.github.io/konajdk/LICENSE.txt) |
| `liberica` | [Liberica JDK](https://bell-sw.com/) | [License](https://bell-sw.com/liberica_eula/) |
| `liberica-nik` | [Liberica Native Image Kit](https://bell-sw.com/pages/downloads/native-image-kit/) | [License](https://bell-sw.com/liberica_nik_eula/) |
| `microsoft` | [Microsoft Build of OpenJDK](https://www.microsoft.com/openjdk) | [License](https://docs.microsoft.com/java/openjdk/faq) |
| `oracle` | [Oracle JDK](https://www.oracle.com/java/technologies/downloads/) | [License](https://java.com/freeuselicense) |
| `oracle-openjdk` | [Oracle OpenJDK](https://jdk.java.net/) | [License](https://openjdk.org/legal/gplv2+ce.html) |
| `redhat` | [Red Hat Build of OpenJDK](https://developers.redhat.com/products/openjdk/overview) | [License](https://openjdk.org/legal/gplv2+ce.html) |
| `sapmachine` | [SAP SapMachine JDK/JRE](https://sapmachine.io/) | [License](https://github.com/SAP/SapMachine/blob/sapmachine/LICENSE) |
| `semeru` | [IBM Semeru Runtime Open Edition](https://developer.ibm.com/languages/java/semeru-runtimes/downloads/) | [License](https://openjdk.java.net/legal/gplv2+ce.html) |
| `temurin` | [Eclipse Temurin](https://adoptium.net/) | [License](https://adoptium.net/about.html) |
| `zulu` | [Azul Zulu OpenJDK](https://www.azul.com/downloads/zulu-community/?package=jdk) | [License](https://www.azul.com/products/zulu-and-zulu-enterprise/zulu-terms-of-use/) |
| `jdkfile` | Custom JDK archive | |
> [!NOTE]
> Distribution availability, package variants, architectures, and version metadata differ by vendor. Check the vendor documentation when a specific version or platform matters.
Additional distribution notes:
- Oracle OpenJDK builds are archived after a limited number of releases and no longer receive security updates. To continue receiving security patches, use Oracle JDK or another vendor.
- Azul Zulu maps `arm64` to `aarch64` when querying the Azul Metadata API.
- GraalVM Community is available as `distribution: graalvm-community` for stable JDK 17 and later releases.
- On Ubuntu runners, commands executed with `sudo` do not inherit the `JAVA_HOME` and `PATH` set by `setup-java` and may fall back to the system-default JDK.
## Supported version syntax
`java-version` accepts exact versions, version ranges, early-access versions, and `latest`.
| Syntax | Examples |
| --- | --- |
| Major version | `8`, `11`, `17`, `21`, `25` |
| Specific feature or patch version | `11.0`, `11.0.4`, `17.0`, `8.0.282+8` |
| JEP 322 multi-field versions | `11.0.9.1`, `18.0.1.1` |
| Early access | `15-ea`, `15.0.0-ea`, `27-ea` |
| Latest stable GA release | `latest` |
When `check-latest` is `false`, the action first tries the runner tool cache for the requested distribution, package type, architecture, and version range. It downloads Java only when no matching cached version is found. When `check-latest` is `true`, the action checks remote metadata first and downloads if the cached version is not current.
GitHub-hosted runners primarily pre-cache Eclipse Temurin JDKs. See the installed Java versions for [Ubuntu](https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2404-Readme.md#java), [Windows](https://github.com/actions/runner-images/blob/main/images/windows/Windows2025-Readme.md#java), and [macOS](https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md#java). On a fresh GitHub-hosted runner, requests for other distributions usually miss the tool cache and resolve from remote metadata. For broad version ranges such as a major version (`21`, `25`), this often behaves similarly to `check-latest: true` because the action downloads the latest available release that satisfies the range.
## Download integrity and signatures
`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. 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
`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.
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '25'
cache: maven
- run: mvn verify
```
The primary dependency cache key is `setup-java-<runner-os>-<node-arch>-<package-manager>-<file-hash>`, where `<node-arch>` is the runner's Node.js process architecture. The primary cache stores dependency directories such as `~/.m2/repository`, `~/.gradle/caches`, or the sbt cache paths. Its file hash is based on these files by default:
| Package manager | Files used for the primary dependency-cache key |
| --- | --- |
| Gradle | `**/*.gradle*`, `**/gradle.properties`, `**/gradle-wrapper.properties`, `buildSrc/**/Versions.kt`, `buildSrc/**/Dependencies.kt`, `gradle/*.versions.toml`, `**/versions.properties` |
| Maven | `**/pom.xml`, `**/.mvn/wrapper/maven-wrapper.properties`, `**/.mvn/extensions.xml` |
| sbt | `**/*.sbt`, `**/project/build.properties`, `**/project/**.scala`, `**/project/**.sbt` |
Use `cache-dependency-path` to override the files used for key hashing, especially in monorepos:
```yaml
- uses: actions/setup-java@v5
with:
distribution: 'temurin'
distribution: temurin
java-version: '25'
cache: 'maven'
cache: gradle
cache-dependency-path: |
sub-project/*.gradle*
sub-project/**/gradle-wrapper.properties
```
Use `cache-path` when the build tool stores dependencies outside the default location:
```yaml
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '25'
cache: maven
cache-path: |
/custom/maven/repository
!/custom/maven/repository/**/*.lastUpdated
- run: mvn -Dmaven.repo.local=/custom/maven/repository verify
```
`cache-path` does not change the cache key. The key continues to use the runner
OS, architecture, selected package manager, and dependency-file hash described
above. Jobs intended to share a cache key must therefore use the same
`cache-path` values so that they restore and save the same filesystem
locations.
`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.
The Maven and Gradle wrapper caches remain at their documented default paths
and are managed independently of `cache-path`. For advanced keying, fallback
keys, or cache topologies that do not map to one package manager's dependency
paths, use [`actions/cache`](https://github.com/actions/cache) directly.
### Wrapper caches
The workflow output `cache-hit` is set to indicate if an exact match was found for the key [as actions/cache does](https://github.com/actions/cache/tree/main#outputs).
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>`.
The workflow output `cache-primary-key` exposes the primary cache key computed by the action for the configured build tool. It is useful for composing with [`actions/cache`](https://github.com/actions/cache) or [`actions/cache/restore`](https://github.com/actions/cache/tree/main/restore) in later steps or dependent jobs that need to reuse the exact same key. It is empty when caching is not enabled or when caching is skipped (for example, when the cache service is unavailable).
| 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` |
The cache input is optional, and caching is turned off by default.
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.
Set `cache-read-only: true` to restore the main dependency cache and any Maven
or Gradle wrapper cache without archiving or uploading changes after the job.
For example, a workflow can allow only the default branch to write caches while
pull requests, merge queues, and short-lived branches remain read-only:
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, 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@v6
- uses: actions/setup-java@v5
with:
distribution: 'temurin'
distribution: temurin
java-version: '25'
cache: 'maven'
cache: maven
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
```
For a fan-out matrix, use one seed job to populate a complete cache and make
every matrix job a read-only consumer. The seed and consumers must use the same
runner OS and cache dependency inputs so they compute the same key:
For matrix fan-out, seed the cache once and make matrix jobs read-only consumers:
```yaml
jobs:
@@ -247,11 +354,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
with:
distribution: 'temurin'
distribution: temurin
java-version: '25'
cache: 'maven'
cache: maven
- run: mvn dependency:go-offline dependency:resolve-plugins
build:
@@ -262,178 +369,116 @@ jobs:
goal: [test, verify, package]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
with:
distribution: 'temurin'
distribution: temurin
java-version: '25'
cache: 'maven'
cache: maven
cache-read-only: true
- run: mvn ${{ matrix.goal }}
```
**Maven Wrapper:** when `cache: 'maven'` is enabled, the action also caches and restores the Maven Wrapper distribution downloaded to `~/.m2/wrapper/dists` (in addition to the local repository), so wrapper-based (`./mvnw`) builds don't re-download the Maven distribution. The wrapper distribution is stored in a **separate** cache entry keyed only on `**/.mvn/wrapper/maven-wrapper.properties`, so it stays cached across the frequent `pom.xml` changes that rotate the main dependency cache key.
### Cache segment restore timeout
#### Caching gradle dependencies
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: 'temurin'
java-version: '25'
cache: 'gradle'
cache-dependency-path: | # optional
sub-project/*.gradle*
sub-project/**/gradle-wrapper.properties
- run: ./gradlew build --no-daemon
```
Using the `cache: gradle` provides a simple and effective way to cache Gradle dependencies with minimal configuration.
**Gradle Wrapper:** when `cache: 'gradle'` is enabled, the action also caches and restores the Gradle Wrapper distribution downloaded to `~/.gradle/wrapper` (in addition to the Gradle caches), so wrapper-based (`./gradlew`) builds don't re-download the Gradle distribution. The wrapper distribution is stored in a **separate** cache entry keyed only on `**/gradle-wrapper.properties`, so it stays cached across the frequent `*.gradle*` changes that rotate the main dependency cache key.
For projects that require more advanced `Gradle` caching features, such as caching build outputs, support for Gradle configuration cache, encrypted cache storage, fine-grained cache control (including options to enable or disable the cache, set it to read-only or write-only, perform automated cleanup, and define custom cache rules), or optimized performance for complex CI workflows, consider using [`gradle/actions/setup-gradle`](https://github.com/gradle/actions/tree/main/setup-gradle).
For setup details and a comprehensive overview of all available features, visit the [setup-gradle documentation](https://github.com/gradle/actions/blob/main/docs/setup-gradle.md).
#### Caching maven dependencies
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: 'temurin'
java-version: '25'
cache: 'maven'
cache-dependency-path: 'sub-project/pom.xml' # optional
- name: Build with Maven
run: mvn package --file pom.xml
```
> [!NOTE]
> Maven resolves plugin dependencies lazily, so a cache created by a "thin" goal
> (e.g. `mvn compile`) can be missing plugin dependencies that later
> `test`/`verify`/`package` jobs then re-download on every run. See
> [Ensuring the Maven cache is complete](docs/advanced-usage.md#ensuring-the-maven-cache-is-complete-plugin-dependencies)
> for how to seed a complete cache.
#### Caching sbt dependencies
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: 'temurin'
java-version: '25'
cache: 'sbt'
cache-dependency-path: | # optional
sub-project/build.sbt
sub-project/project/build.properties
- name: Build with SBT
run: sbt package
```
#### Cache segment restore timeout
Usually, cache gets downloaded in multiple segments of fixed sizes. Sometimes, a segment download gets stuck, which causes the workflow job to be stuck. The cache segment download timeout [was introduced](https://github.com/actions/toolkit/tree/main/packages/cache#cache-segment-restore-timeout) to solve this issue as it allows the segment download to get aborted and hence allows the job to proceed with a cache miss. The default value of the cache segment download timeout is set to 10 minutes and can be customized by specifying an environment variable named `SEGMENT_DOWNLOAD_TIMEOUT_MINS` with a timeout value in minutes.
Cache downloads are split into segments. To reduce the chance of a stuck segment blocking a workflow, set `SEGMENT_DOWNLOAD_TIMEOUT_MINS`:
```yaml
env:
SEGMENT_DOWNLOAD_TIMEOUT_MINS: '5'
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
with:
distribution: 'temurin'
distribution: temurin
java-version: '25'
cache: 'gradle'
cache: gradle
- run: ./gradlew build --no-daemon
```
### Check latest
## Multiple JDKs and Maven toolchains
In the basic examples above, the `check-latest` flag defaults to `false`. When set to `false`, the action tries to first resolve a version of Java from the local tool cache on the runner. If unable to find a specific version in the cache, the action will download a version of Java. Use the default or set `check-latest` to `false` if you prefer a faster more consistent setup experience that prioritizes trying to use the cached versions at the expense of newer versions sometimes being available for download.
Install multiple Java versions by providing a multiline `java-version` value. All configured JDKs are installed. The last one added to `PATH` becomes the default.
If `check-latest` is set to `true`, the action first checks if the cached version is the latest one. If the locally cached version is not the most up-to-date, the latest version of Java will be downloaded. Set `check-latest` to `true` if you want the most up-to-date version of Java to always be used. Setting `check-latest` to `true` has performance implications as downloading versions of Java is slower than using cached versions.
```yaml
steps:
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: |
8
11
17
21
25
```
[GitHub-hosted runners](https://github.com/actions/runner-images) include Eclipse Temurin JDKs in their tool cache. Selecting Eclipse Temurin (`distribution: 'temurin'`) can save setup time by using a pre-installed JDK instead of downloading one. See the installed Java versions for [Ubuntu](https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2404-Readme.md#java), [Windows](https://github.com/actions/runner-images/blob/main/images/windows/Windows2025-Readme.md#java), and [macOS](https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md#java).
Other installed JDKs are available through version-specific variables such as `JAVA_HOME_17_X64`. To use a specific version later in the job, set `JAVA_HOME` and prepend its `bin` directory to `PATH`.
For Java distributions that are not cached on Hosted images, `check-latest` always behaves as `true` and downloads Java on the fly. Check out [Hosted Tool Cache](docs/advanced-usage.md#Hosted-Tool-Cache) for more details about pre-cached Java versions.
`setup-java` writes a Maven Toolchains declaration for each installed JDK. When multiple JDKs are installed, the declaration contains all of them. Customize the generated toolchain values with `mvn-toolchain-id` and `mvn-toolchain-vendor`.
## Testing with a Java matrix
```yaml
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java: ['8', '11', '17', '21', '25']
name: Java ${{ matrix.java }}
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: ${{ matrix.java }}
- run: java --version
- run: mvn verify
```
## Publishing packages
`setup-java` generates Maven `settings.xml` and Maven Toolchains configuration. For Gradle publishing, it installs Java for the workflow; the Gradle build file remains responsible for reading credentials from environment variables.
### Maven
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
with:
distribution: 'temurin'
distribution: temurin
java-version: '25'
check-latest: true
- run: java --version
server-id: github
server-username-env-var: GITHUB_ACTOR
server-password-env-var: GITHUB_TOKEN
- run: mvn --batch-mode deploy
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
```
### Testing against different Java versions
```yaml
jobs:
build:
runs-on: ubuntu-20.04
strategy:
matrix:
java: [ '8', '11', '17', '21', '25' ]
name: Java ${{ matrix.Java }} sample
steps:
- uses: actions/checkout@v7
- name: Setup java
uses: actions/setup-java@v6
with:
distribution: '<distribution>'
java-version: ${{ matrix.java }}
- run: java --version
```
For dependencies hosted outside Maven Central, use `mvn-repositories` to add
resolution repositories to an active profile in the generated `settings.xml`.
Repository IDs can match `mvn-server-credentials` IDs when authentication is
required. See [Resolving Maven dependencies from custom repositories](docs/advanced-usage.md#resolving-maven-dependencies-from-custom-repositories).
### Install multiple JDKs
All configured Java versions are added to the PATH. The last one added to the PATH (i.e., the last JDK set up by this action) will be used as the default and available globally. Other Java versions can be accessed through environment variables such as 'JAVA\_HOME\_{{ MAJOR\_VERSION }}\_{{ ARCHITECTURE }}'. To use a specific Java version, set the JAVA\_HOME environment variable accordingly and prepend its bin directory to the PATH to ensure it takes priority during execution.
### GPG signing
```yaml
steps:
- uses: actions/setup-java@v6
with:
distribution: '<distribution>'
java-version: |
8
11
15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '25'
gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }}
gpg-passphrase-env-var: GPG_PASSPHRASE
- run: mvn --batch-mode deploy
env:
GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
```
### Using Maven Toolchains
In the example above multiple JDKs are installed for the same job. The result after the last JDK is installed is a Maven Toolchains declaration containing references to all three JDKs. The values for `id`, `version`, and `vendor` of the individual Toolchain entries are the given input values for `distribution` and `java-version` (`vendor` being the combination of `${distribution}_${java-version}`) by default.
### Advanced Configuration
- [Selecting a Java distribution](docs/advanced-usage.md#Selecting-a-Java-distribution)
- [Eclipse Temurin](docs/advanced-usage.md#Eclipse-Temurin)
- [Adopt](docs/advanced-usage.md#Adopt)
- [Zulu](docs/advanced-usage.md#Zulu)
- [Liberica](docs/advanced-usage.md#Liberica)
- [Liberica Native Image Kit](docs/advanced-usage.md#Liberica-Native-Image-Kit)
- [Microsoft](docs/advanced-usage.md#Microsoft)
- [Amazon Corretto](docs/advanced-usage.md#Amazon-Corretto)
- [Oracle](docs/advanced-usage.md#Oracle)
- [Alibaba Dragonwell](docs/advanced-usage.md#Alibaba-Dragonwell)
- [SapMachine](docs/advanced-usage.md#SapMachine)
- [GraalVM](docs/advanced-usage.md#GraalVM)
- [JetBrains](docs/advanced-usage.md#JetBrains)
- [Tencent Kona](docs/advanced-usage.md#Tencent-Kona)
- [Installing custom Java package type](docs/advanced-usage.md#Installing-custom-Java-package-type)
- [Installing custom Java architecture](docs/advanced-usage.md#Installing-custom-Java-architecture)
- [Installing custom Java distribution from local file](docs/advanced-usage.md#Installing-Java-from-local-file)
- [Testing against different Java distributions](docs/advanced-usage.md#Testing-against-different-Java-distributions)
- [Testing against different platforms](docs/advanced-usage.md#Testing-against-different-platforms)
- [Publishing using Apache Maven](docs/advanced-usage.md#Publishing-using-Apache-Maven)
- [Maven transfer progress (download logs)](docs/advanced-usage.md#maven-transfer-progress-download-logs)
- [Publishing using Gradle](docs/advanced-usage.md#Publishing-using-Gradle)
- [Hosted Tool Cache](docs/advanced-usage.md#Hosted-Tool-Cache)
- [Modifying Maven Toolchains](docs/advanced-usage.md#Modifying-Maven-Toolchains)
- [Java Version File](docs/advanced-usage.md#Java-version-file)
Maven GPG signing requires `maven-gpg-plugin` 3.2.0 or newer because `setup-java` passes the passphrase through `gpg.passphraseEnvName`.
## Recommended permissions
@@ -444,10 +489,41 @@ permissions:
contents: read # access to check out code and install dependencies
```
Publishing workflows may require additional permissions depending on the target registry.
## Advanced usage
See [advanced usage](docs/advanced-usage.md) for detailed examples:
- [Selecting a Java distribution](docs/advanced-usage.md#selecting-a-java-distribution)
- [Installing custom Java package types](docs/advanced-usage.md#installing-custom-java-package-type)
- [Package compatibility](docs/advanced-usage.md#package-compatibility)
- [Ensuring the Maven cache is complete](docs/advanced-usage.md#ensuring-the-maven-cache-is-complete-plugin-dependencies)
- [Caching JDK installations](docs/advanced-usage.md#caching-jdk-installations)
- [Platform and architecture compatibility](docs/advanced-usage.md#platform-and-architecture-compatibility)
- [Installing custom Java architecture](docs/advanced-usage.md#installing-custom-java-architecture)
- [Installing a JDK without setting it as default](docs/advanced-usage.md#installing-jdk-without-setting-as-default)
- [Installing Java from a local file](docs/advanced-usage.md#installing-java-from-local-file)
- [Testing against different Java distributions](docs/advanced-usage.md#testing-against-different-java-distributions)
- [Testing against different platforms](docs/advanced-usage.md#testing-against-different-platforms)
- [Publishing using Apache Maven](docs/advanced-usage.md#publishing-using-apache-maven)
- [Apache Maven with a settings path](docs/advanced-usage.md#apache-maven-with-a-settings-path)
- [Maven transfer progress](docs/advanced-usage.md#maven-transfer-progress-download-logs)
- [Java problem matcher](docs/advanced-usage.md#java-problem-matcher-compiler-annotations)
- [Publishing using Gradle](docs/advanced-usage.md#publishing-using-gradle)
- [Hosted tool cache](docs/advanced-usage.md#hosted-tool-cache)
- [Modifying Maven Toolchains](docs/advanced-usage.md#modifying-maven-toolchains)
- [Java version files](docs/advanced-usage.md#java-version-file)
- [Self-signed certificates and internal CAs on GitHub Enterprise](docs/advanced-usage.md#self-signed-certificates-and-internal-cas-github-enterprise)
## License
The scripts and documentation in this project are released under the [MIT License](LICENSE).
## Contributions
Contributions are welcome! See [Contributor's Guide](docs/contributors.md)
Contributions are welcome. See our [Contributor's Guide](docs/contributors.md).
## Code of Conduct
:wave: Be nice. See [our code of conduct](CODE_OF_CONDUCT.md)
+543 -29
View File
@@ -26,7 +26,7 @@ jest.unstable_mockModule('@actions/core', () => ({
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
getMultilineInput: jest.fn(() => []),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
@@ -41,14 +41,34 @@ jest.unstable_mockModule('@actions/core', () => ({
toPosixPath: jest.fn((p: string) => p)
}));
jest.unstable_mockModule('../src/gpg.js', () => ({
importKey: jest.fn(),
removeGpgHome: jest.fn(),
toGpgPath: jest.fn()
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const gpg = await import('../src/gpg.js');
const auth = await import('../src/auth.js');
const {M2_DIR, MVN_SETTINGS_FILE} = await import('../src/constants.js');
const {M2_DIR, MVN_SETTINGS_FILE, STATE_GPG_HOME} =
await import('../src/constants.js');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const m2Dir = path.join(__dirname, M2_DIR);
const settingsFile = path.join(m2Dir, MVN_SETTINGS_FILE);
const credentials = (id: string, username: string, password: string) => [
{id, usernameEnvVar: username, passwordEnvVar: password}
];
const repositorySettings = (
repositories: auth.MavenRepository[],
includeCentral = true,
prioritizeCentral = true
): auth.MavenRepositorySettings => ({
repositories,
includeCentral,
prioritizeCentral
});
describe('auth tests', () => {
let spyOSHomedir: any;
@@ -60,8 +80,20 @@ describe('auth tests', () => {
spyOSHomedir.mockReturnValue(__dirname);
spyInfo = core.info as jest.Mock;
spyInfo.mockImplementation(() => null);
(gpg.toGpgPath as jest.Mock<any>).mockImplementation((p: string) => p);
}, 300000);
afterEach(() => {
(core.getInput as jest.Mock).mockReset();
(core.getMultilineInput as jest.Mock).mockReset();
(core.getMultilineInput as jest.Mock).mockReturnValue([]);
(core.warning as jest.Mock).mockReset();
(core.exportVariable as jest.Mock).mockReset();
(gpg.importKey as jest.Mock).mockReset();
(gpg.removeGpgHome as jest.Mock).mockReset();
(gpg.toGpgPath as jest.Mock).mockReset();
});
afterAll(async () => {
try {
await io.rmRF(m2Dir);
@@ -83,9 +115,7 @@ describe('auth tests', () => {
await io.rmRF(altHome); // ensure it doesn't already exist
await auth.createAuthenticationSettings(
id,
username,
password,
credentials(id, username, password),
altHome,
true
);
@@ -96,7 +126,7 @@ describe('auth tests', () => {
expect(fs.existsSync(altHome)).toBe(true);
expect(fs.existsSync(altSettingsFile)).toBe(true);
expect(fs.readFileSync(altSettingsFile, 'utf-8')).toEqual(
auth.generate(id, username, password)
auth.generate(credentials(id, username, password))
);
await io.rmRF(altHome);
@@ -108,9 +138,7 @@ describe('auth tests', () => {
const password = 'TOKEN';
await auth.createAuthenticationSettings(
id,
username,
password,
credentials(id, username, password),
m2Dir,
true
);
@@ -118,7 +146,7 @@ describe('auth tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
expect(fs.readFileSync(settingsFile, 'utf-8')).toEqual(
auth.generate(id, username, password)
auth.generate(credentials(id, username, password))
);
}, 100000);
@@ -129,9 +157,7 @@ describe('auth tests', () => {
const gpgPassphrase = 'GPG';
await auth.createAuthenticationSettings(
id,
username,
password,
credentials(id, username, password),
m2Dir,
true,
gpgPassphrase
@@ -140,10 +166,56 @@ describe('auth tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
expect(fs.readFileSync(settingsFile, 'utf-8')).toEqual(
auth.generate(id, username, password, gpgPassphrase)
auth.generate(credentials(id, username, password), gpgPassphrase)
);
}, 100000);
it('exports a GPG-compatible path and persists the native GPG home', async () => {
const gpgHome = 'D:\\a\\_temp\\setup-java-gpg-1';
const exportedGpgHome = '/d/a/_temp/setup-java-gpg-1';
(gpg.importKey as jest.Mock<any>).mockResolvedValue(gpgHome);
(gpg.toGpgPath as jest.Mock<any>).mockReturnValue(exportedGpgHome);
(core.getInput as jest.Mock<any>).mockImplementation((name: string) => {
const inputs: Record<string, string> = {
'server-id': 'packages',
'server-username-env-var': 'USERNAME',
'server-password-env-var': 'PASSWORD',
'settings-path': m2Dir,
'gpg-private-key': 'KEY ONE\nKEY TWO'
};
return inputs[name] ?? '';
});
await auth.configureAuthentication();
expect(gpg.importKey).toHaveBeenCalledWith('KEY ONE\nKEY TWO');
expect(core.saveState).toHaveBeenCalledWith(STATE_GPG_HOME, gpgHome);
expect(gpg.toGpgPath).toHaveBeenCalledWith(gpgHome);
expect(core.exportVariable).toHaveBeenCalledWith(
'GNUPGHOME',
exportedGpgHome
);
});
it('removes the isolated GPG home when environment export fails', async () => {
const gpgHome = path.join(__dirname, 'runner', 'temp', 'setup-java-gpg-2');
(gpg.importKey as jest.Mock<any>).mockResolvedValue(gpgHome);
(core.exportVariable as jest.Mock<any>).mockImplementation(() => {
throw new Error('environment file unavailable');
});
(core.getInput as jest.Mock<any>).mockImplementation((name: string) => {
if (name === 'gpg-private-key') return 'KEY CONTENTS';
if (name === 'settings-path') return m2Dir;
return '';
});
await expect(auth.configureAuthentication()).rejects.toThrow(
'environment file unavailable'
);
expect(gpg.removeGpgHome).toHaveBeenCalledWith(gpgHome);
});
it('overwrites existing settings.xml files', async () => {
const id = 'packages';
const username = 'USERNAME';
@@ -155,9 +227,7 @@ describe('auth tests', () => {
expect(fs.existsSync(settingsFile)).toBe(true);
await auth.createAuthenticationSettings(
id,
username,
password,
credentials(id, username, password),
m2Dir,
true
);
@@ -165,7 +235,7 @@ describe('auth tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
expect(fs.readFileSync(settingsFile, 'utf-8')).toEqual(
auth.generate(id, username, password)
auth.generate(credentials(id, username, password))
);
}, 100000);
@@ -180,9 +250,7 @@ describe('auth tests', () => {
expect(fs.existsSync(settingsFile)).toBe(true);
await auth.createAuthenticationSettings(
id,
username,
password,
credentials(id, username, password),
m2Dir,
false
);
@@ -210,7 +278,9 @@ describe('auth tests', () => {
</servers>
</settings>`;
expect(auth.generate(id, username, password)).toEqual(expectedSettings);
expect(auth.generate(credentials(id, username, password))).toEqual(
expectedSettings
);
});
it('generates valid settings.xml with additional configuration', () => {
@@ -243,9 +313,9 @@ describe('auth tests', () => {
</activeProfiles>
</settings>`;
expect(auth.generate(id, username, password, gpgPassphrase)).toEqual(
expectedSettings
);
expect(
auth.generate(credentials(id, username, password), gpgPassphrase)
).toEqual(expectedSettings);
});
it('does not add a gpg profile when the passphrase env var is the maven-gpg-plugin default', () => {
@@ -267,9 +337,9 @@ describe('auth tests', () => {
</servers>
</settings>`;
expect(auth.generate(id, username, password, gpgPassphrase)).toEqual(
expectedSettings
);
expect(
auth.generate(credentials(id, username, password), gpgPassphrase)
).toEqual(expectedSettings);
});
it('escapes settings.xml values while preserving parsed semantics', () => {
@@ -278,7 +348,10 @@ describe('auth tests', () => {
const password = `TOKEN&<>"'é`;
const gpgPassphrase = `GPG&<>"'é`;
const xml = auth.generate(id, username, password, gpgPassphrase);
const xml = auth.generate(
credentials(id, username, password),
gpgPassphrase
);
const parsed = parseXmlObject(xml) as any;
expect(parsed.settings.interactiveMode).toBe('false');
@@ -289,6 +362,447 @@ describe('auth tests', () => {
expect(parsed.settings.activeProfiles.activeProfile).toBe('setup-java-gpg');
});
it('generates ordered settings.xml entries for multiple servers', () => {
const servers = [
{
id: 'releases',
usernameEnvVar: 'RELEASES_USERNAME',
passwordEnvVar: 'RELEASES_PASSWORD'
},
{
id: 'snapshots',
usernameEnvVar: 'SNAPSHOTS_USERNAME',
passwordEnvVar: 'SNAPSHOTS_PASSWORD'
}
];
const parsed = parseXmlObject(auth.generate(servers)) as any;
expect(parsed.settings.servers.server).toEqual([
{
id: 'releases',
username: '${env.RELEASES_USERNAME}',
password: '${env.RELEASES_PASSWORD}'
},
{
id: 'snapshots',
username: '${env.SNAPSHOTS_USERNAME}',
password: '${env.SNAPSHOTS_PASSWORD}'
}
]);
});
it('generates an active profile with Central before custom repositories by default', () => {
const parsed = parseXmlObject(
auth.generate(
credentials('packages', 'USERNAME', 'PASSWORD'),
undefined,
repositorySettings([
{
id: 'private',
url: 'https://repo.example.com/maven',
snapshotsEnabled: true
}
])
)
) as any;
expect(parsed.settings.profiles.profile).toEqual({
id: 'setup-java-repositories',
repositories: {
repository: [
{
id: 'central',
url: 'https://repo.maven.apache.org/maven2',
snapshots: {enabled: 'false'}
},
{
id: 'private',
url: 'https://repo.example.com/maven',
snapshots: {enabled: 'true'}
}
]
}
});
expect(parsed.settings.activeProfiles.activeProfile).toBe(
'setup-java-repositories'
);
});
it('places custom repositories before Central when configured', () => {
const parsed = parseXmlObject(
auth.generate(
credentials('packages', 'USERNAME', 'PASSWORD'),
undefined,
repositorySettings(
[
{
id: 'first',
url: 'https://first.example.com',
snapshotsEnabled: false
},
{
id: 'second',
url: 'https://second.example.com',
snapshotsEnabled: true
}
],
true,
false
)
)
) as any;
expect(
parsed.settings.profiles.profile.repositories.repository.map(
(repository: {id: string}) => repository.id
)
).toEqual(['first', 'second', 'central']);
});
it('excludes Central from the generated repository profile when configured', () => {
const parsed = parseXmlObject(
auth.generate(
credentials('packages', 'USERNAME', 'PASSWORD'),
undefined,
repositorySettings(
[
{
id: 'private',
url: 'https://repo.example.com',
snapshotsEnabled: false
}
],
false
)
)
) as any;
expect(parsed.settings.profiles.profile.repositories.repository).toEqual([
{
id: 'private',
url: 'https://repo.example.com',
snapshots: {enabled: 'false'}
},
{
id: 'central',
url: 'https://repo.maven.apache.org/maven2',
releases: {enabled: 'false'},
snapshots: {enabled: 'false'}
}
]);
});
it('combines repository and GPG configuration in shared profile blocks', () => {
const parsed = parseXmlObject(
auth.generate(
credentials('packages', 'USERNAME', 'PASSWORD'),
'GPG_PASSPHRASE',
repositorySettings(
[
{
id: 'private',
url: 'https://repo.example.com',
snapshotsEnabled: false
}
],
false
)
)
) as any;
expect(parsed.settings.profiles.profile).toEqual([
{
id: 'setup-java-repositories',
repositories: {
repository: [
{
id: 'private',
url: 'https://repo.example.com',
snapshots: {enabled: 'false'}
},
{
id: 'central',
url: 'https://repo.maven.apache.org/maven2',
releases: {enabled: 'false'},
snapshots: {enabled: 'false'}
}
]
}
},
{
id: 'setup-java-gpg',
properties: {['gpg.passphraseEnvName']: 'GPG_PASSPHRASE'}
}
]);
expect(parsed.settings.activeProfiles.activeProfile).toEqual([
'setup-java-repositories',
'setup-java-gpg'
]);
});
it('escapes repository values while preserving parsed semantics', () => {
const repository = {
id: `private&<>"'é`,
url: `https://repo.example.com/a?x=1&y=<value>"'é`,
snapshotsEnabled: true
};
const xml = auth.generate(
credentials('packages', 'USERNAME', 'PASSWORD'),
undefined,
repositorySettings([repository], false)
);
const parsed = parseXmlObject(xml) as any;
expect(
parsed.settings.profiles.profile.repositories.repository.find(
(entry: {id: string}) => entry.id === repository.id
)
).toEqual({
id: repository.id,
url: repository.url,
snapshots: {enabled: 'true'}
});
});
it('parses and trims multiline Maven server credentials', () => {
expect(
auth.parseMavenServerCredentials([
'',
' releases : RELEASES_USERNAME : RELEASES_PASSWORD ',
'snapshots:SNAPSHOTS_USERNAME:SNAPSHOTS_PASSWORD'
])
).toEqual([
{
id: 'releases',
usernameEnvVar: 'RELEASES_USERNAME',
passwordEnvVar: 'RELEASES_PASSWORD'
},
{
id: 'snapshots',
usernameEnvVar: 'SNAPSHOTS_USERNAME',
passwordEnvVar: 'SNAPSHOTS_PASSWORD'
}
]);
});
it('parses Maven repositories while preserving colons in URLs', () => {
expect(
auth.parseMavenRepositories(
[
'',
' private : https://repo.example.com:8443/maven : true ',
'releases:https://repo.example.com/releases:false'
],
true
)
).toEqual([
{
id: 'private',
url: 'https://repo.example.com:8443/maven',
snapshotsEnabled: true
},
{
id: 'releases',
url: 'https://repo.example.com/releases',
snapshotsEnabled: false
}
]);
});
it.each([
{
entries: ['private'],
error:
'Invalid mvn-repositories entry at line 1. Expected format: repository-id:repository-url:snapshots-enabled'
},
{
entries: ['private:https://repo.example.com'],
error:
"Invalid snapshots-enabled value '//repo.example.com' in mvn-repositories entry at line 1. Expected true or false"
},
{
entries: ['private::true'],
error:
'Invalid mvn-repositories entry at line 1. repository-id, repository URL, and snapshots-enabled are required'
},
{
entries: ['private:https://repo.example.com:sometimes'],
error:
"Invalid snapshots-enabled value 'sometimes' in mvn-repositories entry at line 1. Expected true or false"
}
])('rejects malformed Maven repositories: $entries', ({entries, error}) => {
expect(() => auth.parseMavenRepositories(entries, true)).toThrow(error);
});
it('rejects duplicate Maven repository ids', () => {
expect(() =>
auth.parseMavenRepositories(
[
'private:https://first.example.com:false',
'private:https://second.example.com:true'
],
true
)
).toThrow("Duplicate repository-id 'private' in mvn-repositories input");
});
it('reserves the Central repository id only when automatic Central inclusion is enabled', () => {
const central = 'central:https://custom.example.com/maven:false';
expect(() => auth.parseMavenRepositories([central], true)).toThrow(
"Repository-id 'central' is reserved when mvn-repositories-include-central is enabled"
);
expect(auth.parseMavenRepositories([central], false)).toEqual([
{
id: 'central',
url: 'https://custom.example.com/maven',
snapshotsEnabled: false
}
]);
});
it('uses an explicit Central repository instead of adding a disabled override', () => {
const parsed = parseXmlObject(
auth.generate(
credentials('packages', 'USERNAME', 'PASSWORD'),
undefined,
repositorySettings(
auth.parseMavenRepositories(
['central:https://mirror.example.com/maven:true'],
false
),
false
)
)
) as any;
expect(parsed.settings.profiles.profile.repositories.repository).toEqual({
id: 'central',
url: 'https://mirror.example.com/maven',
snapshots: {enabled: 'true'}
});
});
it('reads Maven repository settings and Central controls', () => {
(core.getMultilineInput as jest.Mock).mockImplementation((name: string) =>
name === 'mvn-repositories'
? ['private:https://repo.example.com:true']
: []
);
(core.getInput as jest.Mock).mockImplementation((name: string) => {
const inputs: Record<string, string> = {
'mvn-repositories-include-central': 'false',
'mvn-repositories-prioritize-central': 'false'
};
return inputs[name] ?? '';
});
expect(auth.getMavenRepositorySettings()).toEqual({
repositories: [
{
id: 'private',
url: 'https://repo.example.com',
snapshotsEnabled: true
}
],
includeCentral: false,
prioritizeCentral: false
});
});
it('does not read repository controls when no repositories are configured', () => {
expect(auth.getMavenRepositorySettings()).toBeUndefined();
expect(core.getInput).not.toHaveBeenCalled();
});
it.each([
{
entries: ['releases:RELEASES_USERNAME'],
error:
'Invalid mvn-server-credentials entry at line 1. Expected format: server-id:USERNAME_ENV:PASSWORD_ENV'
},
{
entries: ['', 'releases:RELEASES_USERNAME:RELEASES_PASSWORD:EXTRA'],
error:
'Invalid mvn-server-credentials entry at line 2. Expected format: server-id:USERNAME_ENV:PASSWORD_ENV'
},
{
entries: ['releases::RELEASES_PASSWORD'],
error:
'Invalid mvn-server-credentials entry at line 1. server-id, username environment variable, and password environment variable are required'
}
])(
'rejects malformed Maven server credentials: $entries',
({entries, error}) => {
expect(() => auth.parseMavenServerCredentials(entries)).toThrow(error);
}
);
it('rejects duplicate Maven server ids', () => {
expect(() =>
auth.parseMavenServerCredentials([
'releases:RELEASES_USERNAME:RELEASES_PASSWORD',
'releases:OTHER_USERNAME:OTHER_PASSWORD'
])
).toThrow("Duplicate server-id 'releases' in mvn-server-credentials input");
});
it('uses multiline Maven server credentials instead of single-server inputs', () => {
(core.getMultilineInput as jest.Mock).mockReturnValue([
'releases:RELEASES_USERNAME:RELEASES_PASSWORD',
'snapshots:SNAPSHOTS_USERNAME:SNAPSHOTS_PASSWORD'
]);
expect(auth.getMavenServerSettings()).toEqual([
{
id: 'releases',
usernameEnvVar: 'RELEASES_USERNAME',
passwordEnvVar: 'RELEASES_PASSWORD'
},
{
id: 'snapshots',
usernameEnvVar: 'SNAPSHOTS_USERNAME',
passwordEnvVar: 'SNAPSHOTS_PASSWORD'
}
]);
expect(core.getInput).not.toHaveBeenCalled();
});
it('uses the existing single-server inputs when multiline credentials are absent', () => {
(core.getInput as jest.Mock).mockImplementation((name: string) =>
name === 'server-id' ? 'github' : ''
);
expect(auth.getMavenServerSettings()).toEqual([
{
id: 'github',
usernameEnvVar: 'GITHUB_ACTOR',
passwordEnvVar: 'GITHUB_TOKEN'
}
]);
});
it('preserves deprecated single-server aliases as fallback inputs', () => {
(core.getInput as jest.Mock).mockImplementation((name: string) => {
const inputs: Record<string, string> = {
'server-id': 'legacy',
'server-username': 'LEGACY_USERNAME',
'server-password': 'LEGACY_PASSWORD'
};
return inputs[name] ?? '';
});
expect(auth.getMavenServerSettings()).toEqual([
{
id: 'legacy',
usernameEnvVar: 'LEGACY_USERNAME',
passwordEnvVar: 'LEGACY_PASSWORD'
}
]);
expect(core.warning).toHaveBeenCalledTimes(2);
});
function xmlElementText(xml: string, tagName: string): string {
const match = new RegExp(`<${tagName}>([\\s\\S]*?)</${tagName}>`).exec(xml);
expect(match).not.toBeNull();
+52 -9
View File
@@ -11,6 +11,7 @@ import {
import {mkdtempSync} from 'fs';
import {tmpdir} from 'os';
import {join} from 'path';
import {createHash} from 'crypto';
import * as fs from 'fs';
import * as os from 'os';
@@ -67,7 +68,7 @@ jest.unstable_mockModule('@actions/glob', () => ({
const core = await import('@actions/core');
const cache = await import('@actions/cache');
const glob = await import('@actions/glob');
const {restore, save} = await import('../src/cache.js');
const {restore, save, validatePackageManager} = await import('../src/cache.js');
describe('dependency cache', () => {
const ORIGINAL_RUNNER_OS = process.env['RUNNER_OS'];
@@ -130,6 +131,20 @@ describe('dependency cache', () => {
jest.restoreAllMocks();
});
describe('validatePackageManager', () => {
it('accepts supported package managers', () => {
expect(() => validatePackageManager('maven')).not.toThrow();
expect(() => validatePackageManager('gradle')).not.toThrow();
expect(() => validatePackageManager('sbt')).not.toThrow();
});
it('throws the targeted error for unsupported package managers', () => {
expect(() => validatePackageManager('ant')).toThrow(
'unknown package manager specified: ant'
);
});
});
describe('restore', () => {
let spyCacheRestore: any;
let spyGlobHashFiles: any;
@@ -342,7 +357,7 @@ describe('dependency cache', () => {
await expect(restore('gradle', '')).rejects.toThrow(
`No file in ${projectRoot(
workspace
)} matched to [**/*.gradle*,**/gradle-wrapper.properties,buildSrc/**/Versions.kt,buildSrc/**/Dependencies.kt,gradle/*.versions.toml,**/versions.properties], make sure you have checked out the target repository`
)} matched to [**/*.gradle*,**/gradle.properties,**/gradle-wrapper.properties,buildSrc/**/Versions.kt,buildSrc/**/Dependencies.kt,gradle/*.versions.toml,**/versions.properties], make sure you have checked out the target repository`
);
});
it('downloads cache based on build.gradle', async () => {
@@ -351,7 +366,7 @@ describe('dependency cache', () => {
await restore('gradle', '');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyGlobHashFiles).toHaveBeenCalledWith(
'**/*.gradle*\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
'**/*.gradle*\n**/gradle.properties\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
);
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
@@ -362,7 +377,7 @@ describe('dependency cache', () => {
await restore('gradle', '');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyGlobHashFiles).toHaveBeenCalledWith(
'**/*.gradle*\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
'**/*.gradle*\n**/gradle.properties\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
);
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
@@ -374,7 +389,7 @@ describe('dependency cache', () => {
await restore('gradle', '');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyGlobHashFiles).toHaveBeenCalledWith(
'**/*.gradle*\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
'**/*.gradle*\n**/gradle.properties\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
);
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
@@ -386,11 +401,39 @@ describe('dependency cache', () => {
await restore('gradle', '');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyGlobHashFiles).toHaveBeenCalledWith(
'**/*.gradle*\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
'**/*.gradle*\n**/gradle.properties\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
);
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
});
it('changes the cache key when gradle.properties changes', async () => {
const buildFile = join(workspace, 'build.gradle');
const propertiesFile = join(workspace, 'gradle.properties');
createFile(buildFile);
createFile(propertiesFile, 'dependencyVersion=1.0.0');
spyGlobHashFiles.mockImplementation(async (pattern: string) => {
if (pattern === '**/gradle-wrapper.properties') {
return '';
}
const files = [buildFile];
if (pattern.split('\n').includes('**/gradle.properties')) {
files.push(propertiesFile);
}
const hash = createHash('sha256');
files.forEach(file => hash.update(fs.readFileSync(file)));
return hash.digest('hex');
});
await restore('gradle', '');
const firstKey = spyCacheRestore.mock.calls[0][1];
fs.writeFileSync(propertiesFile, 'dependencyVersion=2.0.0');
await restore('gradle', '');
const secondKey = spyCacheRestore.mock.calls[1][1];
expect(secondKey).not.toBe(firstKey);
});
it('restores the gradle wrapper distribution cache independently of the main cache', async () => {
createFile(join(workspace, 'build.gradle'));
@@ -529,7 +572,7 @@ describe('dependency cache', () => {
await restore('gradle', '');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyGlobHashFiles).toHaveBeenCalledWith(
'**/*.gradle*\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
'**/*.gradle*\n**/gradle.properties\n**/gradle-wrapper.properties\nbuildSrc/**/Versions.kt\nbuildSrc/**/Dependencies.kt\ngradle/*.versions.toml\n**/versions.properties'
);
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
@@ -1027,9 +1070,9 @@ function createStateForSuccessfulRestore() {
});
}
function createFile(path: string) {
function createFile(path: string, contents = '') {
core.info(`created a file at ${path}`);
fs.writeFileSync(path, '');
fs.writeFileSync(path, contents);
}
function deferred<T>() {
+210 -1
View File
@@ -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,11 @@ 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 constants = await import('../src/constants.js');
const {GPG_HOME_PREFIX} = await import('../src/gpg.js');
const {registerJdk, buildJdkCacheKey} = await import('../src/jdk-cache.js');
const jdkTempRoots: string[] = [];
describe('cleanup', () => {
let spyWarning: any;
@@ -88,6 +96,9 @@ describe('cleanup', () => {
});
afterEach(() => {
while (jdkTempRoots.length) {
fs.rmSync(jdkTempRoots.pop()!, {recursive: true, force: true});
}
resetState();
jest.resetAllMocks();
jest.clearAllMocks();
@@ -105,11 +116,65 @@ describe('cleanup', () => {
(core.getInput as jest.Mock<any>).mockImplementation((name: string) => {
return name === 'cache' ? 'gradle' : '';
});
await cleanup();
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
});
it('removes the isolated GPG home without touching unrelated key material', async () => {
const tempDir = util.getTempDir();
fs.mkdirSync(tempDir, {recursive: true});
const gpgHome = fs.mkdtempSync(path.join(tempDir, GPG_HOME_PREFIX));
const unrelatedGpgHome = fs.mkdtempSync(
path.join(tempDir, 'user-gpg-home-')
);
fs.writeFileSync(
path.join(unrelatedGpgHome, 'private.key'),
'pre-existing'
);
(core.getInput as jest.Mock<any>).mockReturnValue('');
(core.getState as jest.Mock<any>).mockImplementation((name: string) =>
name === constants.STATE_GPG_HOME ? gpgHome : ''
);
await cleanup();
expect(fs.existsSync(gpgHome)).toBe(false);
expect(
fs.readFileSync(path.join(unrelatedGpgHome, 'private.key'), 'utf8')
).toBe('pre-existing');
fs.rmSync(unrelatedGpgHome, {recursive: true, force: true});
});
it('makes repeated cleanup of the same GPG home idempotent', async () => {
const tempDir = util.getTempDir();
fs.mkdirSync(tempDir, {recursive: true});
const gpgHome = fs.mkdtempSync(path.join(tempDir, GPG_HOME_PREFIX));
(core.getInput as jest.Mock<any>).mockReturnValue('');
(core.getState as jest.Mock<any>).mockImplementation((name: string) =>
name === constants.STATE_GPG_HOME ? gpgHome : ''
);
await cleanup();
await cleanup();
expect(fs.existsSync(gpgHome)).toBe(false);
expect(core.setFailed).not.toHaveBeenCalled();
});
it('skips GPG cleanup when no home was persisted', async () => {
(core.getInput as jest.Mock<any>).mockReturnValue('');
(core.getState as jest.Mock<any>).mockReturnValue('');
await cleanup();
expect(spyInfo).not.toHaveBeenCalledWith(
'Removing private key from isolated GPG home'
);
expect(core.setFailed).not.toHaveBeenCalled();
});
it('does not fail even though the save process throws error', async () => {
spyCacheSave.mockImplementation((paths: string[], key: string) =>
Promise.reject(new Error('Unexpected error'))
@@ -139,7 +204,8 @@ describe('cleanup', () => {
await cleanup();
expect(spyCacheSave).not.toHaveBeenCalled();
expect(core.getState).not.toHaveBeenCalled();
expect(core.getState).toHaveBeenCalledTimes(1);
expect(core.getState).toHaveBeenCalledWith(constants.STATE_GPG_HOME);
expect(spyInfo).toHaveBeenCalledWith(
'Cache saving is skipped because cache-read-only is enabled.'
);
@@ -163,6 +229,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 +362,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')
};
}
@@ -0,0 +1,11 @@
{
"result": [
{
"filename": "java-21-openjdk-21.0.8.0.9-1.portable.jdk.x86_64.tar.xz",
"direct_download_uri": "https://developers.redhat.com/content-gateway/file/pub/openjdk/java-21-openjdk-21.0.8.0.9-1.portable.jdk.x86_64.tar.xz",
"checksum": "91a6f3284cbded9de17f65985a4fca48dd4fd0aa295162178631c23ade335aad",
"checksum_type": "sha256"
}
],
"message": ""
}
+71
View File
@@ -0,0 +1,71 @@
{
"result": [
{
"id": "redhat-21.0.8-jdk-linux-x64",
"archive_type": "tar.xz",
"distribution": "redhat",
"java_version": "21.0.8+9",
"release_status": "ga",
"operating_system": "linux",
"architecture": "x64",
"package_type": "jdk",
"directly_downloadable": true
},
{
"id": "redhat-21.0.7-jdk-linux-x64",
"archive_type": "tar.xz",
"distribution": "redhat",
"java_version": "21.0.7+6",
"release_status": "ga",
"operating_system": "linux",
"architecture": "x64",
"package_type": "jdk",
"directly_downloadable": true
},
{
"id": "redhat-17.0.16-jdk-linux-x64",
"archive_type": "tar.xz",
"distribution": "redhat",
"java_version": "17.0.16+8",
"release_status": "ga",
"operating_system": "linux",
"architecture": "x64",
"package_type": "jdk",
"directly_downloadable": true
},
{
"id": "redhat-9-jdk-linux-x64",
"archive_type": "tar.xz",
"distribution": "redhat",
"java_version": "9+181",
"release_status": "ga",
"operating_system": "linux",
"architecture": "x64",
"package_type": "jdk",
"directly_downloadable": true
},
{
"id": "redhat-21.0.8-jre-linux-x64",
"archive_type": "tar.xz",
"distribution": "redhat",
"java_version": "21.0.8+9",
"release_status": "ga",
"operating_system": "linux",
"architecture": "x64",
"package_type": "jre",
"directly_downloadable": true
},
{
"id": "redhat-17.0.16-jdk-windows-x64",
"archive_type": "zip",
"distribution": "redhat",
"java_version": "17.0.16+8",
"release_status": "ga",
"operating_system": "windows",
"architecture": "x64",
"package_type": "jdk",
"directly_downloadable": true
}
],
"message": "6 package(s) found"
}
@@ -0,0 +1,73 @@
{
"25": {
"lts": "false",
"updates": {
"25.0.2": {
"sapmachine-25.0.2": {
"release_url": "https://example.test/releases/25.0.2",
"ea": false,
"assets": {
"jdk": {
"linux-x64": {
"tar.gz": {
"name": "sapmachine-jdk-25.0.2_linux-x64_bin.tar.gz",
"checksum": "stable-boolean",
"url": "https://example.test/sapmachine-25.0.2-ga.tar.gz"
}
}
}
}
}
},
"25.0.1": {
"sapmachine-25.0.1": {
"release_url": "https://example.test/releases/25.0.1",
"ea": "false",
"assets": {
"jdk": {
"linux-x64": {
"tar.gz": {
"name": "sapmachine-jdk-25.0.1_linux-x64_bin.tar.gz",
"checksum": "stable-string",
"url": "https://example.test/sapmachine-25.0.1-ga.tar.gz"
}
}
}
}
}
},
"25": {
"sapmachine-25+11": {
"release_url": "https://example.test/releases/25+11",
"ea": true,
"assets": {
"jdk": {
"linux-x64": {
"tar.gz": {
"name": "sapmachine-jdk-25-ea.11_linux-x64_bin.tar.gz",
"checksum": "ea-boolean",
"url": "https://example.test/sapmachine-25-ea.11.tar.gz"
}
}
}
}
},
"sapmachine-25+10": {
"release_url": "https://example.test/releases/25+10",
"ea": "true",
"assets": {
"jdk": {
"linux-x64": {
"tar.gz": {
"name": "sapmachine-jdk-25-ea.10_linux-x64_bin.tar.gz",
"checksum": "ea-string",
"url": "https://example.test/sapmachine-25-ea.10.tar.gz"
}
}
}
}
}
}
}
}
}
+610 -1
View File
@@ -70,6 +70,19 @@ 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()
}));
jest.unstable_mockModule('../../src/jdk-resolution-cache.js', () => ({
registerJdkResolution: jest.fn(),
restoreJdkResolution: jest.fn()
}));
const real_util_module = await import('../../src/util.js');
jest.unstable_mockModule('../../src/util.js', () => ({
...real_util_module,
@@ -86,6 +99,10 @@ 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 jdkResolutionCache = await import('../../src/jdk-resolution-cache.js');
const {getJavaPlatformIdentity} =
await import('../../src/distributions/platform-types.js');
const {JavaBase} = await import('../../src/distributions/base-installer.js');
class EmptyJavaBase extends JavaBase {
@@ -133,6 +150,47 @@ class EmptyJavaBase extends JavaBase {
}
}
class FloatingJavaBase extends JavaBase {
static actualVersion = '21.0.8+9';
static checksum: string | undefined = 'artifact-one';
static fingerprint: string | undefined = undefined;
constructor(installerOptions: JavaInstallerOptions) {
super('Floating', installerOptions);
}
protected async downloadTool(): Promise<JavaInstallerResults> {
return {
version: FloatingJavaBase.actualVersion,
path: path.join(
'toolcache',
this.toolcacheFolderName,
FloatingJavaBase.actualVersion.replace('+', '-'),
this.architecture
)
};
}
protected async findPackageForDownload(): Promise<JavaDownloadRelease> {
return {
version: '21',
url: 'https://example.com/java/21/latest/jdk-21.tar.gz',
checksum: FloatingJavaBase.checksum
? {
algorithm: 'sha256',
value: FloatingJavaBase.checksum
}
: undefined,
floating: true,
fingerprint: FloatingJavaBase.fingerprint
};
}
protected requiresRemoteResolution(): boolean {
return true;
}
}
describe('findInToolcache', () => {
const actualJavaVersion = '11.0.8';
const javaPath = path.join('Java_Empty_jdk', actualJavaVersion, 'x64');
@@ -336,6 +394,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) => {
@@ -378,6 +440,7 @@ describe('setupJava', () => {
spyCoreError.mockImplementation(() => undefined);
jest.spyOn(os, 'arch').mockReturnValue('x86' as ReturnType<typeof os.arch>);
FloatingJavaBase.fingerprint = undefined;
});
afterEach(() => {
@@ -457,14 +520,289 @@ describe('setupJava', () => {
);
});
describe('floating tool-cache reuse', () => {
let toolCacheRoot: string;
const installVersion = (toolcacheVersion: string): string => {
const architecturePath = path.join(
toolCacheRoot,
'Java_Floating_jdk',
toolcacheVersion,
'x64'
);
fs.mkdirSync(architecturePath, {recursive: true});
fs.writeFileSync(`${architecturePath}.complete`, '');
return architecturePath;
};
beforeEach(() => {
toolCacheRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-java-tc-'));
process.env['RUNNER_TOOL_CACHE'] = toolCacheRoot;
FloatingJavaBase.actualVersion = '21.0.8+9';
FloatingJavaBase.checksum = 'artifact-one';
(jdkCache.restoreJdk as jest.Mock).mockResolvedValue(false);
spyTcFindAllVersions.mockReturnValue([]);
});
afterEach(() => {
fs.rmSync(toolCacheRoot, {recursive: true, force: true});
delete process.env['RUNNER_TOOL_CACHE'];
});
const createDistribution = (forceDownload = false) =>
new FloatingJavaBase({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true,
forceDownload
});
it('reuses a tool-cache installation once the resolution cache identifies the floating version', async () => {
const installedPath = installVersion('21.0.8-9');
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue({
release: {version: '21.0.8+9'}
});
const distribution = createDistribution();
const downloadTool = jest.spyOn(distribution as any, 'downloadTool');
await expect(distribution.setupJava()).resolves.toEqual({
version: '21.0.8+9',
path: installedPath
});
// The artifact behind the mutable URL is already installed, so neither a
// download nor a cache round-trip is needed.
expect(downloadTool).not.toHaveBeenCalled();
expect(jdkCache.restoreJdk).not.toHaveBeenCalled();
});
it('ignores a tool-cache installation of a version the resolution cache did not vouch for', async () => {
installVersion('21.0.7-6');
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue({
release: {version: '21.0.8+9'}
});
const distribution = createDistribution();
const downloadTool = jest.spyOn(distribution as any, 'downloadTool');
await distribution.setupJava();
expect(downloadTool).toHaveBeenCalled();
});
it('never reuses the tool-cache for a floating artifact the resolution cache cannot identify', async () => {
installVersion('21.0.8-9');
spyTcFindAllVersions.mockReturnValue(['21.0.8-9']);
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue(
undefined
);
const distribution = createDistribution();
const downloadTool = jest.spyOn(distribution as any, 'downloadTool');
await distribution.setupJava();
// Nothing ties the installed bytes to what the URL serves right now.
expect(downloadTool).toHaveBeenCalled();
});
it('still downloads a resolution-cache-identified version when force-download is set', async () => {
installVersion('21.0.8-9');
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue({
release: {version: '21.0.8+9'}
});
const distribution = createDistribution(true);
const downloadTool = jest.spyOn(distribution as any, 'downloadTool');
await distribution.setupJava();
expect(downloadTool).toHaveBeenCalled();
});
});
it('uses the concrete versions of two different floating artifacts under the same major', async () => {
spyTcFindAllVersions.mockReturnValue(['21.0.8-9']);
spyGetToolcachePath.mockImplementation(
(_toolname: string, version: string, architecture: string) =>
path.join('toolcache', 'Java_Floating_jdk', version, architecture)
);
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue(
undefined
);
(jdkCache.restoreJdk as jest.Mock).mockResolvedValue(false);
FloatingJavaBase.actualVersion = '21.0.8+9';
FloatingJavaBase.checksum = 'artifact-one';
const first = new FloatingJavaBase({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true
});
await expect(first.setupJava()).resolves.toEqual({
version: '21.0.8+9',
path: path.join('toolcache', 'Java_Floating_jdk', '21.0.8-9', 'x64')
});
FloatingJavaBase.actualVersion = '21.0.9+7';
FloatingJavaBase.checksum = 'artifact-two';
const second = new FloatingJavaBase({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true
});
await expect(second.setupJava()).resolves.toEqual({
version: '21.0.9+7',
path: path.join('toolcache', 'Java_Floating_jdk', '21.0.9-7', 'x64')
});
expect(spyCoreSetOutput).toHaveBeenNthCalledWith(3, 'version', '21.0.8+9');
expect(spyCoreSetOutput).toHaveBeenNthCalledWith(6, 'version', '21.0.9+7');
expect(jdkCache.registerJdk).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
version: '21.0.8+9',
source: 'sha256:artifact-one'
})
);
expect(jdkCache.registerJdk).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
version: '21.0.9+7',
source: 'sha256:artifact-two'
})
);
expect(jdkResolutionCache.registerJdkResolution).toHaveBeenNthCalledWith(
2,
expect.objectContaining({source: 'sha256:artifact-two'}),
expect.objectContaining({version: '21.0.9+7', floating: true})
);
});
it('does not trust a matching tool-cache version for a floating artifact', async () => {
spyTcFindAllVersions.mockReturnValue(['21.0.8-9']);
spyGetToolcachePath.mockReturnValue(
path.join('toolcache', 'Java_Floating_jdk', '21.0.8-9', 'x64')
);
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue({
release: {
version: '21.0.8+9',
url: 'https://example.com/java/21/latest/jdk-21.tar.gz',
checksum: {algorithm: 'sha256', value: 'artifact-republished'},
floating: true
},
fresh: true
});
(jdkCache.restoreJdk as jest.Mock).mockResolvedValue(false);
FloatingJavaBase.actualVersion = '21.0.8+9';
FloatingJavaBase.checksum = 'artifact-republished';
const distribution = new FloatingJavaBase({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true
});
const downloadTool = jest.spyOn(distribution as any, 'downloadTool');
await distribution.setupJava();
expect(jdkCache.restoreJdk).toHaveBeenCalled();
expect(downloadTool).toHaveBeenCalled();
});
it('does not cache a floating artifact with no way to identify its bytes', async () => {
spyTcFindAllVersions.mockReturnValue(['21.0.8-9']);
spyGetToolcachePath.mockReturnValue(
path.join('toolcache', 'Java_Floating_jdk', '21.0.8-9', 'x64')
);
FloatingJavaBase.actualVersion = '21.0.8+9';
FloatingJavaBase.checksum = undefined;
FloatingJavaBase.fingerprint = undefined;
const distribution = new FloatingJavaBase({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true
});
await distribution.setupJava();
expect(jdkResolutionCache.restoreJdkResolution).not.toHaveBeenCalled();
expect(jdkResolutionCache.registerJdkResolution).not.toHaveBeenCalled();
expect(jdkCache.restoreJdk).not.toHaveBeenCalled();
expect(jdkCache.registerJdk).not.toHaveBeenCalled();
});
it('caches a checksum-less floating artifact identified by its response fingerprint', async () => {
spyTcFindAllVersions.mockReturnValue([]);
spyGetToolcachePath.mockReturnValue(
path.join('toolcache', 'Java_Floating_jdk', '21.0.8-9', 'x64')
);
FloatingJavaBase.actualVersion = '21.0.8+9';
FloatingJavaBase.checksum = undefined;
FloatingJavaBase.fingerprint = 'etag:"artifact-one"';
const distribution = new FloatingJavaBase({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true
});
await distribution.setupJava();
// The fingerprint changes when the vendor republishes, so it is a safe
// identity even though no checksum is available.
expect(jdkResolutionCache.registerJdkResolution).toHaveBeenCalledWith(
expect.objectContaining({source: 'etag:"artifact-one"'}),
expect.objectContaining({version: '21.0.8+9'})
);
expect(jdkCache.registerJdk).toHaveBeenCalledWith(
expect.objectContaining({source: 'etag:"artifact-one"'})
);
});
it('separates the cache identities of two builds served by the same floating URL', async () => {
const sources: string[] = [];
(jdkCache.registerJdk as jest.Mock).mockImplementation((entry: any) => {
sources.push(entry.source);
});
spyTcFindAllVersions.mockReturnValue([]);
spyGetToolcachePath.mockReturnValue(
path.join('toolcache', 'Java_Floating_jdk', '21.0.8-9', 'x64')
);
FloatingJavaBase.actualVersion = '21.0.8+9';
FloatingJavaBase.checksum = undefined;
for (const fingerprint of ['etag:"before"', 'etag:"after"']) {
FloatingJavaBase.fingerprint = fingerprint;
await new FloatingJavaBase({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true
}).setupJava();
}
expect(sources).toEqual(['etag:"before"', 'etag:"after"']);
});
it('should download java when force-download is enabled, even if the version is cached', async () => {
mockJavaBase = new EmptyJavaBase({
version: actualJavaVersion,
architecture: 'x86',
packageType: 'jdk',
checkLatest: false,
forceDownload: true
forceDownload: true,
cacheJdk: true
});
const findInToolcache = jest.fn(() => ({
version: actualJavaVersion,
path: javaPathInstalled
@@ -484,6 +822,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([
@@ -829,6 +1272,172 @@ describe('setupJava', () => {
'Installing Java 11.0.9 (not setting as default)'
);
});
describe('resolution cache', () => {
// 11.0.9 is not in the mocked tool-cache, so the tool-cache short-circuit
// misses and the release has to be resolved, exactly as it does for every
// distribution that is not preinstalled on hosted runners.
const options: JavaInstallerOptions = {
version: '11.0.9',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false,
cacheJdk: true
};
const cachedRelease = {
version: '11.0.9',
url: 'https://example.com/java/11.0.9'
};
const expectedRequest = {
distribution: 'Empty',
packageType: 'jdk',
platform: getJavaPlatformIdentity(),
architecture: 'x86',
versionSpec: '11.0.9',
stable: true
};
beforeEach(() => {
(jdkCache.restoreJdk as jest.Mock).mockResolvedValue(false);
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue(
undefined
);
});
it('skips the metadata API on a fresh cached resolution', async () => {
mockJavaBase = new EmptyJavaBase(options);
const findPackageForDownload = jest.spyOn(
mockJavaBase as any,
'findPackageForDownload'
);
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue({
release: cachedRelease,
fresh: true
});
await mockJavaBase.setupJava();
expect(jdkResolutionCache.restoreJdkResolution).toHaveBeenCalledWith(
expectedRequest
);
expect(findPackageForDownload).not.toHaveBeenCalled();
expect(jdkResolutionCache.registerJdkResolution).not.toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith(
'Resolved Empty 11.0.9 from the resolution cache'
);
});
it('re-resolves and records the release on a miss', async () => {
mockJavaBase = new EmptyJavaBase(options);
await mockJavaBase.setupJava();
expect(jdkResolutionCache.registerJdkResolution).toHaveBeenCalledWith(
expectedRequest,
{version: '11.0.9', url: 'some/random_url/java/11.0.9'}
);
});
it('re-resolves when the cached resolution is stale', async () => {
mockJavaBase = new EmptyJavaBase(options);
const findPackageForDownload = jest.spyOn(
mockJavaBase as any,
'findPackageForDownload'
);
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue({
release: cachedRelease,
fresh: false
});
await mockJavaBase.setupJava();
expect(findPackageForDownload).toHaveBeenCalled();
expect(jdkResolutionCache.registerJdkResolution).toHaveBeenCalled();
});
it('falls back to a stale resolution when the metadata API fails', async () => {
mockJavaBase = new EmptyJavaBase(options);
const downloadTool = jest
.spyOn(mockJavaBase as any, 'downloadTool')
.mockResolvedValue({version: '11.0.9', path: javaPathInstalled});
jest
.spyOn(mockJavaBase as any, 'findPackageForDownload')
.mockRejectedValue(new Error('503 Service Unavailable'));
(jdkResolutionCache.restoreJdkResolution as jest.Mock).mockResolvedValue({
release: cachedRelease,
fresh: false
});
await expect(mockJavaBase.setupJava()).resolves.toEqual({
version: '11.0.9',
path: javaPathInstalled
});
expect(downloadTool).toHaveBeenCalledWith(cachedRelease);
expect(jdkResolutionCache.registerJdkResolution).not.toHaveBeenCalled();
expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining('falling back to the cached resolution')
);
});
it('fails when the metadata API fails and nothing was cached', async () => {
mockJavaBase = new EmptyJavaBase(options);
jest
.spyOn(mockJavaBase as any, 'findPackageForDownload')
.mockRejectedValue(new Error('503 Service Unavailable'));
await expect(mockJavaBase.setupJava()).rejects.toThrow(
'503 Service Unavailable'
);
});
it('records the concrete version for a checksum-bound floating release', async () => {
mockJavaBase = new EmptyJavaBase(options);
jest
.spyOn(mockJavaBase as any, 'findPackageForDownload')
.mockResolvedValue({
version: '11.0.9',
url: 'https://example.com/java/11/latest/jdk-11.tar.gz',
checksum: {algorithm: 'sha256', value: 'abc'},
floating: true
});
await mockJavaBase.setupJava();
expect(jdkResolutionCache.registerJdkResolution).toHaveBeenCalledWith(
{
distribution: 'Empty',
packageType: 'jdk',
platform: getJavaPlatformIdentity(),
architecture: 'x86',
versionSpec: '11.0.9',
stable: true,
source: 'sha256:abc'
},
{
version: '11.0.9',
url: 'https://example.com/java/11/latest/jdk-11.tar.gz',
checksum: {algorithm: 'sha256', value: 'abc'},
floating: true
}
);
});
it.each([
['cache-jdk is disabled', {cacheJdk: false}],
['check-latest is enabled', {checkLatest: true}],
['force-download is enabled', {forceDownload: true}],
['java-version is "latest"', {version: 'latest'}]
])('is bypassed when %s', async (_name, overrides) => {
mockJavaBase = new EmptyJavaBase({...options, ...overrides});
await mockJavaBase.setupJava();
expect(jdkResolutionCache.restoreJdkResolution).not.toHaveBeenCalled();
expect(jdkResolutionCache.registerJdkResolution).not.toHaveBeenCalled();
});
});
});
describe('downloadAndVerify', () => {
@@ -8,6 +8,7 @@ import {
beforeAll,
afterAll
} from '@jest/globals';
import fs from 'fs';
import type {JavaInstallerOptions} from '../../src/distributions/base-models.js';
import {HttpClient} from '@actions/http-client';
@@ -323,3 +324,50 @@ describe('getAvailableVersions', () => {
spyGetDownloadArchiveExtension.mockReturnValue(mockedExtension);
};
});
describe('Corretto getPlatformOption libc selection', () => {
const originalPlatform = Object.getOwnPropertyDescriptor(
process,
'platform'
) as PropertyDescriptor;
const setPlatform = (platform: NodeJS.Platform) =>
Object.defineProperty(process, 'platform', {
...originalPlatform,
value: platform
});
const distribution = new CorrettoDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
afterEach(() => {
Object.defineProperty(process, 'platform', originalPlatform);
jest.restoreAllMocks();
});
it('selects the musl artifacts on Alpine', () => {
setPlatform('linux');
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(distribution['getPlatformOption']()).toBe('alpine');
});
it('selects the glibc artifacts on other Linux runners', () => {
setPlatform('linux');
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(distribution['getPlatformOption']()).toBe('linux');
});
it('does not probe for Alpine off Linux', () => {
setPlatform('darwin');
const existsSync = jest.spyOn(fs, 'existsSync');
expect(distribution['getPlatformOption']()).toBe('macos');
expect(existsSync).not.toHaveBeenCalled();
});
});
@@ -8,6 +8,7 @@ import {
beforeAll,
afterAll
} from '@jest/globals';
import fs from 'fs';
import {HttpClient} from '@actions/http-client';
import manifestData from '../data/dragonwell.json' with {type: 'json'};
@@ -307,3 +308,50 @@ describe('getAvailableVersions', () => {
});
});
});
describe('Dragonwell getPlatformOption libc selection', () => {
const originalPlatform = Object.getOwnPropertyDescriptor(
process,
'platform'
) as PropertyDescriptor;
const setPlatform = (platform: NodeJS.Platform) =>
Object.defineProperty(process, 'platform', {
...originalPlatform,
value: platform
});
const distribution = new DragonwellDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
afterEach(() => {
Object.defineProperty(process, 'platform', originalPlatform);
jest.restoreAllMocks();
});
it('selects the musl artifacts on Alpine', () => {
setPlatform('linux');
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(distribution['getPlatformOption']()).toBe('alpine-linux');
});
it('selects the glibc artifacts on other Linux runners', () => {
setPlatform('linux');
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(distribution['getPlatformOption']()).toBe('linux');
});
it('does not probe for Alpine off Linux', () => {
setPlatform('win32');
const existsSync = jest.spyOn(fs, 'existsSync');
expect(distribution['getPlatformOption']()).toBe('windows');
expect(existsSync).not.toHaveBeenCalled();
});
});
@@ -72,6 +72,7 @@ jest.unstable_mockModule('../../src/util.js', () => ({
...realUtil,
extractJdkFile: jest.fn(),
getDownloadArchiveExtension: jest.fn(),
getJavaVersionFromReleaseFile: jest.fn(),
renameWinArchive: jest.fn(),
getGitHubHttpHeaders: jest.fn().mockReturnValue({Accept: 'application/json'})
}));
@@ -363,6 +364,30 @@ describe('GraalVMDistribution', () => {
path: '/cached/java/path'
});
});
it('caches Oracle GraalVM floating artifacts under their installed version', async () => {
(util.getJavaVersionFromReleaseFile as jest.Mock<any>).mockReturnValue(
'21.0.9+7'
);
const floatingRelease = {
version: '21',
url: 'https://example.com/graalvm/latest/graalvm-jdk-21.tar.gz',
floating: true
};
const result = await (distribution as any).downloadTool(floatingRelease);
expect(tc.cacheDir).toHaveBeenCalledWith(
path.join('/tmp/extracted', 'graalvm-jdk-17.0.5'),
'Java_GraalVM_jdk',
'21.0.9+7',
'x64'
);
expect(result).toEqual({
version: '21.0.9+7',
path: '/cached/java/path'
});
});
});
describe('findPackageForDownload', () => {
@@ -421,7 +446,8 @@ describe('GraalVMDistribution', () => {
value: 'a'.repeat(64),
source:
'https://download.oracle.com/graalvm/17/archive/graalvm-jdk-17.0.5_linux-x64_bin.tar.gz.sha256'
}
},
floating: false
});
expect(mockHttpClient.head).toHaveBeenCalledWith(result.url);
expect(mockHttpClient.get).toHaveBeenCalledWith(`${result.url}.sha256`);
@@ -443,10 +469,40 @@ describe('GraalVMDistribution', () => {
value: 'a'.repeat(64),
source:
'https://download.oracle.com/graalvm/21/latest/graalvm-jdk-21_linux-x64_bin.tar.gz.sha256'
}
},
// A major-only range resolves to the floating `/latest/` URL, so the
// release must not be reused by a later job.
floating: true
});
});
it.each([
['21', 'etag:"graalvm-latest"'],
['17.0.5', undefined]
])(
'fingerprints only the floating artifact for version %s',
async (input, expected) => {
mockHttpClient.head.mockResolvedValue({
message: {statusCode: 200, headers: {etag: '"graalvm-latest"'}}
} as any);
const result = await (distribution as any).findPackageForDownload(
input
);
// Without a fingerprint the constant `/latest/` URL would key a cache
// entry that never invalidates when Oracle republishes the artifact.
expect(result.fingerprint).toBe(expected);
}
);
it('always resolves Oracle GraalVM major-only requests remotely', () => {
expect((distribution as any).requiresRemoteResolution()).toBe(true);
expect((communityDistribution as any).requiresRemoteResolution()).toBe(
false
);
});
it('should throw error for unsupported architecture', async () => {
distribution = new GraalVMDistribution({
...defaultOptions,
@@ -492,7 +548,8 @@ describe('GraalVMDistribution', () => {
value: 'a'.repeat(64),
source:
'https://download.oracle.com/graalvm/25/latest/graalvm-jdk-25_linux-x64_bin.tar.gz.sha256'
}
},
floating: true
});
});
@@ -47,6 +47,24 @@ const core = await import('@actions/core');
const {JetBrainsDistribution} =
await import('../../src/distributions/jetbrains/installer.js');
const {RetryingHttpClient} = await import('../../src/retrying-http-client.js');
const {MAX_PAGINATION_PAGES} = await import('../../src/util.js');
const JETBRAINS_RELEASES_URL =
'https://api.github.com/repos/JetBrains/JetBrainsRuntime/releases?per_page=100';
function release(tagName: string, prerelease: boolean) {
return {
tag_name: tagName,
name: tagName,
prerelease
};
}
function nextPageHeader(page: number) {
return {
link: `<${JETBRAINS_RELEASES_URL}&page=${page}>; rel="next"`
};
}
function response(
statusCode: number,
@@ -62,8 +80,11 @@ function response(
describe('getAvailableVersions', () => {
let spyHttpClient: any;
let spyCoreError: any;
const originalGitHubToken = process.env.GITHUB_TOKEN;
beforeEach(() => {
delete process.env.GITHUB_TOKEN;
(core.getInput as jest.Mock).mockReturnValue('');
spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
spyHttpClient.mockReturnValue({
statusCode: 200,
@@ -77,6 +98,11 @@ describe('getAvailableVersions', () => {
});
afterEach(() => {
if (originalGitHubToken === undefined) {
delete process.env.GITHUB_TOKEN;
} else {
process.env.GITHUB_TOKEN = originalGitHubToken;
}
jest.resetAllMocks();
jest.clearAllMocks();
jest.restoreAllMocks();
@@ -110,6 +136,224 @@ describe('getAvailableVersions', () => {
expect(availableVersions.length).toBe(length);
}, 10_000);
it('continues a stable request after an all-prerelease page', async () => {
jest.spyOn(HttpClient.prototype, 'head').mockResolvedValue({
message: {statusCode: 200}
} as any);
spyHttpClient
.mockResolvedValueOnce({
statusCode: 200,
headers: nextPageHeader(2),
result: [release('jbr-release-26.0.0b1.1', true)]
})
.mockResolvedValueOnce({
statusCode: 200,
headers: {},
result: [release('jbr-release-21.0.11b1163.116', false)]
});
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions.map(version => version.tag_name)).toContain(
'jbr-release-21.0.11b1163.116'
);
expect(availableVersions.map(version => version.tag_name)).not.toContain(
'jbr-release-26.0.0b1.1'
);
expect(spyHttpClient).toHaveBeenCalledTimes(2);
});
it('continues an EA request after an all-stable page', async () => {
jest.spyOn(HttpClient.prototype, 'head').mockResolvedValue({
message: {statusCode: 200}
} as any);
spyHttpClient
.mockResolvedValueOnce({
statusCode: 200,
headers: nextPageHeader(2),
result: [release('jbr-release-21.0.11b1163.116', false)]
})
.mockResolvedValueOnce({
statusCode: 200,
headers: {},
result: [release('jbr-release-26.0.0b1.1', true)]
});
const distribution = new JetBrainsDistribution({
version: '26-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions.map(version => version.tag_name)).toEqual([
'jbr-release-26.0.0b1.1'
]);
expect(spyHttpClient).toHaveBeenCalledTimes(2);
});
it('uses the token input for every paginated GitHub Releases request', async () => {
(core.getInput as jest.Mock).mockReturnValue('input-token');
spyHttpClient
.mockResolvedValueOnce({
statusCode: 200,
headers: nextPageHeader(2),
result: [release('jbr-release-21.0.11b1163.116', false)]
})
.mockResolvedValueOnce({
statusCode: 200,
headers: {},
result: [release('jbr-release-21.0.10b1087.6', false)]
});
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
await distribution['getAvailableVersions']();
expect(spyHttpClient).toHaveBeenNthCalledWith(1, JETBRAINS_RELEASES_URL, {
Accept: 'application/vnd.github+json',
Authorization: 'Bearer input-token'
});
expect(spyHttpClient).toHaveBeenNthCalledWith(
2,
`${JETBRAINS_RELEASES_URL}&page=2`,
{
Accept: 'application/vnd.github+json',
Authorization: 'Bearer input-token'
}
);
});
it('prefers the token input over the environment fallback', async () => {
(core.getInput as jest.Mock).mockReturnValue('input-token');
process.env.GITHUB_TOKEN = 'environment-token';
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
await distribution['getAvailableVersions']();
expect(spyHttpClient).toHaveBeenCalledWith(JETBRAINS_RELEASES_URL, {
Accept: 'application/vnd.github+json',
Authorization: 'Bearer input-token'
});
});
it('falls back to GITHUB_TOKEN when the token input is empty', async () => {
process.env.GITHUB_TOKEN = 'environment-token';
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
await distribution['getAvailableVersions']();
expect(spyHttpClient).toHaveBeenCalledWith(JETBRAINS_RELEASES_URL, {
Accept: 'application/vnd.github+json',
Authorization: 'Bearer environment-token'
});
});
it('omits authorization when no GitHub token is available', async () => {
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
await distribution['getAvailableVersions']();
expect(spyHttpClient).toHaveBeenCalledWith(JETBRAINS_RELEASES_URL, {
Accept: 'application/vnd.github+json'
});
});
it('stops pagination when a raw GitHub page is empty', async () => {
spyHttpClient
.mockResolvedValueOnce({
statusCode: 200,
headers: nextPageHeader(2),
result: [release('jbr-release-21.0.11b1163.116', false)]
})
.mockResolvedValueOnce({
statusCode: 200,
headers: nextPageHeader(3),
result: []
});
const distribution = new JetBrainsDistribution({
version: '26-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
await distribution['getAvailableVersions']();
expect(spyHttpClient).toHaveBeenCalledTimes(2);
});
it('stops at the pagination safeguard', async () => {
spyHttpClient.mockResolvedValue({
statusCode: 200,
headers: nextPageHeader(2),
result: [release('jbr-release-21.0.11b1163.116', false)]
});
const distribution = new JetBrainsDistribution({
version: '26-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions).toEqual([]);
expect(spyHttpClient).toHaveBeenCalledTimes(MAX_PAGINATION_PAGES);
expect(core.warning).toHaveBeenCalledWith(
`Reached pagination safeguard limit (${MAX_PAGINATION_PAGES} pages) while listing JetBrains Runtime releases.`
);
});
it('ignores pagination links with an unexpected origin', async () => {
spyHttpClient.mockResolvedValueOnce({
statusCode: 200,
headers: {
link: '<https://example.com/releases?page=2>; rel="next"'
},
result: [release('jbr-release-21.0.11b1163.116', false)]
});
const distribution = new JetBrainsDistribution({
version: '26-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
await distribution['getAvailableVersions']();
expect(spyHttpClient).toHaveBeenCalledTimes(1);
expect(core.warning).toHaveBeenCalledWith(
'Ignoring pagination link with unexpected origin: https://example.com/releases?page=2'
);
});
it('retries a GitHub rate limit using Retry-After', async () => {
spyHttpClient.mockRestore();
const sleep = jest.fn(async () => undefined);
@@ -8,6 +8,7 @@ import {
beforeAll,
afterAll
} from '@jest/globals';
import fs from 'fs';
import type {
ArchitectureOptions,
LibericaVersion
@@ -260,6 +261,16 @@ describe('findPackageForDownload', () => {
});
describe('getPlatformOption', () => {
beforeEach(() => {
// The linux row below is glibc, so pin the Alpine probe rather than
// letting it depend on the machine running the suite.
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
});
afterEach(() => {
jest.restoreAllMocks();
});
const distributions = new LibericaDistributions({
architecture: 'x64',
version: '11',
@@ -335,3 +346,35 @@ describe('convertVersionToSemver', () => {
expect(actual).toEqual(expected);
});
});
describe('Liberica getPlatformOption libc selection', () => {
const distributions = new LibericaDistributions({
architecture: 'x64',
version: '11',
packageType: 'jdk',
checkLatest: false
});
afterEach(() => {
jest.restoreAllMocks();
});
it('selects the musl artifacts on Alpine', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(distributions['getPlatformOption']('linux')).toBe('linux-musl');
});
it('selects the glibc artifacts on other Linux runners', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(distributions['getPlatformOption']('linux')).toBe('linux');
});
it('does not probe for Alpine off Linux', () => {
const existsSync = jest.spyOn(fs, 'existsSync');
expect(distributions['getPlatformOption']('darwin')).toBe('macos');
expect(existsSync).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,5 @@
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals';
import fs from 'fs';
import type {
ArchitectureOptions,
NikVersion
@@ -170,6 +171,16 @@ describe('findPackageForDownload', () => {
});
describe('getPlatformOption', () => {
beforeEach(() => {
// The linux row below is glibc, so pin the Alpine probe rather than
// letting it depend on the machine running the suite.
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
});
afterEach(() => {
jest.restoreAllMocks();
});
const distributions = new LibericaNikDistributions({
architecture: 'x64',
version: '21',
@@ -217,3 +228,35 @@ describe('convertVersionToSemver', () => {
expect(actual).toEqual(expected);
});
});
describe('Liberica NIK getPlatformOption libc selection', () => {
const distributions = new LibericaNikDistributions({
architecture: 'x64',
version: '21',
packageType: 'jdk',
checkLatest: false
});
afterEach(() => {
jest.restoreAllMocks();
});
it('selects the musl artifacts on Alpine', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(distributions['getPlatformOption']('linux')).toBe('linux-musl');
});
it('selects the glibc artifacts on other Linux runners', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(distributions['getPlatformOption']('linux')).toBe('linux');
});
it('does not probe for Alpine off Linux', () => {
const existsSync = jest.spyOn(fs, 'existsSync');
expect(distributions['getPlatformOption']('darwin')).toBe('macos');
expect(existsSync).not.toHaveBeenCalled();
});
});
@@ -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,
@@ -86,7 +86,7 @@ jest.unstable_mockModule('../../src/util.js', () => ({
jest.unstable_mockModule('../../src/gpg.js', () => ({
importKey: jest.fn(),
deleteKey: jest.fn(),
removeGpgHome: jest.fn(),
verifyPackageSignature: jest.fn()
}));
@@ -142,8 +142,32 @@ describe('findPackageForDownload', () => {
.replace('{{OS_TYPE}}', osType)
.replace('{{ARCHIVE_TYPE}}', archiveType);
expect(result.url).toBe(url);
// Only the `/latest/` path serves changing contents, so only it must be
// excluded from the resolution cache.
expect(result.floating).toBe(url.includes('/latest/'));
});
it.each([
['21', 'etag:"oracle-latest"'],
['21.0.1', undefined]
])(
'fingerprints only the floating artifact for version %s',
async (input, expected) => {
spyHttpClient = jest.spyOn(HttpClient.prototype, 'head');
spyHttpClient.mockResolvedValue({
message: {statusCode: 200, headers: {etag: '"oracle-latest"'}}
});
const result = await distribution['findPackageForDownload'](input);
jest.restoreAllMocks();
// Without a fingerprint the constant `/latest/` URL would key a cache
// entry that never invalidates when Oracle republishes the artifact.
expect(result.fingerprint).toBe(expected);
}
);
it('fetches the authoritative sha256 checksum for the resolved archive', async () => {
spyHttpClient = jest.spyOn(HttpClient.prototype, 'head');
spyHttpClient.mockResolvedValue({message: {statusCode: 200}});
@@ -161,6 +185,17 @@ describe('findPackageForDownload', () => {
expect(spyHttpClientGet).toHaveBeenCalledTimes(1);
});
it('always resolves major-only requests remotely', () => {
expect(distribution['requiresRemoteResolution']()).toBe(true);
const exactDistribution = new OracleDistribution({
version: '21.0.8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
expect(exactDistribution['requiresRemoteResolution']()).toBe(false);
});
it.each([
['amd64', 'x64'],
['arm64', 'aarch64']
@@ -0,0 +1,109 @@
import {beforeEach, describe, expect, it, jest} from '@jest/globals';
import path from 'path';
const mockReaddirSync = jest.fn();
const realFs = await import('fs');
jest.unstable_mockModule('fs', () => ({
...realFs,
default: {...realFs.default, readdirSync: mockReaddirSync},
readdirSync: mockReaddirSync
}));
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
debug: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn()
}));
const realUtil = await import('../../src/util.js');
const mockCacheJdkDir = jest.fn();
const mockExtractJdkFile = jest.fn();
const mockRenameWinArchive = jest.fn();
jest.unstable_mockModule('../../src/util.js', () => ({
...realUtil,
cacheJdkDir: mockCacheJdkDir,
extractJdkFile: mockExtractJdkFile,
renameWinArchive: mockRenameWinArchive
}));
const {RedHatDistribution} =
await import('../../src/distributions/redhat/installer.js');
const release = {
version: '21.0.8+9',
url: 'https://developers.redhat.com/openjdk-21.tar.xz',
checksum: {
algorithm: 'sha256' as const,
value: 'a'.repeat(64)
}
};
const createDistribution = () =>
new RedHatDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
beforeEach(() => {
jest.clearAllMocks();
mockReaddirSync.mockReturnValue(['jdk-21']);
mockExtractJdkFile.mockResolvedValue('/tmp/extracted');
mockCacheJdkDir.mockResolvedValue('/toolcache/Java_RedHat_jdk/21.0.8-9/x64');
mockRenameWinArchive.mockReturnValue('/tmp/download.zip');
});
describe('Red Hat package installation', () => {
it('extracts and caches Linux tar.xz archives', async () => {
const distribution = createDistribution();
distribution['downloadAndVerify'] = jest
.fn()
.mockResolvedValue('/tmp/download');
distribution['getArchiveType'] = () => 'tar.xz';
const result = await distribution['downloadTool'](release);
expect(mockExtractJdkFile).toHaveBeenCalledWith('/tmp/download', 'tar.xz');
expect(mockRenameWinArchive).not.toHaveBeenCalled();
expect(mockCacheJdkDir).toHaveBeenCalledWith(
path.join('/tmp/extracted', 'jdk-21'),
'Java_RedHat_jdk',
'21.0.8-9',
'x64'
);
expect(result).toEqual({
version: '21.0.8+9',
path: '/toolcache/Java_RedHat_jdk/21.0.8-9/x64'
});
});
it('renames downloaded Windows ZIP archives before extraction', async () => {
const distribution = createDistribution();
distribution['downloadAndVerify'] = jest
.fn()
.mockResolvedValue('/tmp/download');
distribution['getArchiveType'] = () => 'zip';
await distribution['downloadTool'](release);
expect(mockRenameWinArchive).toHaveBeenCalledWith('/tmp/download');
expect(mockExtractJdkFile).toHaveBeenCalledWith('/tmp/download.zip', 'zip');
});
it('fails when the extracted archive is empty', async () => {
mockReaddirSync.mockReturnValue([]);
const distribution = createDistribution();
distribution['downloadAndVerify'] = jest
.fn()
.mockResolvedValue('/tmp/download');
distribution['getArchiveType'] = () => 'tar.xz';
await expect(distribution['downloadTool'](release)).rejects.toThrow(
'The Red Hat archive for Java 21.0.8+9 was empty.'
);
expect(mockCacheJdkDir).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,181 @@
import {afterEach, describe, expect, it, jest} from '@jest/globals';
import {HttpClient} from '@actions/http-client';
import packageDetails from '../data/redhat-package-details.json' with {type: 'json'};
import packages from '../data/redhat-packages.json' with {type: 'json'};
import {RedHatDistribution} from '../../src/distributions/redhat/installer.js';
const createDistribution = (
version: string,
packageType = 'jdk'
): RedHatDistribution => {
const distribution = new RedHatDistribution({
version,
architecture: 'x64',
packageType,
checkLatest: false
});
distribution['getOperatingSystem'] = () => 'linux';
distribution['getArchiveType'] = () => 'tar.xz';
return distribution;
};
const mockDisco = (
packageResponse: unknown = packages,
detailsResponse: unknown = packageDetails
) =>
jest.spyOn(HttpClient.prototype, 'getJson').mockImplementation(async url => ({
result: url.includes('/packages?') ? packageResponse : detailsResponse,
statusCode: 200,
headers: {}
}));
afterEach(() => {
jest.restoreAllMocks();
});
describe('Red Hat package resolution', () => {
it('resolves the newest matching release and authoritative checksum', async () => {
const getJson = mockDisco();
const distribution = createDistribution('21');
const release = await distribution['findPackageForDownload']('21');
expect(release).toEqual({
version: '21.0.8+9',
url: packageDetails.result[0].direct_download_uri,
checksum: {
algorithm: 'sha256',
value: packageDetails.result[0].checksum,
source:
'https://api.foojay.io/disco/v3.0/ids/redhat-21.0.8-jdk-linux-x64'
}
});
expect(getJson).toHaveBeenNthCalledWith(
1,
expect.stringContaining(
'distro=redhat&release_status=ga&operating_system=linux&architecture=x64&package_type=jdk&archive_type=tar.xz&directly_downloadable=true'
)
);
expect(getJson).toHaveBeenNthCalledWith(
2,
'https://api.foojay.io/disco/v3.0/ids/redhat-21.0.8-jdk-linux-x64'
);
});
it('normalizes feature-only Disco versions before matching', async () => {
mockDisco(undefined, {
result: [
{
...packageDetails.result[0],
direct_download_uri: 'https://developers.redhat.com/openjdk-9.tar.xz'
}
],
message: ''
});
const distribution = createDistribution('9');
const release = await distribution['findPackageForDownload']('9');
expect(release.version).toBe('9.0.0+181');
});
it('selects the requested package type', async () => {
const getJson = mockDisco();
const distribution = createDistribution('21', 'jre');
await distribution['findPackageForDownload']('21');
expect(getJson).toHaveBeenNthCalledWith(
1,
expect.stringContaining('package_type=jre')
);
expect(getJson).toHaveBeenNthCalledWith(
2,
'https://api.foojay.io/disco/v3.0/ids/redhat-21.0.8-jre-linux-x64'
);
});
it('maps Windows to ZIP packages', async () => {
const getJson = mockDisco();
const distribution = createDistribution('17');
distribution['getOperatingSystem'] = () => 'windows';
distribution['getArchiveType'] = () => 'zip';
await distribution['findPackageForDownload']('17');
expect(getJson).toHaveBeenNthCalledWith(
1,
expect.stringContaining(
'operating_system=windows&architecture=x64&package_type=jdk&archive_type=zip'
)
);
expect(getJson).toHaveBeenNthCalledWith(
2,
'https://api.foojay.io/disco/v3.0/ids/redhat-17.0.16-jdk-windows-x64'
);
});
it('rejects Alpine before requesting glibc package metadata', async () => {
const getJson = mockDisco();
const distribution = new RedHatDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
expect(() => distribution['getOperatingSystem'](true)).toThrow(
"Distribution 'redhat' does not support Alpine Linux because Red Hat portable archives require glibc."
);
expect(getJson).not.toHaveBeenCalled();
});
it('rejects early-access versions before requesting metadata', async () => {
const getJson = mockDisco();
const distribution = createDistribution('21-ea');
await expect(distribution['findPackageForDownload']('21')).rejects.toThrow(
'Early access versions are not supported'
);
expect(getJson).not.toHaveBeenCalled();
});
it('reports available versions when no release matches', async () => {
mockDisco();
const distribution = createDistribution('25');
await expect(distribution['findPackageForDownload']('25')).rejects.toThrow(
"No matching version found for SemVer '25'.\nDistribution: RedHat"
);
});
it('fails when the package detail has no direct Red Hat URL', async () => {
mockDisco(packages, {result: [], message: ''});
const distribution = createDistribution('21');
await expect(distribution['findPackageForDownload']('21')).rejects.toThrow(
'returned no direct Red Hat download URL'
);
});
it('fails when the package detail has no SHA-256 checksum', async () => {
mockDisco(packages, {
result: [{...packageDetails.result[0], checksum: ''}],
message: ''
});
const distribution = createDistribution('21');
await expect(distribution['findPackageForDownload']('21')).rejects.toThrow(
'returned no SHA-256 checksum'
);
});
it('fails with a targeted error when package metadata is missing', async () => {
mockDisco(null);
const distribution = createDistribution('21');
await expect(distribution['findPackageForDownload']('21')).rejects.toThrow(
'Could not fetch Red Hat package metadata from Foojay Disco'
);
});
});
@@ -11,6 +11,7 @@ import {
import {HttpClient} from '@actions/http-client';
import manifestData from '../data/sapmachine.json' with {type: 'json'};
import releaseClassManifestData from '../data/sapmachine-release-classes.json' with {type: 'json'};
// Mock @actions/core before importing source modules that depend on it
jest.unstable_mockModule('@actions/core', () => ({
@@ -132,9 +133,9 @@ describe('getAvailableVersions', () => {
['11', 'aarch64', 'linux', 54],
['17', 'riscv', 'linux', 0],
['16.0.1', 'x64', 'linux', 71],
['23-ea', 'x64', 'linux', 798],
['23-ea', 'x64', 'linux', 727],
['23-ea', 'aarch64', 'windows', 0],
['23-ea', 'x64', 'windows', 750]
['23-ea', 'x64', 'windows', 679]
])(
'should get right number of available versions from JSON',
async (
@@ -156,6 +157,45 @@ describe('getAvailableVersions', () => {
expect(availableVersions.length).toBe(len);
}
);
it.each([
[
'25',
[
'https://example.test/sapmachine-25.0.2-ga.tar.gz',
'https://example.test/sapmachine-25.0.1-ga.tar.gz'
]
],
[
'25-ea',
[
'https://example.test/sapmachine-25-ea.11.tar.gz',
'https://example.test/sapmachine-25-ea.10.tar.gz'
]
]
])(
'should classify boolean and string EA metadata for %s requests',
async (version: string, expectedLinks: string[]) => {
spyHttpClient.mockReturnValue({
statusCode: 200,
headers: {},
result: releaseClassManifestData
});
const distribution = new SapMachineDistribution({
version,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, 'linux');
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions.map(item => item.downloadLink)).toStrictEqual(
expectedLinks
);
}
);
});
describe('findPackageForDownload', () => {
@@ -314,6 +354,27 @@ describe('getAvailableVersions', () => {
expect(release.checksum?.value).toBe(archiveChecksum);
});
it('does not select a newer stable release for an EA request', async () => {
spyHttpClient.mockReturnValue({
statusCode: 200,
headers: {},
result: releaseClassManifestData
});
const distribution = new SapMachineDistribution({
version: '25-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, 'linux');
const release = await distribution['findPackageForDownload']('25');
expect(release.url).toBe(
'https://example.test/sapmachine-25-ea.11.tar.gz'
);
});
it.each([
['8', 'linux', 'x64'],
['8', 'macos', 'aarch64'],
@@ -72,7 +72,7 @@ jest.unstable_mockModule('../../src/util.js', () => ({
jest.unstable_mockModule('../../src/gpg.js', () => ({
importKey: jest.fn(),
deleteKey: jest.fn(),
removeGpgHome: jest.fn(),
verifyPackageSignature: jest.fn()
}));
@@ -8,6 +8,7 @@ import {
beforeAll,
afterAll
} from '@jest/globals';
import fs from 'fs';
import type {IZuluVersions} from '../../src/distributions/zulu/models.js';
import {HttpClient} from '@actions/http-client';
import os from 'os';
@@ -346,3 +347,50 @@ describe('findPackageForDownload', () => {
).rejects.toThrow(/No matching version found for SemVer/);
});
});
describe('Zulu getPlatformOption libc selection', () => {
const originalPlatform = Object.getOwnPropertyDescriptor(
process,
'platform'
) as PropertyDescriptor;
const setPlatform = (platform: NodeJS.Platform) =>
Object.defineProperty(process, 'platform', {
...originalPlatform,
value: platform
});
const distribution = new ZuluDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
afterEach(() => {
Object.defineProperty(process, 'platform', originalPlatform);
jest.restoreAllMocks();
});
it('selects the musl artifacts on Alpine', () => {
setPlatform('linux');
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(distribution['getPlatformOption']()).toBe('linux_musl');
});
it('selects the glibc artifacts on other Linux runners', () => {
setPlatform('linux');
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
expect(distribution['getPlatformOption']()).toBe('linux_glibc');
});
it('does not probe for Alpine off Linux', () => {
setPlatform('win32');
const existsSync = jest.spyOn(fs, 'existsSync');
expect(distribution['getPlatformOption']()).toBe('windows');
expect(existsSync).not.toHaveBeenCalled();
});
});
+177 -54
View File
@@ -8,6 +8,7 @@ import {
afterEach
} from '@jest/globals';
import {fileURLToPath} from 'url';
import * as fs from 'fs';
import * as path from 'path';
import * as io from '@actions/io';
@@ -30,7 +31,10 @@ process.env['RUNNER_TEMP'] = tempDir;
describe('gpg tests', () => {
beforeEach(async () => {
await io.rmRF(tempDir);
await io.mkdirP(tempDir);
jest.clearAllMocks();
(exec.exec as jest.Mock<any>).mockResolvedValue(0);
});
afterAll(async () => {
@@ -71,74 +75,193 @@ describe('gpg tests', () => {
});
describe('importKey', () => {
it('attempts to import private key and returns null key id on failure', async () => {
it('imports private keys into a unique isolated GPG home', async () => {
const privateKey = 'KEY CONTENTS';
const keyId = await gpg.importKey(privateKey);
let privateKeyFile = '';
(exec.exec as jest.Mock<any>).mockImplementation(
async (_command: string, _args: string[]) => {
const [createdGpgHome] = fs.readdirSync(tempDir);
privateKeyFile = path.join(
tempDir,
createdGpgHome,
fs
.readdirSync(path.join(tempDir, createdGpgHome))
.find(file => file.startsWith('private-key-')) ?? ''
);
expect(fs.readFileSync(privateKeyFile, 'utf8')).toBe(privateKey);
if (process.platform !== 'win32') {
expect(fs.statSync(privateKeyFile).mode & 0o777).toBe(0o600);
}
return 0;
}
);
expect(keyId).toBeNull();
const gpgHome = await gpg.importKey(privateKey);
expect(path.dirname(gpgHome)).toBe(tempDir);
expect(path.basename(gpgHome).startsWith(gpg.GPG_HOME_PREFIX)).toBe(true);
expect(fs.existsSync(gpgHome)).toBe(true);
expect(fs.existsSync(privateKeyFile)).toBe(false);
if (process.platform !== 'win32') {
expect(fs.statSync(gpgHome).mode & 0o777).toBe(0o700);
}
expect(exec.exec).toHaveBeenCalledWith(
'gpg',
expect.anything(),
expect.anything()
[
'--homedir',
gpg.toGpgPath(gpgHome),
'--batch',
'--import',
gpg.toGpgPath(privateKeyFile)
],
{silent: true}
);
});
it('removes the private-key file and isolated home when import fails', async () => {
let gpgHome = '';
let privateKeyFile = '';
(exec.exec as jest.Mock<any>).mockImplementation(
async (_command: string, _args: string[]) => {
const [createdGpgHome] = fs.readdirSync(tempDir);
gpgHome = path.join(tempDir, createdGpgHome);
privateKeyFile = path.join(
gpgHome,
fs
.readdirSync(gpgHome)
.find(file => file.startsWith('private-key-')) ?? ''
);
expect(fs.existsSync(privateKeyFile)).toBe(true);
throw new Error('invalid key');
}
);
await expect(gpg.importKey('INVALID KEY')).rejects.toThrow('invalid key');
expect(fs.existsSync(privateKeyFile)).toBe(false);
expect(fs.existsSync(gpgHome)).toBe(false);
});
it('imports multi-key input without parsing or deleting fingerprints', async () => {
const privateKeys = 'KEY ONE\nKEY TWO';
(exec.exec as jest.Mock<any>).mockImplementation(
async (_command: string, _args: string[]) => {
const [createdGpgHome] = fs.readdirSync(tempDir);
const keyFile = fs
.readdirSync(path.join(tempDir, createdGpgHome))
.find(file => file.startsWith('private-key-'));
expect(
fs.readFileSync(
path.join(tempDir, createdGpgHome, keyFile ?? ''),
'utf8'
)
).toBe(privateKeys);
return 0;
}
);
const gpgHome = await gpg.importKey(privateKeys);
expect(gpgHome).toContain(gpg.GPG_HOME_PREFIX);
expect(exec.exec).toHaveBeenCalledTimes(1);
expect((exec.exec as jest.Mock).mock.calls[0][1]).not.toContain(
'--delete-secret-and-public-key'
);
});
it('uses a separate GPG home for each invocation', async () => {
const firstGpgHome = await gpg.importKey('FIRST KEY');
const secondGpgHome = await gpg.importKey('SECOND KEY');
expect(firstGpgHome).not.toBe(secondGpgHome);
expect(fs.existsSync(firstGpgHome)).toBe(true);
expect(fs.existsSync(secondGpgHome)).toBe(true);
});
});
describe('deleteKey', () => {
it('deletes private key', async () => {
const keyId = 'asdfhjkl';
await gpg.deleteKey(keyId);
describe('removeGpgHome', () => {
it('removes only action-owned GPG homes and is idempotent', async () => {
const gpgHome = await gpg.importKey('KEY CONTENTS');
const unrelatedGpgHome = path.join(tempDir, 'user-gpg-home');
fs.mkdirSync(unrelatedGpgHome);
expect(exec.exec).toHaveBeenCalledWith(
'gpg',
expect.anything(),
expect.anything()
await gpg.removeGpgHome(gpgHome);
await gpg.removeGpgHome(gpgHome);
expect(exec.exec).toHaveBeenNthCalledWith(
2,
'gpgconf',
['--homedir', gpg.toGpgPath(gpgHome), '--kill', 'gpg-agent'],
{silent: true, ignoreReturnCode: true}
);
expect(exec.exec).toHaveBeenCalledTimes(2);
expect(fs.existsSync(gpgHome)).toBe(false);
expect(fs.existsSync(unrelatedGpgHome)).toBe(true);
});
describe('verifyPackageSignature', () => {
it('imports bundled key and verifies package', async () => {
const publicKeyContent =
'-----BEGIN PGP PUBLIC KEY BLOCK-----\ntest\n-----END PGP PUBLIC KEY BLOCK-----';
(tc.downloadTool as jest.Mock<any>).mockResolvedValue(
'/tmp/jdk.tar.gz.sig'
);
await gpg.verifyPackageSignature(
'/tmp/jdk.tar.gz',
'https://example.com/jdk.tar.gz.sig',
publicKeyContent
);
it('removes the GPG home when gpgconf is unavailable', async () => {
const gpgHome = await gpg.importKey('KEY CONTENTS');
(exec.exec as jest.Mock<any>).mockRejectedValueOnce(
new Error('gpgconf not found')
);
expect(tc.downloadTool).toHaveBeenCalledWith(
'https://example.com/jdk.tar.gz.sig'
);
expect(exec.exec).toHaveBeenNthCalledWith(
1,
'gpg',
[
'--homedir',
expect.any(String),
'--batch',
'--import',
expect.stringContaining('public-key.asc')
],
expect.objectContaining({silent: true})
);
expect(exec.exec).toHaveBeenNthCalledWith(
2,
'gpg',
[
'--homedir',
expect.any(String),
'--batch',
'--verify',
'/tmp/jdk.tar.gz.sig',
'/tmp/jdk.tar.gz'
],
expect.objectContaining({silent: true})
);
});
await gpg.removeGpgHome(gpgHome);
expect(fs.existsSync(gpgHome)).toBe(false);
});
it('refuses to remove a GPG home it does not own', async () => {
const unrelatedGpgHome = path.join(tempDir, 'user-gpg-home');
fs.mkdirSync(unrelatedGpgHome, {recursive: true});
await expect(gpg.removeGpgHome(unrelatedGpgHome)).rejects.toThrow(
'Refusing to remove unexpected GPG home'
);
expect(fs.existsSync(unrelatedGpgHome)).toBe(true);
});
});
describe('verifyPackageSignature', () => {
it('imports bundled key and verifies package', async () => {
const publicKeyContent =
'-----BEGIN PGP PUBLIC KEY BLOCK-----\ntest\n-----END PGP PUBLIC KEY BLOCK-----';
(tc.downloadTool as jest.Mock<any>).mockResolvedValue(
'/tmp/jdk.tar.gz.sig'
);
await gpg.verifyPackageSignature(
'/tmp/jdk.tar.gz',
'https://example.com/jdk.tar.gz.sig',
publicKeyContent
);
expect(tc.downloadTool).toHaveBeenCalledWith(
'https://example.com/jdk.tar.gz.sig'
);
expect(exec.exec).toHaveBeenNthCalledWith(
1,
'gpg',
[
'--homedir',
expect.any(String),
'--batch',
'--import',
expect.stringContaining('public-key.asc')
],
expect.objectContaining({silent: true})
);
expect(exec.exec).toHaveBeenNthCalledWith(
2,
'gpg',
[
'--homedir',
expect.any(String),
'--batch',
'--verify',
'/tmp/jdk.tar.gz.sig',
'/tmp/jdk.tar.gz'
],
expect.objectContaining({silent: true})
);
});
});
});
+1 -1
View File
@@ -22,7 +22,7 @@ describe('java-package published contract', () => {
? content.match(/ {2}java-package:\n(?: {4}.+\n)+/)?.[0]
: content
.split('\n')
.find(line => line.includes('- `java-package`:'));
.find(line => line.includes('| `java-package` |'));
expect(contractLine).toBeDefined();
for (const packageType of allPackageTypes) {
+34
View File
@@ -1,6 +1,8 @@
import fs from 'fs';
import path from 'path';
import {
getJavaPlatformIdentity,
isAlpineLinux,
JAVA_PLATFORM_CAPABILITIES,
normalizeArchitecture,
validateJavaPlatform
@@ -28,6 +30,38 @@ describe('Java platform capabilities', () => {
expect(normalizeArchitecture(input)).toBe(expected);
});
it.each([
['linux', false, 'linux-glibc'],
['linux', true, 'linux-musl'],
['darwin', false, 'macos'],
['win32', false, 'windows'],
// Exercises the normalizePlatform alias path and the `?? platform`
// fallback for a platform that has no Java alias.
['sunos', false, 'solaris'],
['aix', false, 'aix']
] as const)(
'identifies %s with Alpine release %s as %s',
(platform, alpineReleaseExists, expected) => {
expect(getJavaPlatformIdentity(platform, alpineReleaseExists)).toBe(
expected
);
}
);
// The platform check has to short-circuit before the filesystem probe, so a
// stray /etc/alpine-release can never make a non-Linux runner look like musl.
it.each([
['linux', true, true],
['linux', false, false],
['darwin', true, false],
['win32', true, false]
] as const)(
'treats %s with Alpine release %s as Alpine: %s',
(platform, alpineReleaseExists, expected) => {
expect(isAlpineLinux(platform, alpineReleaseExists)).toBe(expected);
}
);
it('uses the normalized architecture for validation', () => {
expect(validateJavaPlatform('microsoft', 'linux', 'arm64', '25')).toBe(
'aarch64'
+325
View File
@@ -0,0 +1,325 @@
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals';
import fs from 'fs';
import os from 'os';
import path from 'path';
jest.unstable_mockModule('@actions/cache', () => ({
restoreCache: jest.fn(),
saveCache: jest.fn(),
ReserveCacheError: class ReserveCacheError extends Error {
constructor(message: string) {
super(message);
this.name = 'ReserveCacheError';
}
}
}));
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
saveState: jest.fn(),
getState: jest.fn()
}));
jest.unstable_mockModule('../src/cache-feature.js', () => ({
isCacheFeatureAvailable: jest.fn()
}));
const cache = await import('@actions/cache');
const core = await import('@actions/core');
const cacheFeature = await import('../src/cache-feature.js');
const {
buildJdkCacheKey,
getJdkVerificationIdentity,
registerJdk,
restoreJdk,
saveJdkCaches
} = await import('../src/jdk-cache.js');
const jdk = {
distribution: 'temurin',
packageType: 'jdk',
architecture: 'x64',
version: '21.0.8+9',
source: 'sha256:abc123',
verification: 'unverified',
path: '/toolcache/Java_temurin_jdk/21.0.8-9'
};
describe('JDK cache', () => {
const tempRoots: string[] = [];
const createInstallation = (marker = 'a'): string => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-java-jdk-'));
tempRoots.push(root);
const jdkPath = path.join(root, 'Java_temurin_jdk', '21.0.8-9');
writeInstallation(jdkPath, marker);
return jdkPath;
};
const writeInstallation = (jdkPath: string, marker: string): void => {
const architecturePath = path.join(jdkPath, 'x64');
fs.rmSync(architecturePath, {recursive: true, force: true});
fs.rmSync(`${architecturePath}.complete`, {force: true});
fs.mkdirSync(path.join(architecturePath, 'bin'), {recursive: true});
fs.writeFileSync(path.join(architecturePath, 'bin', 'java'), marker);
fs.writeFileSync(`${architecturePath}.complete`, marker);
};
const lastState = (): string =>
((core.saveState as jest.Mock).mock.calls.at(-1) as string[])[1];
beforeEach(() => {
jest.resetAllMocks();
(cacheFeature.isCacheFeatureAvailable as jest.Mock).mockReturnValue(true);
process.env['RUNNER_OS'] = 'Linux';
});
afterEach(() => {
jest.restoreAllMocks();
delete process.env['RUNNER_OS'];
while (tempRoots.length) {
fs.rmSync(tempRoots.pop()!, {recursive: true, force: true});
}
});
it('builds distinct keys for incompatible JDK identities', () => {
const key = buildJdkCacheKey(jdk);
expect(key).toMatch(/^setup-java-jdk-v1-Linux-x64-[a-f0-9]{64}$/);
expect(buildJdkCacheKey({...jdk, architecture: 'aarch64'})).not.toBe(key);
expect(buildJdkCacheKey({...jdk, distribution: 'zulu'})).not.toBe(key);
expect(buildJdkCacheKey({...jdk, packageType: 'jre'})).not.toBe(key);
expect(buildJdkCacheKey({...jdk, version: '21.0.7+6'})).not.toBe(key);
expect(buildJdkCacheKey({...jdk, source: 'sha256:def456'})).not.toBe(key);
});
it('preserves canonical runner OS values and separates operating systems', () => {
process.env['RUNNER_OS'] = 'Linux';
const linux = buildJdkCacheKey(jdk);
process.env['RUNNER_OS'] = 'Windows';
const windows = buildJdkCacheKey(jdk);
process.env['RUNNER_OS'] = 'macOS';
const macos = buildJdkCacheKey(jdk);
expect(new Set([linux, windows, macos])).toHaveProperty('size', 3);
expect(linux).toMatch(/^setup-java-jdk-v1-Linux-x64-/);
expect(windows).toMatch(/^setup-java-jdk-v1-Windows-x64-/);
expect(macos).toMatch(/^setup-java-jdk-v1-macOS-x64-/);
});
it('falls back to process.platform without RUNNER_OS', () => {
delete process.env['RUNNER_OS'];
expect(buildJdkCacheKey(jdk)).toMatch(
new RegExp(`^setup-java-jdk-v1-${process.platform}-x64-`)
);
});
it('separates unverified, bundled-key, and custom-key caches', () => {
const unverified = getJdkVerificationIdentity(false);
const bundled = getJdkVerificationIdentity(true);
const customA = getJdkVerificationIdentity(
true,
'-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nkey-a\r\n-----END PGP PUBLIC KEY BLOCK-----\r\n'
);
const customANormalized = getJdkVerificationIdentity(
true,
'-----BEGIN PGP PUBLIC KEY BLOCK-----\nkey-a\n-----END PGP PUBLIC KEY BLOCK-----'
);
const customB = getJdkVerificationIdentity(true, 'different-key');
expect(new Set([unverified, bundled, customA, customB])).toHaveProperty(
'size',
4
);
expect(customA).toBe(customANormalized);
expect(customA).not.toContain('key-a');
expect(
new Set(
[unverified, bundled, customA, customB].map(verification =>
buildJdkCacheKey({...jdk, verification})
)
)
).toHaveProperty('size', 4);
});
it('restores and records an exact JDK cache hit', async () => {
(cache.restoreCache as jest.Mock).mockResolvedValue(buildJdkCacheKey(jdk));
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
await expect(restoreJdk(jdk)).resolves.toBe(true);
expect(cache.restoreCache).toHaveBeenCalledWith(
[jdk.path],
buildJdkCacheKey(jdk)
);
const architecturePath = path.join(jdk.path, 'x64');
expect(fs.existsSync).toHaveBeenCalledWith(architecturePath);
expect(fs.existsSync).toHaveBeenCalledWith(`${architecturePath}.complete`);
expect(core.saveState).toHaveBeenCalledWith(
'jdk-caches',
expect.stringContaining(buildJdkCacheKey(jdk))
);
});
it('falls back to download when restoration fails', async () => {
(cache.restoreCache as jest.Mock).mockRejectedValue(
new Error('cache unavailable')
);
await expect(restoreJdk(jdk)).resolves.toBe(false);
expect(core.warning).toHaveBeenCalledWith(
'Failed to restore JDK cache: cache unavailable'
);
});
it('saves a downloaded JDK registered after installation', async () => {
const jdkPath = createInstallation();
const installed = {...jdk, path: jdkPath};
const key = buildJdkCacheKey(installed);
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined);
await restoreJdk(installed);
registerJdk(installed);
(core.getState as jest.Mock).mockReturnValue(lastState());
(cache.saveCache as jest.Mock).mockResolvedValue(1);
await saveJdkCaches();
expect(cache.saveCache).toHaveBeenCalledWith([jdkPath], key);
});
it('does not save an installation that was replaced after registration', async () => {
const jdkPath = createInstallation();
const installed = {...jdk, path: jdkPath};
const key = buildJdkCacheKey(installed);
registerJdk(installed);
(core.getState as jest.Mock).mockReturnValue(lastState());
writeInstallation(jdkPath, 'replaced-by-a-later-step');
await saveJdkCaches();
expect(cache.saveCache).not.toHaveBeenCalledWith([jdkPath], key);
expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining('was replaced after it was registered')
);
});
it('saves only the key matching the installation that occupies the path', async () => {
const jdkPath = createInstallation();
const verified = {...jdk, path: jdkPath, verification: 'verified:bundled'};
const unverified = {...jdk, path: jdkPath};
registerJdk(verified);
writeInstallation(jdkPath, 'force-downloaded-without-verification');
registerJdk(unverified);
(core.getState as jest.Mock).mockReturnValue(lastState());
(cache.saveCache as jest.Mock).mockResolvedValue(1);
await saveJdkCaches();
expect(cache.saveCache).not.toHaveBeenCalledWith(
[jdkPath],
buildJdkCacheKey(verified)
);
expect(cache.saveCache).toHaveBeenCalledWith(
[jdkPath],
buildJdkCacheKey(unverified)
);
});
it('does not save a path that was never registered as installed', async () => {
const jdkPath = createInstallation();
const installed = {...jdk, path: jdkPath};
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined);
await restoreJdk(installed);
(core.getState as jest.Mock).mockReturnValue(lastState());
await saveJdkCaches();
expect(cache.saveCache).not.toHaveBeenCalledWith(
[jdkPath],
buildJdkCacheKey(installed)
);
});
it('keeps saving the remaining JDK caches when one save fails', async () => {
const failingPath = createInstallation();
const succeedingPath = createInstallation();
const failing = {...jdk, path: failingPath};
const succeeding = {...jdk, path: succeedingPath, version: '17.0.19+9'};
registerJdk(failing);
registerJdk(succeeding);
(core.getState as jest.Mock).mockReturnValue(lastState());
(cache.saveCache as jest.Mock).mockImplementation(
async (paths: unknown) => {
if ((paths as string[])[0] === failingPath) {
throw new Error('cache service unavailable');
}
return 1;
}
);
await expect(saveJdkCaches()).resolves.toBeUndefined();
expect(cache.saveCache).toHaveBeenCalledWith(
[succeedingPath],
buildJdkCacheKey(succeeding)
);
expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining('cache service unavailable')
);
expect(core.info).toHaveBeenCalledWith(
`JDK cache saved with the key: ${buildJdkCacheKey(succeeding)}`
);
});
it('reports a reserved cache key without failing the remaining saves', async () => {
const reservedPath = createInstallation();
const reserved = {...jdk, path: reservedPath};
registerJdk(reserved);
(core.getState as jest.Mock).mockReturnValue(lastState());
(cache.saveCache as jest.Mock).mockRejectedValue(
new cache.ReserveCacheError('Unable to reserve cache')
);
await expect(saveJdkCaches()).resolves.toBeUndefined();
expect(core.info).toHaveBeenCalledWith('Unable to reserve cache');
});
it('registers a force-downloaded JDK without restoring it', () => {
const jdkPath = createInstallation();
registerJdk({...jdk, path: jdkPath});
expect(cache.restoreCache).not.toHaveBeenCalled();
expect(core.saveState).toHaveBeenCalledWith(
'jdk-caches',
expect.stringContaining(buildJdkCacheKey({...jdk, path: jdkPath}))
);
});
it('does not save an exact JDK cache hit again', async () => {
const key = buildJdkCacheKey(jdk);
(core.getState as jest.Mock).mockReturnValue(
JSON.stringify([
{
key,
path: jdk.path,
architecture: jdk.architecture,
matchedKey: key
}
])
);
await saveJdkCaches();
expect(cache.saveCache).not.toHaveBeenCalled();
});
});
+416
View File
@@ -0,0 +1,416 @@
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals';
import fs from 'fs';
import os from 'os';
import path from 'path';
jest.unstable_mockModule('@actions/cache', () => ({
isFeatureAvailable: jest.fn(),
restoreCache: jest.fn(),
saveCache: jest.fn()
}));
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
saveState: jest.fn(),
getState: jest.fn()
}));
const cache = await import('@actions/cache');
const core = await import('@actions/core');
const {restoreJdkResolution, registerJdkResolution, saveJdkResolutionCaches} =
await import('../src/jdk-resolution-cache.js');
const request = {
distribution: 'Temurin-Hotspot',
packageType: 'jdk',
platform: 'linux-glibc',
architecture: 'x64',
versionSpec: '21',
stable: true
};
const release = {
version: '21.0.8+9',
url: 'https://example.com/jdk-21.0.8.tar.gz',
checksum: {algorithm: 'sha256' as const, value: 'abc123'}
};
const WEEK = 7 * 24 * 60 * 60 * 1000;
const bucket = () =>
new Date(Math.floor(Date.now() / WEEK) * WEEK).toISOString().slice(0, 10);
describe('JDK resolution cache', () => {
const tempRoots: string[] = [];
let originalTemp: string | undefined;
let originalOs: string | undefined;
const createRunnerTemp = (): string => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-java-res-'));
tempRoots.push(root);
process.env['RUNNER_TEMP'] = root;
return root;
};
/** Emulates the cache service materializing the entry at the requested path. */
const restoreWith = (contents: string, matchedKey: string) => {
jest
.mocked(cache.restoreCache)
.mockImplementation(async (paths: string[]) => {
fs.mkdirSync(paths[0], {recursive: true});
fs.writeFileSync(path.join(paths[0], 'release.json'), contents);
return matchedKey;
});
};
beforeEach(() => {
originalTemp = process.env['RUNNER_TEMP'];
originalOs = process.env['RUNNER_OS'];
process.env['RUNNER_OS'] = 'Linux';
jest.mocked(cache.isFeatureAvailable).mockReturnValue(true);
jest.mocked(cache.restoreCache).mockResolvedValue(undefined);
jest.mocked(cache.saveCache).mockResolvedValue(1);
jest.mocked(core.getState).mockReturnValue('');
});
afterEach(() => {
process.env['RUNNER_TEMP'] = originalTemp;
process.env['RUNNER_OS'] = originalOs;
if (originalTemp === undefined) {
delete process.env['RUNNER_TEMP'];
}
if (originalOs === undefined) {
delete process.env['RUNNER_OS'];
}
while (tempRoots.length > 0) {
fs.rmSync(tempRoots.pop()!, {recursive: true, force: true});
}
jest.resetAllMocks();
});
describe('restoreJdkResolution', () => {
it('looks the entry up with a bucket-independent path', async () => {
const runnerTemp = createRunnerTemp();
await restoreJdkResolution(request);
const [paths, primaryKey, restoreKeys] = jest.mocked(cache.restoreCache)
.mock.calls[0] as [string[], string, string[]];
expect(paths).toHaveLength(1);
expect(
paths[0].startsWith(path.join(runnerTemp, 'setup-java-jdk-resolution'))
).toBe(true);
expect(paths[0]).not.toContain(bucket());
expect(primaryKey).toBe(`${restoreKeys[0]}${bucket()}`);
expect(restoreKeys[0]).toMatch(
/^setup-java-jdkres-v2-Linux-x64-[0-9a-f]{64}-$/
);
});
it('separates glibc and musl Linux resolutions', async () => {
createRunnerTemp();
await restoreJdkResolution(request);
const [glibcPaths, glibcKey] = jest.mocked(cache.restoreCache).mock
.calls[0] as [string[], string];
await restoreJdkResolution({...request, platform: 'linux-musl'});
const [muslPaths, muslKey] = jest.mocked(cache.restoreCache).mock
.calls[1] as [string[], string];
expect(muslKey).not.toBe(glibcKey);
expect(muslPaths).not.toEqual(glibcPaths);
});
it('holds the key steady for a week and then rolls it', async () => {
createRunnerTemp();
const nowSpy = jest.spyOn(Date, 'now');
const keyAt = async (ms: number) => {
nowSpy.mockReturnValue(ms);
await restoreJdkResolution(request);
return jest.mocked(cache.restoreCache).mock.calls.at(-1)![1] as string;
};
// A window boundary, so the offsets below are unambiguous.
const windowStart = 2900 * WEEK;
const start = await keyAt(windowStart);
const sameWindow = await keyAt(windowStart + 6 * 24 * 60 * 60 * 1000);
const nextWindow = await keyAt(windowStart + WEEK);
expect(sameWindow).toBe(start);
expect(nextWindow).not.toBe(start);
nowSpy.mockRestore();
});
it('reports a hit on the current bucket as fresh', async () => {
createRunnerTemp();
const key = `setup-java-jdkres-v2-Linux-x64-${'0'.repeat(64)}-${bucket()}`;
restoreWith(JSON.stringify(release), key);
// The key the module computes is the one it passes to restoreCache, so
// echo it back to emulate an exact hit.
jest
.mocked(cache.restoreCache)
.mockImplementation(async (paths: string[], primaryKey: string) => {
fs.mkdirSync(paths[0], {recursive: true});
fs.writeFileSync(
path.join(paths[0], 'release.json'),
JSON.stringify(release)
);
return primaryKey;
});
const restored = await restoreJdkResolution(request);
expect(restored?.fresh).toBe(true);
expect(restored?.release).toEqual(release);
});
it('reports a hit on an older bucket as stale', async () => {
createRunnerTemp();
restoreWith(JSON.stringify(release), 'setup-java-jdkres-v2-old');
const restored = await restoreJdkResolution(request);
expect(restored?.fresh).toBe(false);
expect(restored?.release).toEqual(release);
});
it('returns nothing when the entry is missing', async () => {
createRunnerTemp();
await expect(restoreJdkResolution(request)).resolves.toBeUndefined();
});
it('returns nothing when the cache service is unavailable', async () => {
createRunnerTemp();
jest.mocked(cache.isFeatureAvailable).mockReturnValue(false);
await expect(restoreJdkResolution(request)).resolves.toBeUndefined();
expect(cache.restoreCache).not.toHaveBeenCalled();
});
it('returns nothing when RUNNER_TEMP is not set', async () => {
delete process.env['RUNNER_TEMP'];
await expect(restoreJdkResolution(request)).resolves.toBeUndefined();
expect(cache.restoreCache).not.toHaveBeenCalled();
});
it('does not fail the job when the restore throws', async () => {
createRunnerTemp();
jest
.mocked(cache.restoreCache)
.mockRejectedValue(new Error('service unavailable'));
await expect(restoreJdkResolution(request)).resolves.toBeUndefined();
});
it.each([
['malformed JSON', 'not json'],
['a non-object payload', '"nope"'],
[
'a missing version',
JSON.stringify({url: 'https://example.com/a.tar.gz'})
],
['a missing url', JSON.stringify({version: '21.0.8+9'})],
[
'a non-HTTPS url',
JSON.stringify({
version: '21.0.8+9',
url: 'http://example.com/a.tar.gz'
})
],
[
'a malformed url',
JSON.stringify({version: '21.0.8+9', url: 'not-a-url'})
],
[
'a non-HTTPS signature url',
JSON.stringify({
version: '21.0.8+9',
url: 'https://example.com/a.tar.gz',
signatureUrl: 'http://example.com/a.sig'
})
],
[
'an unsupported checksum algorithm',
JSON.stringify({
version: '21.0.8+9',
url: 'https://example.com/a.tar.gz',
checksum: {algorithm: 'md5', value: 'abc'}
})
],
[
'a checksum without a value',
JSON.stringify({
version: '21.0.8+9',
url: 'https://example.com/a.tar.gz',
checksum: {algorithm: 'sha256'}
})
]
])('rejects an entry with %s', async (_name, contents) => {
createRunnerTemp();
restoreWith(contents, 'setup-java-jdkres-v2-old');
await expect(restoreJdkResolution(request)).resolves.toBeUndefined();
});
it('keeps the optional fields of a valid entry', async () => {
createRunnerTemp();
const full = {
version: '21.0.8+9',
url: 'https://example.com/a.tar.gz',
signatureUrl: 'https://example.com/a.sig',
checksum: {
algorithm: 'sha512',
value: 'def456',
source: 'https://example.com/a.sha512'
},
floating: true
};
restoreWith(JSON.stringify(full), 'setup-java-jdkres-v2-old');
const restored = await restoreJdkResolution(request);
expect(restored?.release).toEqual(full);
});
it('ignores unknown fields rather than passing them through', async () => {
createRunnerTemp();
restoreWith(
JSON.stringify({...release, evil: 'payload'}),
'setup-java-jdkres-v2-old'
);
const restored = await restoreJdkResolution(request);
expect(restored?.release).toEqual(release);
});
});
describe('registerJdkResolution', () => {
it('writes the release and records it under the current bucket', () => {
createRunnerTemp();
registerJdkResolution(request, release);
const state = JSON.parse(
jest.mocked(core.saveState).mock.calls.at(-1)![1] as string
);
const entry = state.at(-1);
expect(entry.key.endsWith(bucket())).toBe(true);
expect(
JSON.parse(
fs.readFileSync(path.join(entry.path, 'release.json'), 'utf8')
)
).toEqual(release);
});
it('does nothing when the cache service is unavailable', () => {
createRunnerTemp();
jest.mocked(cache.isFeatureAvailable).mockReturnValue(false);
registerJdkResolution(request, release);
expect(core.saveState).not.toHaveBeenCalled();
});
it('does nothing when RUNNER_TEMP is not set', () => {
delete process.env['RUNNER_TEMP'];
registerJdkResolution(request, release);
expect(core.saveState).not.toHaveBeenCalled();
});
it('uses different keys for different requests', () => {
createRunnerTemp();
registerJdkResolution(request, release);
registerJdkResolution({...request, distribution: 'zulu'}, release);
const state = JSON.parse(
jest.mocked(core.saveState).mock.calls.at(-1)![1] as string
);
expect(new Set(state.map((item: {key: string}) => item.key)).size).toBe(
state.length
);
});
it('uses different keys for different floating artifact identities', () => {
createRunnerTemp();
registerJdkResolution({...request, source: 'sha256:first'}, release);
registerJdkResolution({...request, source: 'sha256:second'}, release);
const state = JSON.parse(
jest.mocked(core.saveState).mock.calls.at(-1)![1] as string
);
expect(new Set(state.map((item: {key: string}) => item.key)).size).toBe(
state.length
);
});
});
describe('saveJdkResolutionCaches', () => {
const stateFor = (cachePath: string) =>
JSON.stringify([
{
key: 'setup-java-jdkres-v2-key',
path: cachePath,
release: JSON.stringify(release)
}
]);
it('does nothing without state', async () => {
await saveJdkResolutionCaches();
expect(cache.saveCache).not.toHaveBeenCalled();
});
it('saves a recorded entry', async () => {
const root = createRunnerTemp();
jest.mocked(core.getState).mockReturnValue(stateFor(root));
await saveJdkResolutionCaches();
expect(cache.saveCache).toHaveBeenCalledWith(
[root],
'setup-java-jdkres-v2-key'
);
});
it('saves the payload the key was computed for, not the file on disk', async () => {
const root = createRunnerTemp();
jest.mocked(core.getState).mockReturnValue(stateFor(root));
// A restore performed by a later step replaces the file behind the key.
fs.writeFileSync(
path.join(root, 'release.json'),
JSON.stringify({version: '8.0.1+1', url: 'https://example.com/stale'})
);
await saveJdkResolutionCaches();
expect(
JSON.parse(fs.readFileSync(path.join(root, 'release.json'), 'utf8'))
).toEqual(release);
expect(cache.saveCache).toHaveBeenCalled();
});
it('does not fail the job when the payload cannot be written', async () => {
const root = createRunnerTemp();
const blocked = path.join(root, 'blocked');
fs.writeFileSync(blocked, 'not a directory');
jest.mocked(core.getState).mockReturnValue(stateFor(blocked));
await expect(saveJdkResolutionCaches()).resolves.toBeUndefined();
expect(cache.saveCache).not.toHaveBeenCalled();
});
it('does not fail the job when the save throws', async () => {
const root = createRunnerTemp();
jest.mocked(core.getState).mockReturnValue(stateFor(root));
jest
.mocked(cache.saveCache)
.mockRejectedValue(new Error('already reserved'));
await expect(saveJdkResolutionCaches()).resolves.toBeUndefined();
});
it('does not fail the job on invalid state', async () => {
jest.mocked(core.getState).mockReturnValue('{}');
await expect(saveJdkResolutionCaches()).resolves.toBeUndefined();
expect(cache.saveCache).not.toHaveBeenCalled();
});
});
});
+3 -1
View File
@@ -33,7 +33,8 @@ jest.unstable_mockModule('fs', () => ({
jest.unstable_mockModule('../src/util.js', () => ({
getBooleanInput: jest.fn(),
getVersionFromFileContent: jest.fn()
getVersionFromFileContent: jest.fn(),
isJdkCacheEnabled: jest.fn()
}));
jest.unstable_mockModule('../src/toolchains.js', () => ({
@@ -98,6 +99,7 @@ describe('setup-java conditional module loading', () => {
return booleanInputs.get(name as string) ?? defaultValue;
}
);
(util.isJdkCacheEnabled as jest.Mock).mockReturnValue(false);
(toolchains.configureToolchains as jest.Mock).mockResolvedValue(undefined);
});
+132 -2
View File
@@ -33,7 +33,8 @@ jest.unstable_mockModule('fs', () => ({
jest.unstable_mockModule('../src/util.js', () => ({
getBooleanInput: jest.fn(),
getVersionFromFileContent: jest.fn()
getVersionFromFileContent: jest.fn(),
isJdkCacheEnabled: jest.fn()
}));
jest.unstable_mockModule('../src/toolchains.js', () => ({
@@ -46,7 +47,8 @@ jest.unstable_mockModule('../src/toolchain-ids.js', () => ({
}));
jest.unstable_mockModule('../src/cache.js', () => ({
restore: jest.fn()
restore: jest.fn(),
validatePackageManager: jest.fn()
}));
jest.unstable_mockModule('../src/cache-feature.js', () => ({
@@ -113,6 +115,14 @@ describe('setup action orchestration', () => {
return booleanInputs.get(name as string) ?? defaultValue;
}
);
(util.isJdkCacheEnabled as jest.Mock).mockImplementation(
(cache: string) => {
const explicit = inputs.get('cache-jdk');
return explicit
? (booleanInputs.get('cache-jdk') ?? explicit === 'true')
: Boolean(cache);
}
);
(cacheFeature.isCacheFeatureAvailable as jest.Mock).mockReturnValue(true);
(toolchainIds.validateToolchainIds as jest.Mock).mockImplementation(
() => undefined
@@ -120,6 +130,9 @@ describe('setup action orchestration', () => {
(toolchains.configureToolchains as jest.Mock).mockResolvedValue(undefined);
(auth.configureAuthentication as jest.Mock).mockResolvedValue(undefined);
(cache.restore as jest.Mock).mockResolvedValue(undefined);
(cache.validatePackageManager as jest.Mock).mockImplementation(
() => undefined
);
});
it('does not execute the action when imported', () => {
@@ -217,6 +230,7 @@ describe('setup action orchestration', () => {
packageType: 'jdk',
checkLatest: true,
forceDownload: true,
cacheJdk: false,
setDefault: false,
verifySignature: true,
verifySignaturePublicKey: 'public-key'
@@ -457,6 +471,7 @@ describe('setup action orchestration', () => {
it('does not initialize cache modules when cache input is absent', async () => {
inputs.set('distribution', 'temurin');
multilineInputs.set('java-version', ['21']);
booleanInputs.set('cache-jdk', false);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({
setupJava: jest.fn(async () => ({
version: '21.0.4+7',
@@ -468,8 +483,82 @@ describe('setup action orchestration', () => {
expect(cacheFeature.isCacheFeatureAvailable).not.toHaveBeenCalled();
expect(cache.restore).not.toHaveBeenCalled();
expect(factory.getJavaDistribution).toHaveBeenCalledWith(
'temurin',
expect.objectContaining({cacheJdk: false}),
''
);
});
it('fails invalid cache input before resolving a Java distribution', async () => {
inputs.set('distribution', 'temurin');
inputs.set('cache', 'ant');
multilineInputs.set('java-version', ['21']);
const setupJava = jest.fn();
(factory.getJavaDistribution as jest.Mock).mockReturnValue({setupJava});
(cache.validatePackageManager as jest.Mock).mockImplementation(() => {
throw new Error('unknown package manager specified: ant');
});
await run();
expect(core.setFailed).toHaveBeenCalledWith(
'unknown package manager specified: ant'
);
expect(factory.getJavaDistribution).not.toHaveBeenCalled();
expect(setupJava).not.toHaveBeenCalled();
expect(cache.restore).not.toHaveBeenCalled();
});
it('reports missing java-version before validating the cache input', async () => {
inputs.set('distribution', 'temurin');
inputs.set('cache', 'ant');
(cache.validatePackageManager as jest.Mock).mockImplementation(() => {
throw new Error('unknown package manager specified: ant');
});
await run();
expect(core.setFailed).toHaveBeenCalledWith(
'java-version or java-version-file input expected'
);
expect(cache.validatePackageManager).not.toHaveBeenCalled();
});
it.each([
['', '', false],
['', 'true', true],
['', 'false', false],
['maven', '', true],
['maven', 'true', true],
['maven', 'false', false]
])(
'passes effective JDK caching for cache=%j and cache-jdk=%j',
async (cacheInput, cacheJdkInput, expected) => {
inputs.set('distribution', 'temurin');
inputs.set('cache', cacheInput);
inputs.set('cache-jdk', cacheJdkInput);
multilineInputs.set('java-version', ['21']);
if (cacheJdkInput) {
booleanInputs.set('cache-jdk', cacheJdkInput === 'true');
}
(factory.getJavaDistribution as jest.Mock).mockReturnValue({
setupJava: jest.fn(async () => ({
version: '21.0.4+7',
path: '/opt/java/21'
}))
});
await run();
expect(factory.getJavaDistribution).toHaveBeenCalledWith(
'temurin',
expect.objectContaining({cacheJdk: expected}),
''
);
}
);
it('reports unsupported distributions through core.setFailed', async () => {
inputs.set('distribution', 'unsupported');
multilineInputs.set('java-version', ['21']);
@@ -542,6 +631,47 @@ describe('setup action orchestration', () => {
expect(core.setFailed).toHaveBeenCalledWith('download failed');
});
it('observes cache failures while Java setup is still pending', async () => {
inputs.set('distribution', 'temurin');
inputs.set('cache', 'maven');
multilineInputs.set('java-version', ['21']);
const javaSetup = deferred<{version: string; path: string}>();
const setupJava = jest.fn(() => javaSetup.promise);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({setupJava});
const cacheRestore = deferred<void>();
const cacheRestoreCalled = deferred<void>();
(cache.restore as jest.Mock).mockImplementation(() => {
cacheRestoreCalled.resolve();
return cacheRestore.promise;
});
const unhandledRejections: unknown[] = [];
const onUnhandledRejection = (reason: unknown) => {
unhandledRejections.push(reason);
};
process.on('unhandledRejection', onUnhandledRejection);
const runPromise = run();
try {
// Only reject once the restore has actually started and while the Java
// installation is still pending, so the unfixed code would leave the
// rejection unhandled.
await cacheRestoreCalled.promise;
cacheRestore.reject(new Error('cache restore failed'));
await tick();
expect(setupJava).toHaveBeenCalled();
expect(unhandledRejections).toEqual([]);
expect(core.setFailed).not.toHaveBeenCalled();
} finally {
javaSetup.resolve({version: '21.0.4+7', path: '/opt/java/21'});
await runPromise;
process.off('unhandledRejection', onUnhandledRejection);
}
expect(unhandledRejections).toEqual([]);
expect(core.setFailed).toHaveBeenCalledWith('cache restore failed');
});
});
function deferred<T>() {
+520
View File
@@ -0,0 +1,520 @@
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
jest.unstable_mockModule('@actions/core', () => ({
debug: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
error: jest.fn(),
getInput: jest.fn(() => ''),
isDebug: jest.fn(() => false),
addPath: jest.fn(),
exportVariable: jest.fn(),
setOutput: jest.fn()
}));
jest.unstable_mockModule('@actions/tool-cache', () => ({
cacheDir: jest.fn(),
extractTar: jest.fn(),
extractZip: jest.fn(),
extract7z: jest.fn()
}));
jest.unstable_mockModule('@actions/exec', () => ({
exec: jest.fn()
}));
jest.unstable_mockModule('@actions/io', () => ({
which: jest.fn(),
rmRF: jest.fn(async (target: string) =>
fs.rmSync(target, {recursive: true, force: true})
),
mkdirP: jest.fn(async (target: string) =>
fs.mkdirSync(target, {recursive: true})
)
}));
jest.unstable_mockModule('@actions/http-client', () => ({
HttpClient: jest.fn(),
HttpClientError: class HttpClientError extends Error {}
}));
const tc = await import('@actions/tool-cache');
const exec = await import('@actions/exec');
const io = await import('@actions/io');
const {
cacheJdkDir,
extractJdkFile,
getArtifactFingerprint,
getJavaVersionFromReleaseFile
} = await import('../src/util.js');
const originalToolCache = process.env['RUNNER_TOOL_CACHE'];
const originalTemp = process.env['RUNNER_TEMP'];
const originalPlatform = process.platform;
let workDir: string;
function setPlatform(platform: NodeJS.Platform) {
Object.defineProperty(process, 'platform', {
value: platform,
configurable: true
});
}
beforeEach(() => {
workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-java-util-'));
process.env['RUNNER_TOOL_CACHE'] = path.join(workDir, 'toolcache');
process.env['RUNNER_TEMP'] = path.join(workDir, 'temp');
fs.mkdirSync(process.env['RUNNER_TEMP'], {recursive: true});
});
afterEach(() => {
jest.clearAllMocks();
setPlatform(originalPlatform);
while (lockedDirs.length) {
fs.chmodSync(lockedDirs.pop()!, 0o755);
}
fs.rmSync(workDir, {recursive: true, force: true});
if (originalToolCache === undefined) {
delete process.env['RUNNER_TOOL_CACHE'];
} else {
process.env['RUNNER_TOOL_CACHE'] = originalToolCache;
}
if (originalTemp === undefined) {
delete process.env['RUNNER_TEMP'];
} else {
process.env['RUNNER_TEMP'] = originalTemp;
}
});
function createJdkDir(name = 'jdk-source'): string {
const sourceDir = path.join(workDir, name);
fs.mkdirSync(path.join(sourceDir, 'bin'), {recursive: true});
fs.writeFileSync(path.join(sourceDir, 'bin', 'java'), 'binary');
fs.writeFileSync(path.join(sourceDir, 'release'), 'JAVA_VERSION="17"');
return sourceDir;
}
// A rename needs write permission on the source's parent directory, so making
// that parent read-only is a portable way to force the same failure a
// cross-device tool-cache (EXDEV) or a Windows anti-virus handle (EPERM) would.
// Root ignores the permission bits, so those tests are skipped there.
const canForceRenameFailure =
process.platform !== 'win32' &&
typeof process.getuid === 'function' &&
process.getuid() !== 0;
const itUnlessRoot = canForceRenameFailure ? it : it.skip;
const lockedDirs: string[] = [];
function createUnrenameableJdkDir(): string {
const parent = path.join(workDir, 'locked');
fs.mkdirSync(parent, {recursive: true});
const sourceDir = path.join(parent, 'jdk-source');
fs.mkdirSync(path.join(sourceDir, 'bin'), {recursive: true});
fs.writeFileSync(path.join(sourceDir, 'bin', 'java'), 'binary');
fs.chmodSync(parent, 0o555);
lockedDirs.push(parent);
return sourceDir;
}
describe('cacheJdkDir', () => {
it('moves the JDK into the tool-cache instead of copying it', async () => {
const sourceDir = createJdkDir();
const javaPath = await cacheJdkDir(
sourceDir,
'Java_temurin_jdk',
'17.0.1',
'x64'
);
expect(javaPath).toBe(
path.join(
process.env['RUNNER_TOOL_CACHE']!,
'Java_temurin_jdk',
'17.0.1',
'x64'
)
);
expect(fs.existsSync(path.join(javaPath, 'bin', 'java'))).toBe(true);
expect(fs.existsSync(path.join(javaPath, 'release'))).toBe(true);
// the source is moved, not copied, so it no longer exists
expect(fs.existsSync(sourceDir)).toBe(false);
expect(tc.cacheDir).not.toHaveBeenCalled();
});
it('writes the .complete marker expected by the tool-cache', async () => {
const javaPath = await cacheJdkDir(
createJdkDir(),
'Java_temurin_jdk',
'17.0.1',
'x64'
);
expect(fs.existsSync(`${javaPath}.complete`)).toBe(true);
});
it('replaces an existing tool-cache entry', async () => {
const destPath = path.join(
process.env['RUNNER_TOOL_CACHE']!,
'Java_temurin_jdk',
'17.0.1',
'x64'
);
fs.mkdirSync(destPath, {recursive: true});
fs.writeFileSync(path.join(destPath, 'stale'), 'stale');
const javaPath = await cacheJdkDir(
createJdkDir(),
'Java_temurin_jdk',
'17.0.1',
'x64'
);
expect(fs.existsSync(path.join(javaPath, 'stale'))).toBe(false);
expect(fs.existsSync(path.join(javaPath, 'bin', 'java'))).toBe(true);
});
it('normalizes the version the same way as tc.cacheDir', async () => {
const javaPath = await cacheJdkDir(
createJdkDir(),
'Java_temurin_jdk',
'v17.0.1',
'x64'
);
expect(path.basename(path.dirname(javaPath))).toBe('17.0.1');
});
it('keeps unparseable versions as-is', async () => {
const javaPath = await cacheJdkDir(
createJdkDir(),
'Java_temurin_jdk',
'17.0.1-ea.3',
'x64'
);
expect(path.basename(path.dirname(javaPath))).toBe('17.0.1-ea.3');
});
it('falls back to tc.cacheDir when the move fails', async () => {
(tc.cacheDir as jest.Mock).mockResolvedValue('/fallback/path' as never);
const missingDir = path.join(workDir, 'does-not-exist');
const javaPath = await cacheJdkDir(
missingDir,
'Java_temurin_jdk',
'17.0.1',
'x64'
);
expect(javaPath).toBe('/fallback/path');
expect(tc.cacheDir).toHaveBeenCalledWith(
missingDir,
'Java_temurin_jdk',
'17.0.1',
'x64'
);
});
itUnlessRoot(
'falls back to tc.cacheDir when the rename itself fails',
async () => {
const sourceDir = createUnrenameableJdkDir();
(tc.cacheDir as jest.Mock).mockResolvedValue('/fallback/path' as never);
await expect(
cacheJdkDir(sourceDir, 'Java_temurin_jdk', '17.0.1', 'x64')
).resolves.toBe('/fallback/path');
// the source must survive so the copy-based fallback can still read it
expect(fs.existsSync(path.join(sourceDir, 'bin', 'java'))).toBe(true);
}
);
itUnlessRoot(
'does not leave a .complete marker behind when the rename fails',
async () => {
const destPath = path.join(
process.env['RUNNER_TOOL_CACHE']!,
'Java_temurin_jdk',
'17.0.1',
'x64'
);
fs.mkdirSync(destPath, {recursive: true});
fs.writeFileSync(`${destPath}.complete`, '');
(tc.cacheDir as jest.Mock).mockResolvedValue('/fallback/path' as never);
await cacheJdkDir(
createUnrenameableJdkDir(),
'Java_temurin_jdk',
'17.0.1',
'x64'
);
// a stale marker without a matching installation would make the
// tool-cache resolve a directory that is no longer there
expect(fs.existsSync(`${destPath}.complete`)).toBe(false);
}
);
it('falls back to tc.cacheDir for symlinked sources', async () => {
const realDir = createJdkDir('real-jdk');
const linkDir = path.join(workDir, 'linked-jdk');
fs.symlinkSync(realDir, linkDir, 'dir');
(tc.cacheDir as jest.Mock).mockResolvedValue('/fallback/path' as never);
await expect(
cacheJdkDir(linkDir, 'Java_temurin_jdk', '17.0.1', 'x64')
).resolves.toBe('/fallback/path');
// moving the symlink itself would leave a dangling tool-cache entry
expect(fs.lstatSync(linkDir).isSymbolicLink()).toBe(true);
});
it('defaults the architecture the same way as tc.cacheDir', async () => {
const javaPath = await cacheJdkDir(
createJdkDir(),
'Java_temurin_jdk',
'17.0.1',
''
);
expect(javaPath).toBe(
path.join(
process.env['RUNNER_TOOL_CACHE']!,
'Java_temurin_jdk',
'17.0.1',
os.arch()
)
);
});
it('falls back to tc.cacheDir when the tool-cache location is unknown', async () => {
delete process.env['RUNNER_TOOL_CACHE'];
(tc.cacheDir as jest.Mock).mockResolvedValue('/fallback/path' as never);
await expect(
cacheJdkDir(createJdkDir(), 'Java_temurin_jdk', '17.0.1', 'x64')
).resolves.toBe('/fallback/path');
});
});
describe('getJavaVersionFromReleaseFile', () => {
it.each([
['JAVA_RUNTIME_VERSION="21.0.9+7-LTS-123"', '21.0.9+7'],
['JAVA_RUNTIME_VERSION="17.0.12+8-jvmci-23.1-b52"', '17.0.12+8'],
['JAVA_RUNTIME_VERSION="25+36-LTS"', '25.0.0+36'],
['JAVA_VERSION="25.0.1"', '25.0.1'],
['JAVA_VERSION="25"', '25.0.0']
])('reads a concrete version from %s', (contents, expected) => {
const javaHome = createJdkDir();
fs.writeFileSync(path.join(javaHome, 'release'), contents);
expect(getJavaVersionFromReleaseFile(javaHome)).toBe(expected);
});
it('reads the macOS Contents/Home release file', () => {
const javaHome = path.join(workDir, 'macos-jdk');
fs.mkdirSync(path.join(javaHome, 'Contents', 'Home'), {recursive: true});
fs.writeFileSync(
path.join(javaHome, 'Contents', 'Home', 'release'),
'JAVA_RUNTIME_VERSION="21.0.9+7-LTS"'
);
expect(getJavaVersionFromReleaseFile(javaHome)).toBe('21.0.9+7');
});
it('fails when the JDK release metadata has no usable version', () => {
const javaHome = createJdkDir();
fs.writeFileSync(path.join(javaHome, 'release'), 'IMPLEMENTOR="Oracle"');
expect(() => getJavaVersionFromReleaseFile(javaHome)).toThrow(
/Unable to determine the installed Java version/
);
});
});
describe('extractJdkFile', () => {
it('uses pigz for tarballs when it is available', async () => {
(io.which as jest.Mock).mockResolvedValue('/usr/bin/pigz' as never);
(tc.extractTar as jest.Mock).mockResolvedValue('/extracted' as never);
await expect(extractJdkFile('/tmp/jdk.tar.gz')).resolves.toBe('/extracted');
expect(tc.extractTar).toHaveBeenCalledWith(
'/tmp/jdk.tar.gz',
expect.stringContaining(process.env['RUNNER_TEMP']!),
['--use-compress-program', '/usr/bin/pigz -d', '-x']
);
});
it('falls back to gzip when pigz is not installed', async () => {
(io.which as jest.Mock).mockResolvedValue('' as never);
(tc.extractTar as jest.Mock).mockResolvedValue('/extracted' as never);
await expect(extractJdkFile('/tmp/jdk.tar.gz')).resolves.toBe('/extracted');
expect(tc.extractTar).toHaveBeenCalledWith('/tmp/jdk.tar.gz');
});
it('falls back to gzip when pigz extraction fails', async () => {
(io.which as jest.Mock).mockResolvedValue('/usr/bin/pigz' as never);
(tc.extractTar as jest.Mock)
.mockRejectedValueOnce(new Error('pigz exploded') as never)
.mockResolvedValue('/extracted' as never);
await expect(extractJdkFile('/tmp/jdk.tar.gz')).resolves.toBe('/extracted');
expect(tc.extractTar).toHaveBeenNthCalledWith(2, '/tmp/jdk.tar.gz');
});
it('cleans up the abandoned folder when pigz extraction fails', async () => {
(io.which as jest.Mock).mockResolvedValue('/usr/bin/pigz' as never);
let pigzDest: string | undefined;
(tc.extractTar as jest.Mock)
.mockImplementationOnce((...args: unknown[]) => {
pigzDest = args[1] as string;
throw new Error('pigz exploded');
})
.mockResolvedValue('/extracted' as never);
await extractJdkFile('/tmp/jdk.tar.gz');
expect(pigzDest).toBeDefined();
expect(fs.existsSync(pigzDest!)).toBe(false);
});
it('ignores pigz when its path contains whitespace', async () => {
(io.which as jest.Mock).mockResolvedValue(
'C:\\Program Files\\pigz.exe' as never
);
(tc.extractTar as jest.Mock).mockResolvedValue('/extracted' as never);
await extractJdkFile('/tmp/jdk.tar.gz');
// tar word-splits --use-compress-program, so a spaced path is unusable
expect(tc.extractTar).toHaveBeenCalledWith('/tmp/jdk.tar.gz');
});
it('leaves uncompressed tarballs on the default extraction path', async () => {
(tc.extractTar as jest.Mock).mockResolvedValue('/extracted' as never);
await expect(extractJdkFile('/tmp/jdk.tar')).resolves.toBe('/extracted');
expect(tc.extractTar).toHaveBeenCalledWith('/tmp/jdk.tar');
expect(io.which).not.toHaveBeenCalled();
});
it('extracts xz-compressed tarballs with xz tar flags', async () => {
(tc.extractTar as jest.Mock).mockResolvedValue('/extracted' as never);
await expect(extractJdkFile('/tmp/jdk.tar.xz')).resolves.toBe('/extracted');
expect(tc.extractTar).toHaveBeenCalledWith(
'/tmp/jdk.tar.xz',
undefined,
'xJ'
);
expect(io.which).not.toHaveBeenCalled();
});
it('uses the bundled tar.exe for zip archives on Windows', async () => {
setPlatform('win32');
const systemRoot = path.join(workDir, 'Windows');
fs.mkdirSync(path.join(systemRoot, 'System32'), {recursive: true});
const systemTar = path.join(systemRoot, 'System32', 'tar.exe');
fs.writeFileSync(systemTar, '');
process.env['SystemRoot'] = systemRoot;
const javaPath = await extractJdkFile('/tmp/jdk.zip');
expect(tc.extractZip).not.toHaveBeenCalled();
expect(exec.exec).toHaveBeenCalledWith(
`"${systemTar}"`,
['-xf', '/tmp/jdk.zip', '-C', javaPath],
{silent: true}
);
expect(fs.existsSync(javaPath)).toBe(true);
});
it('falls back to tc.extractZip when tar.exe fails', async () => {
setPlatform('win32');
const systemRoot = path.join(workDir, 'Windows');
fs.mkdirSync(path.join(systemRoot, 'System32'), {recursive: true});
fs.writeFileSync(path.join(systemRoot, 'System32', 'tar.exe'), '');
process.env['SystemRoot'] = systemRoot;
let tarDest: string | undefined;
(exec.exec as jest.Mock).mockImplementation((...args: unknown[]) => {
tarDest = (args[1] as string[])[3];
throw new Error('boom');
});
(tc.extractZip as jest.Mock).mockResolvedValue('/extracted' as never);
await expect(extractJdkFile('/tmp/jdk.zip')).resolves.toBe('/extracted');
expect(tarDest).toBeDefined();
expect(fs.existsSync(tarDest!)).toBe(false);
});
it('uses tc.extractZip on non-Windows platforms', async () => {
setPlatform('linux');
(tc.extractZip as jest.Mock).mockResolvedValue('/extracted' as never);
await expect(extractJdkFile('/tmp/jdk.zip')).resolves.toBe('/extracted');
expect(exec.exec).not.toHaveBeenCalled();
});
});
describe('getArtifactFingerprint', () => {
it('prefers the ETag over the other validators', () => {
expect(
getArtifactFingerprint({
etag: '"abc123"',
'last-modified': 'Wed, 21 Oct 2026 07:28:00 GMT',
'content-length': '195000000'
})
).toBe('etag:"abc123"');
});
it('combines the last-modified date and the content length without an ETag', () => {
expect(
getArtifactFingerprint({
'last-modified': 'Wed, 21 Oct 2026 07:28:00 GMT',
'content-length': '195000000'
})
).toBe('mtime:Wed, 21 Oct 2026 07:28:00 GMT;length:195000000');
});
it.each([
['no validators', {}],
[
'only a last-modified date',
{'last-modified': 'Wed, 21 Oct 2026 07:28:00 GMT'}
],
['only a content length', {'content-length': '195000000'}],
[
'blank validators',
{etag: ' ', 'last-modified': '', 'content-length': ''}
],
['missing headers', undefined]
])('returns undefined for %s', (_label, headers) => {
expect(getArtifactFingerprint(headers)).toBeUndefined();
});
it('uses the first value of a repeated header', () => {
expect(getArtifactFingerprint({etag: ['"first"', '"second"'] as any})).toBe(
'etag:"first"'
);
});
it('distinguishes a republished artifact from the previous one', () => {
const before = getArtifactFingerprint({
'last-modified': 'Wed, 21 Oct 2026 07:28:00 GMT',
'content-length': '195000000'
});
const after = getArtifactFingerprint({
'last-modified': 'Thu, 22 Oct 2026 09:03:00 GMT',
'content-length': '195400000'
});
expect(before).not.toBe(after);
});
});
+34 -1
View File
@@ -49,7 +49,8 @@ const {
isGhes,
validatePaginationUrl,
getLatestMajorVersion,
getBooleanInput
getBooleanInput,
isJdkCacheEnabled
} = await import('../src/util.js');
describe('getBooleanInput', () => {
@@ -115,6 +116,37 @@ describe('getBooleanInput', () => {
});
});
describe('isJdkCacheEnabled', () => {
let inputs: Record<string, string>;
beforeEach(() => {
inputs = {};
(core.getInput as jest.Mock).mockImplementation(
(name: string) => inputs[name] ?? ''
);
});
afterEach(() => {
jest.resetAllMocks();
});
it.each([
['', '', false],
['', 'true', true],
['', 'false', false],
['maven', '', true],
['maven', 'true', true],
['maven', 'false', false]
])(
'resolves cache=%j and cache-jdk=%j to %s',
(cache, cacheJdk, expected) => {
inputs['cache-jdk'] = cacheJdk;
expect(isJdkCacheEnabled(cache)).toBe(expected);
}
);
});
describe('isVersionSatisfies', () => {
it.each([
['x', '11.0.0', true],
@@ -231,6 +263,7 @@ describe('validatePaginationUrl', () => {
describe('getVersionFromFileContent', () => {
describe('.sdkmanrc', () => {
it.each([
['java=26-tem', '26', 'temurin'],
['java=11.0.20.1-tem', '11.0.20', 'temurin'],
['java = 11.0.20.1-tem', '11.0.20', 'temurin'],
['java=11.0.20.1-tem # a comment in sdkmanrc', '11.0.20', 'temurin'],
+20
View File
@@ -12,6 +12,8 @@ fi
EXPECTED_JAVA_VERSION=$1
EXPECTED_PATH=$2
SETUP_JAVA_VERSION=$3
REQUIRE_CONCRETE_VERSION=$4
EXPECTED_JAVA_VERSION=$(echo $EXPECTED_JAVA_VERSION | cut -d'+' -f1)
if [[ $EXPECTED_JAVA_VERSION == 8 ]] || [[ $EXPECTED_JAVA_VERSION == 8.* ]]; then
@@ -31,6 +33,24 @@ if [ -z "$GREP_RESULT" ]; then
exit 1
fi
if [ -n "$SETUP_JAVA_VERSION" ]; then
OUTPUT_JAVA_VERSION=$(echo "$SETUP_JAVA_VERSION" | cut -d'+' -f1)
if [[ $OUTPUT_JAVA_VERSION == *-ea* ]]; then
OUTPUT_JAVA_VERSION=$(echo "$OUTPUT_JAVA_VERSION" | cut -d'-' -f1 | cut -d'.' -f1)
fi
OUTPUT_GREP_RESULT=$(echo "$ACTUAL_JAVA_VERSION" | grep -E "^(openjdk|java) version \"$OUTPUT_JAVA_VERSION")
if [ -z "$OUTPUT_GREP_RESULT" ]; then
echo "::error::The version output does not match the installed Java version"
echo "Version output: $SETUP_JAVA_VERSION"
exit 1
fi
if [ "$REQUIRE_CONCRETE_VERSION" = "true" ] && [ "$OUTPUT_JAVA_VERSION" = "$EXPECTED_JAVA_VERSION" ]; then
echo "::error::Expected a concrete version output for a floating JDK"
echo "Version output: $SETUP_JAVA_VERSION"
exit 1
fi
fi
if [ "$EXPECTED_PATH" != "$JAVA_HOME" ]; then
echo "::error::Unexpected path"
echo "Actual path: $JAVA_HOME"
+20 -3
View File
@@ -64,6 +64,20 @@ inputs:
server-password:
description: 'Deprecated alias for server-password-env-var'
required: false
mvn-server-credentials:
description: 'Multiline list of Maven server credentials in the format `server-id:USERNAME_ENV:PASSWORD_ENV`. When set, replaces the single server configured by server-id, server-username-env-var, and server-password-env-var.'
required: false
mvn-repositories:
description: 'Multiline list of Maven dependency repositories in the format `repository-id:repository-url:snapshots-enabled`.'
required: false
mvn-repositories-include-central:
description: 'Include Maven Central in the generated dependency repositories profile. When false, Central is disabled unless an explicit repository with ID `central` is declared.'
required: false
default: true
mvn-repositories-prioritize-central:
description: 'Place Maven Central before custom dependency repositories. Has no effect when Maven Central is excluded.'
required: false
default: true
settings-path:
description: 'Path to where the settings.xml file will be written. Default is ~/.m2.'
required: false
@@ -72,7 +86,7 @@ inputs:
required: false
default: true
gpg-private-key:
description: 'GPG private key to import. Default is empty string.'
description: 'GPG private key to import into an isolated temporary keyring. Default is empty string.'
required: false
default: ''
gpg-passphrase-env-var:
@@ -84,6 +98,9 @@ inputs:
cache:
description: 'Name of the build platform to cache dependencies. It can be "maven", "gradle" or "sbt".'
required: false
cache-jdk:
description: 'Cache downloaded JDK installations between jobs. Defaults to enabled when dependency caching is configured with `cache`; set explicitly to "true" or "false" to override.'
required: false
cache-dependency-path:
description: 'The path to a dependency file: pom.xml, build.gradle, build.sbt, etc. This option can be used with the `cache` option. If this option is omitted, the action searches for the dependency file in the entire repository. This option supports wildcards and a list of file names for caching multiple dependencies.'
required: false
@@ -91,7 +108,7 @@ inputs:
description: 'The path to cache instead of the default dependency cache path for the selected package manager. This option can be used with the `cache` option and supports a list of paths and exclusion patterns.'
required: false
cache-read-only:
description: 'Restore dependency caches without saving cache changes in the post action.'
description: 'Restore caches without saving cache changes in the post action.'
required: false
default: false
job-status:
@@ -103,7 +120,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. When supplied, the number of IDs must match the number of Java versions. See examples of supported syntax in Advanced Usage file'
description: 'Name of Maven Toolchain ID if the default name of "${mvn-toolchain-vendor}_${java-version}" is not wanted. The toolchain vendor defaults to the "distribution" input. 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'
+224
View File
@@ -0,0 +1,224 @@
export const id = 314;
export const ids = [314];
export const modules = {
/***/ 2314:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
saveJdkCaches: () => (/* binding */ saveJdkCaches)
});
// UNUSED EXPORTS: buildJdkCacheKey, getJdkVerificationIdentity, registerJdk, restoreJdk
// EXTERNAL MODULE: external "crypto"
var external_crypto_ = __webpack_require__(6982);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(9896);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(6928);
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_);
// EXTERNAL MODULE: ./node_modules/@actions/cache/lib/cache.js + 291 modules
var lib_cache = __webpack_require__(5767);
// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js + 7 modules
var lib_core = __webpack_require__(3838);
// EXTERNAL MODULE: ./src/util.ts
var util = __webpack_require__(4527);
;// CONCATENATED MODULE: ./src/cache-feature.ts
function cache_feature_isCacheFeatureAvailable() {
if (cache.isFeatureAvailable()) {
return true;
}
if (isGhes()) {
core.warning('Caching is only supported on GHES version >= 3.5. If you are on a version >= 3.5, please check with your GHES admin if the Actions cache service is enabled or not.');
return false;
}
core.warning('The runner was not able to contact the cache service. Caching will be skipped');
return false;
}
;// CONCATENATED MODULE: ./src/jdk-cache.ts
const STATE_JDK_CACHES = 'jdk-caches';
const JDK_CACHE_KEY_VERSION = 1;
const restoredCaches = (/* unused pure expression or super */ null && ([]));
async function restoreJdk(jdk) {
if (!jdk.path || !isCacheFeatureAvailable()) {
return false;
}
const key = buildJdkCacheKey(jdk);
let matchedKey;
try {
matchedKey = await cache.restoreCache([jdk.path], key);
}
catch (error) {
core.warning(`Failed to restore JDK cache: ${error.message}`);
}
const architecturePath = path.join(jdk.path, jdk.architecture);
if (matchedKey &&
(!fs.existsSync(architecturePath) ||
!fs.existsSync(`${architecturePath}.complete`))) {
core.warning(`JDK cache key ${matchedKey} was restored without the expected tool-cache path; downloading the JDK instead.`);
matchedKey = undefined;
}
recordJdkCache({
key,
path: jdk.path,
architecture: jdk.architecture,
matchedKey
});
if (matchedKey) {
core.info(`JDK cache restored from key: ${matchedKey}`);
return true;
}
core.info(`JDK cache is not found for ${jdk.distribution} ${jdk.version}`);
return false;
}
function registerJdk(jdk) {
if (!jdk.path) {
return;
}
recordJdkCache({
key: buildJdkCacheKey(jdk),
path: jdk.path,
architecture: jdk.architecture,
installation: getInstallationIdentity(jdk.path, jdk.architecture)
});
}
/**
* Cheap fingerprint of the installation stored at a tool-cache path. The
* `<architecture>.complete` marker is (re)created by `tc.cacheDir` every time an
* installation is written, so its inode and timestamps change whenever the
* installation is replaced. This avoids rehashing a multi-hundred-megabyte JDK
* directory while still detecting that the bytes behind a key were swapped.
*/
function getInstallationIdentity(jdkPath, architecture) {
const architecturePath = external_path_default().join(jdkPath, architecture);
try {
const marker = external_fs_default().statSync(`${architecturePath}.complete`);
const installation = external_fs_default().statSync(architecturePath);
return [
marker.ino,
marker.mtimeMs,
marker.ctimeMs,
marker.size,
installation.ino,
installation.mtimeMs,
installation.ctimeMs
].join(':');
}
catch {
return undefined;
}
}
function getJdkVerificationIdentity(verifySignature, publicKey) {
if (!verifySignature) {
return 'unverified';
}
if (!publicKey) {
return 'verified:bundled';
}
const normalizedKey = publicKey.replace(/\r\n?/g, '\n').trim();
const fingerprint = createHash('sha256').update(normalizedKey).digest('hex');
return `verified:custom:sha256:${fingerprint}`;
}
async function saveJdkCaches() {
const state = lib_core/* getState */.Gu(STATE_JDK_CACHES);
if (!state) {
return;
}
const caches = parseJdkCacheState(state);
for (const jdk of caches) {
if (jdk.matchedKey === jdk.key) {
lib_core/* info */.pq(`Cache hit occurred on the JDK primary key ${jdk.key}, not saving cache.`);
continue;
}
if (!external_fs_default().existsSync(jdk.path)) {
lib_core/* debug */.Yz(`JDK cache path does not exist, not saving: ${jdk.path}`);
continue;
}
if (!jdk.installation) {
lib_core/* debug */.Yz(`No JDK installation was registered for the key ${jdk.key}, not saving cache.`);
continue;
}
if (getInstallationIdentity(jdk.path, jdk.architecture) !== jdk.installation) {
lib_core/* warning */.$e(`The JDK installation in ${jdk.path} was replaced after it was registered for the key ${jdk.key}; not saving cache.`);
continue;
}
try {
const cacheId = await lib_cache/* saveCache */.Io([jdk.path], jdk.key);
if (cacheId !== -1) {
lib_core/* info */.pq(`JDK cache saved with the key: ${jdk.key}`);
}
}
catch (error) {
const err = error;
if (err.name === lib_cache/* ReserveCacheError */.Zh.name) {
lib_core/* info */.pq(err.message);
}
else {
// Saving is best-effort and per entry: one failure must not suppress
// the remaining JDK caches.
lib_core/* warning */.$e(`Failed to save the JDK cache with the key ${jdk.key}: ${err.message}`);
}
}
}
}
function buildJdkCacheKey(jdk) {
const runnerOs = process.env['RUNNER_OS'] ?? process.platform;
const normalizedArchitecture = jdk.architecture.toLowerCase();
const identity = JSON.stringify({
keyVersion: JDK_CACHE_KEY_VERSION,
runnerOs,
distribution: jdk.distribution.toLowerCase(),
packageType: jdk.packageType.toLowerCase(),
architecture: normalizedArchitecture,
version: jdk.version,
source: jdk.source,
verification: jdk.verification
});
const digest = createHash('sha256').update(identity).digest('hex');
return `setup-java-jdk-v${JDK_CACHE_KEY_VERSION}-${runnerOs}-${normalizedArchitecture}-${digest}`;
}
function recordJdkCache(jdk) {
const existing = restoredCaches.findIndex(item => item.key === jdk.key && item.path === jdk.path);
if (existing === -1) {
restoredCaches.push(jdk);
}
else {
restoredCaches[existing] = { ...restoredCaches[existing], ...jdk };
}
core.saveState(STATE_JDK_CACHES, JSON.stringify(restoredCaches));
}
function parseJdkCacheState(state) {
const value = JSON.parse(state);
if (!Array.isArray(value) ||
!value.every(item => typeof item === 'object' &&
item !== null &&
typeof item.key === 'string' &&
typeof item.path === 'string' &&
typeof item.architecture === 'string' &&
(item.matchedKey === undefined ||
typeof item.matchedKey === 'string') &&
(item.installation === undefined ||
typeof item.installation === 'string'))) {
throw new Error('Invalid JDK cache information retrieved from state.');
}
return value;
}
/***/ })
};
+279
View File
@@ -0,0 +1,279 @@
export const id = 348;
export const ids = [348];
export const modules = {
/***/ 967:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ saveJdkResolutionCaches: () => (/* binding */ saveJdkResolutionCaches)
/* harmony export */ });
/* unused harmony exports restoreJdkResolution, registerJdkResolution */
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _actions_cache__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5767);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3838);
const STATE_JDK_RESOLUTIONS = 'jdk-resolutions';
const JDK_RESOLUTION_KEY_VERSION = 2;
const RESOLUTION_DIRECTORY = 'setup-java-jdk-resolution';
const RESOLUTION_FILE_NAME = 'release.json';
const pendingResolutions = (/* unused pure expression or super */ null && ([]));
/**
* Restores a previously resolved release so a distribution can skip its vendor
* metadata API.
*
* The cache path deliberately excludes the freshness window: `@actions/cache`
* derives
* a cache version by hashing the requested paths, so a bucket-independent path
* is what allows the restore keys to fall back to an older bucket.
*/
async function restoreJdkResolution(request) {
// Deliberately not `isCacheFeatureAvailable()`: this is an optional
// optimization, and the JDK cache already warns once when the service is
// unreachable.
if (!cache.isFeatureAvailable()) {
return undefined;
}
const cachePath = getResolutionCachePath(request);
if (!cachePath) {
return undefined;
}
const keyPrefix = getResolutionKeyPrefix(request);
const primaryKey = `${keyPrefix}${getFreshnessBucket()}`;
let matchedKey;
try {
matchedKey = await cache.restoreCache([cachePath], primaryKey, [keyPrefix]);
}
catch (error) {
core.debug(`Failed to restore the JDK resolution cache: ${getErrorMessage(error)}`);
return undefined;
}
if (!matchedKey) {
return undefined;
}
let release;
try {
const contents = fs.readFileSync(path.join(cachePath, RESOLUTION_FILE_NAME), 'utf8');
release = parseResolvedRelease(contents);
}
catch (error) {
core.debug(`Ignoring the JDK resolution cache entry ${matchedKey}: ${getErrorMessage(error)}`);
return undefined;
}
return { release, fresh: matchedKey === primaryKey };
}
/**
* Persists a freshly resolved release for later jobs. The entry is written to
* disk immediately and uploaded by the post-job step.
*/
function registerJdkResolution(request, release) {
if (!cache.isFeatureAvailable()) {
return;
}
const cachePath = getResolutionCachePath(request);
if (!cachePath) {
return;
}
const payload = JSON.stringify(release);
try {
fs.mkdirSync(cachePath, { recursive: true });
fs.writeFileSync(path.join(cachePath, RESOLUTION_FILE_NAME), payload);
}
catch (error) {
core.debug(`Failed to record the JDK resolution cache entry: ${getErrorMessage(error)}`);
return;
}
const key = `${getResolutionKeyPrefix(request)}${getFreshnessBucket()}`;
if (!pendingResolutions.some(item => item.key === key)) {
pendingResolutions.push({ key, path: cachePath, release: payload });
}
core.saveState(STATE_JDK_RESOLUTIONS, JSON.stringify(pendingResolutions));
}
async function saveJdkResolutionCaches() {
const state = _actions_core__WEBPACK_IMPORTED_MODULE_4__/* .getState */ .Gu(STATE_JDK_RESOLUTIONS);
if (!state) {
return;
}
let resolutions;
try {
resolutions = parseJdkResolutionState(state);
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Invalid JDK resolution cache state, not saving: ${getErrorMessage(error)}`);
return;
}
for (const resolution of resolutions) {
// A restore performed by a later step overwrites this path, so the payload
// the key was computed for is written again rather than trusted to still be
// on disk.
try {
fs__WEBPACK_IMPORTED_MODULE_1___default().mkdirSync(resolution.path, { recursive: true });
fs__WEBPACK_IMPORTED_MODULE_1___default().writeFileSync(path__WEBPACK_IMPORTED_MODULE_2___default().join(resolution.path, RESOLUTION_FILE_NAME), resolution.release);
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Failed to write the JDK resolution cache entry for the key ${resolution.key}: ${getErrorMessage(error)}`);
continue;
}
try {
await _actions_cache__WEBPACK_IMPORTED_MODULE_3__/* .saveCache */ .Io([resolution.path], resolution.key);
}
catch (error) {
// A matrix of jobs resolving the same JDK races on the same daily key, so
// an already-reserved key is the expected outcome rather than a problem.
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Failed to save the JDK resolution cache with the key ${resolution.key}: ${getErrorMessage(error)}`);
}
}
}
function getResolutionCachePath(request) {
const runnerTemp = process.env['RUNNER_TEMP'];
if (!runnerTemp) {
return undefined;
}
return path.join(runnerTemp, RESOLUTION_DIRECTORY, getResolutionIdentity(request));
}
function getResolutionIdentity(request) {
const identity = JSON.stringify({
keyVersion: JDK_RESOLUTION_KEY_VERSION,
runnerOs: getRunnerOs(),
distribution: request.distribution.toLowerCase(),
packageType: request.packageType.toLowerCase(),
platform: request.platform.toLowerCase(),
architecture: request.architecture.toLowerCase(),
versionSpec: request.versionSpec,
stable: request.stable,
source: request.source
});
return createHash('sha256').update(identity).digest('hex');
}
function getResolutionKeyPrefix(request) {
const architecture = request.architecture.toLowerCase();
const digest = getResolutionIdentity(request);
return `setup-java-jdkres-v${JDK_RESOLUTION_KEY_VERSION}-${getRunnerOs()}-${architecture}-${digest}-`;
}
function getRunnerOs() {
return process.env['RUNNER_OS'] ?? process.platform;
}
/**
* Start of the seven-day window the entry was resolved in, which bounds how long
* a floating version spec such as `21` can keep resolving to an already known
* release.
*
* Seven days is the longest usable window: GitHub evicts cache entries that have
* not been accessed for seven days, so a longer one would mean the previous
* entry is already gone when the window rolls over, taking the stale-fallback
* path with it. It also comfortably covers the real release cadence, which is
* monthly at its fastest and usually quarterly.
*/
function getFreshnessBucket() {
const week = 7 * 24 * 60 * 60 * 1000;
return new Date(Math.floor(Date.now() / week) * week)
.toISOString()
.slice(0, 10);
}
/**
* The restored payload drives a download, so it is validated as untrusted input
* rather than trusted because it came back from the cache service.
*/
function parseResolvedRelease(contents) {
const value = JSON.parse(contents);
if (typeof value !== 'object' || value === null) {
throw new Error('The cached resolution is not an object.');
}
const candidate = value;
const version = candidate['version'];
const url = candidate['url'];
const signatureUrl = candidate['signatureUrl'];
const floating = candidate['floating'];
if (typeof version !== 'string' || !version) {
throw new Error('The cached resolution has no version.');
}
assertHttpsUrl(url, 'url');
if (signatureUrl !== undefined) {
assertHttpsUrl(signatureUrl, 'signatureUrl');
}
if (floating !== undefined && typeof floating !== 'boolean') {
throw new Error('The cached resolution has an invalid floating flag.');
}
const release = {
version,
url: url
};
if (signatureUrl !== undefined) {
release.signatureUrl = signatureUrl;
}
if (floating !== undefined) {
release.floating = floating;
}
const checksum = candidate['checksum'];
if (checksum !== undefined) {
release.checksum = parseChecksum(checksum);
}
return release;
}
function parseChecksum(value) {
if (typeof value !== 'object' || value === null) {
throw new Error('The cached checksum is not an object.');
}
const candidate = value;
const algorithm = candidate['algorithm'];
const checksumValue = candidate['value'];
const source = candidate['source'];
if (algorithm !== 'sha256' && algorithm !== 'sha512') {
throw new Error(`Unsupported cached checksum algorithm: ${algorithm}`);
}
if (typeof checksumValue !== 'string' || !checksumValue) {
throw new Error('The cached checksum has no value.');
}
if (source !== undefined && typeof source !== 'string') {
throw new Error('The cached checksum source is not a string.');
}
const checksum = { algorithm, value: checksumValue };
if (source !== undefined) {
checksum.source = source;
}
return checksum;
}
function assertHttpsUrl(value, field) {
if (typeof value !== 'string' || !value) {
throw new Error(`The cached resolution has no ${field}.`);
}
let parsed;
try {
parsed = new URL(value);
}
catch {
throw new Error(`The cached resolution has a malformed ${field}.`);
}
if (parsed.protocol !== 'https:') {
throw new Error(`The cached resolution ${field} does not use HTTPS: ${parsed.protocol}`);
}
}
function parseJdkResolutionState(state) {
const value = JSON.parse(state);
if (!Array.isArray(value) ||
!value.every(item => typeof item === 'object' &&
item !== null &&
typeof item.key === 'string' &&
typeof item.path === 'string' &&
typeof item.release === 'string')) {
throw new Error('Invalid JDK resolution information retrieved from state.');
}
return value;
}
function getErrorMessage(error) {
return error instanceof Error ? error.message : String(error);
}
/***/ })
};
+5 -1
View File
@@ -8,7 +8,7 @@ export const modules = {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ save: () => (/* binding */ save)
/* harmony export */ });
/* unused harmony export restore */
/* unused harmony exports validatePackageManager, restore */
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(857);
@@ -56,6 +56,7 @@ const supportedPackageManager = [
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---gradle
pattern: [
'**/*.gradle*',
'**/gradle.properties',
'**/gradle-wrapper.properties',
'buildSrc/**/Versions.kt',
'buildSrc/**/Dependencies.kt',
@@ -107,6 +108,9 @@ function findPackageManager(id) {
}
return packageManager;
}
function validatePackageManager(id) {
findPackageManager(id);
}
function resolveCachePaths(packageManager, cachePaths) {
return cachePaths.length > 0 ? cachePaths : packageManager.path;
}
+61350
View File
File diff suppressed because it is too large Load Diff
+360
View File
@@ -0,0 +1,360 @@
export const id = 758;
export const ids = [758];
export const modules = {
/***/ 7377:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ save: () => (/* binding */ save)
/* harmony export */ });
/* unused harmony exports validatePackageManager, restore */
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(857);
/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _actions_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* harmony import */ var _actions_glob__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2377);
/**
* @fileoverview this file provides methods handling dependency cache
*/
const STATE_CACHE_PRIMARY_KEY = 'cache-primary-key';
const STATE_CACHE_PATHS = 'cache-paths';
const CACHE_MATCHED_KEY = 'cache-matched-key';
const CACHE_KEY_PREFIX = 'setup-java';
const supportedPackageManager = [
{
id: 'maven',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.m2', 'repository')],
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---maven
pattern: [
'**/pom.xml',
'**/.mvn/wrapper/maven-wrapper.properties',
'**/.mvn/extensions.xml'
],
// The Maven wrapper distribution only depends on the wrapper properties,
// which change very rarely, so it is cached separately from the local
// repository. This keeps it available across the frequent pom.xml changes
// that rotate the main cache key. See issue #1095.
additionalCaches: [
{
name: 'maven-wrapper',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.m2', 'wrapper', 'dists')],
pattern: ['**/.mvn/wrapper/maven-wrapper.properties']
}
]
},
{
id: 'gradle',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.gradle', 'caches')],
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---gradle
pattern: [
'**/*.gradle*',
'**/gradle.properties',
'**/gradle-wrapper.properties',
'buildSrc/**/Versions.kt',
'buildSrc/**/Dependencies.kt',
'gradle/*.versions.toml',
'**/versions.properties'
],
// The Gradle wrapper distribution only depends on the wrapper properties,
// which change very rarely, so it is cached separately from the Gradle
// caches. This keeps it available across the frequent *.gradle* changes
// that rotate the main cache key. See issue #269.
additionalCaches: [
{
name: 'gradle-wrapper',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.gradle', 'wrapper')],
pattern: ['**/gradle-wrapper.properties']
}
]
},
{
id: 'sbt',
path: [
(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.ivy2', 'cache'),
(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.sbt'),
getCoursierCachePath(),
// Some files should not be cached to avoid resolution problems.
// In particular the resolution of snapshots (ideological gap between maven/ivy).
'!' + (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.sbt', '*.lock'),
'!' + (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '**', 'ivydata-*.properties')
],
pattern: [
'**/*.sbt',
'**/project/build.properties',
'**/project/**.scala',
'**/project/**.sbt'
]
}
];
function getCoursierCachePath() {
if (os__WEBPACK_IMPORTED_MODULE_1___default().type() === 'Linux')
return (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.cache', 'coursier');
if (os__WEBPACK_IMPORTED_MODULE_1___default().type() === 'Darwin')
return (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), 'Library', 'Caches', 'Coursier');
return (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), 'AppData', 'Local', 'Coursier', 'Cache');
}
function findPackageManager(id) {
const packageManager = supportedPackageManager.find(packageManager => packageManager.id === id);
if (packageManager === undefined) {
throw new Error(`unknown package manager specified: ${id}`);
}
return packageManager;
}
function validatePackageManager(id) {
findPackageManager(id);
}
function resolveCachePaths(packageManager, cachePaths) {
return cachePaths.length > 0 ? cachePaths : packageManager.path;
}
function getCachePathsFromState(packageManager) {
const cachePathsState = _actions_core__WEBPACK_IMPORTED_MODULE_3__/* .getState */ .Gu(STATE_CACHE_PATHS);
if (!cachePathsState) {
return packageManager.path;
}
const cachePaths = JSON.parse(cachePathsState);
if (!Array.isArray(cachePaths) ||
!cachePaths.every(cachePath => typeof cachePath === 'string')) {
throw new Error('Invalid cache paths retrieved from state.');
}
return cachePaths;
}
/**
* State keys used to carry an additional cache's restore-time information over
* to the post (save) action, scoped by the additional cache name.
*/
function additionalCachePrimaryKeyState(name) {
return `${STATE_CACHE_PRIMARY_KEY}-${name}`;
}
function additionalCacheMatchedKeyState(name) {
return `${CACHE_MATCHED_KEY}-${name}`;
}
function buildCacheKey(id, fileHash) {
return `${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${process.arch}-${id}-${fileHash}`;
}
/**
* A function that generates a cache key to use.
* Format of the generated key will be "${{ platform }}-${{ id }}-${{ fileHash }}"".
* @see {@link https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows#matching-a-cache-key|spec of cache key}
*/
async function computeCacheKey(packageManager, cacheDependencyPath) {
const pattern = cacheDependencyPath
? cacheDependencyPath.trim().split('\n')
: packageManager.pattern;
const fileHash = await glob.hashFiles(pattern.join('\n'));
if (!fileHash) {
throw new Error(`No file in ${process.cwd()} matched to [${pattern}], make sure you have checked out the target repository`);
}
return buildCacheKey(packageManager.id, fileHash);
}
/**
* Computes the cache key for an additional cache. Unlike {@link computeCacheKey}
* this returns undefined (instead of throwing) when no file matches the pattern,
* because additional caches are optional features that many projects do not use.
*/
async function computeAdditionalCacheKey(additionalCache) {
const fileHash = await glob.hashFiles(additionalCache.pattern.join('\n'));
if (!fileHash) {
return undefined;
}
return buildCacheKey(additionalCache.name, fileHash);
}
/**
* Restore the dependency cache
* @param id ID of the package manager, should be "maven", "gradle", or "sbt"
* @param cacheDependencyPath The path to a dependency file
* @param cachePaths Paths to cache instead of the package manager defaults
*/
async function restore(id, cacheDependencyPath, cachePaths = []) {
const packageManager = findPackageManager(id);
const resolvedCachePaths = resolveCachePaths(packageManager, cachePaths);
const [primaryKey, preparedAdditionalCaches] = await Promise.all([
computeCacheKey(packageManager, cacheDependencyPath),
prepareAdditionalCaches(packageManager.additionalCaches ?? [])
]);
core.debug(`primary key is ${primaryKey}`);
core.saveState(STATE_CACHE_PRIMARY_KEY, primaryKey);
core.saveState(STATE_CACHE_PATHS, JSON.stringify(resolvedCachePaths));
core.setOutput(STATE_CACHE_PRIMARY_KEY, primaryKey);
for (const preparedCache of preparedAdditionalCaches) {
core.debug(`${preparedCache.cache.name} primary key is ${preparedCache.primaryKey}`);
core.saveState(additionalCachePrimaryKeyState(preparedCache.cache.name), preparedCache.primaryKey);
}
await Promise.all([
restorePrimaryCache(packageManager, resolvedCachePaths, primaryKey),
...preparedAdditionalCaches.map(preparedCache => restoreAdditionalCache(preparedCache))
]);
}
async function restorePrimaryCache(packageManager, cachePaths, primaryKey) {
// No "restoreKeys" is set, to start with a clear cache after dependency update (see https://github.com/actions/setup-java/issues/269)
const matchedKey = await cache.restoreCache(cachePaths, primaryKey);
if (matchedKey) {
core.saveState(CACHE_MATCHED_KEY, matchedKey);
core.setOutput('cache-hit', matchedKey === primaryKey);
core.info(`Cache restored from key: ${matchedKey}`);
}
else {
core.setOutput('cache-hit', false);
core.info(`${packageManager.id} cache is not found`);
}
}
/**
* Compute keys for additional caches (e.g. build-tool wrapper distributions).
* Additional caches without a matching configuration file are omitted.
*/
async function prepareAdditionalCaches(additionalCaches) {
const preparedCaches = await Promise.all(additionalCaches.map(async (additionalCache) => {
const primaryKey = await computeAdditionalCacheKey(additionalCache);
if (!primaryKey) {
core.debug(`No file matched [${additionalCache.pattern}] for the ${additionalCache.name} cache, skipping.`);
return undefined;
}
return { cache: additionalCache, primaryKey };
}));
return preparedCaches.filter((preparedCache) => preparedCache !== undefined);
}
/**
* Restore an additional cache keyed independently of the main dependency cache.
*/
async function restoreAdditionalCache(preparedCache) {
const { cache: additionalCache, primaryKey } = preparedCache;
const matchedKey = await cache.restoreCache(additionalCache.path, primaryKey);
if (matchedKey) {
core.saveState(additionalCacheMatchedKeyState(additionalCache.name), matchedKey);
core.info(`${additionalCache.name} cache restored from key: ${matchedKey}`);
}
else {
core.info(`${additionalCache.name} cache is not found`);
}
}
/**
* Save the dependency cache
* @param id ID of the package manager, should be "maven" or "gradle"
*/
async function save(id) {
const packageManager = findPackageManager(id);
const cachePaths = getCachePathsFromState(packageManager);
const matchedKey = _actions_core__WEBPACK_IMPORTED_MODULE_3__/* .getState */ .Gu(CACHE_MATCHED_KEY);
// Inputs are re-evaluated before the post action, so we want the original key used for restore
const primaryKey = _actions_core__WEBPACK_IMPORTED_MODULE_3__/* .getState */ .Gu(STATE_CACHE_PRIMARY_KEY);
for (const additionalCache of packageManager.additionalCaches ?? []) {
try {
await saveAdditionalCache(packageManager, additionalCache);
}
catch (error) {
const err = error;
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .warning */ .$e(`Failed to save ${additionalCache.name} cache: ${err.message}. Continuing with primary cache save.`);
}
}
if (!primaryKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .warning */ .$e('Error retrieving key from state.');
return;
}
else if (matchedKey === primaryKey) {
// no change in target directories
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`);
return;
}
try {
const cacheId = await _actions_cache__WEBPACK_IMPORTED_MODULE_2__/* .saveCache */ .Io(cachePaths, primaryKey);
if (cacheId === -1) {
// saveCache returns -1 without throwing when the cache was not saved,
// e.g. a reserve collision or a read-only token (fork PR). @actions/cache
// has already logged the reason at the appropriate severity, so just
// trace it instead of misreporting that the cache was saved.
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`Cache was not saved for the key: ${primaryKey}`);
return;
}
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Cache saved with the key: ${primaryKey}`);
}
catch (error) {
const err = error;
if (err.name === _actions_cache__WEBPACK_IMPORTED_MODULE_2__/* .ReserveCacheError */ .Zh.name) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(err.message);
}
else {
if (isProbablyGradleDaemonProblem(packageManager, err)) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .warning */ .$e('Failed to save Gradle cache on Windows. If tar.exe reported "Permission denied", try to run Gradle with `--no-daemon` option. Refer to https://github.com/actions/cache/issues/454 for details.');
}
throw error;
}
}
}
/**
* Save an additional cache under its own key. Skips when no key was recorded at
* restore time (feature unused) or when the exact key was already restored.
*/
async function saveAdditionalCache(packageManager, additionalCache) {
const primaryKey = _actions_core__WEBPACK_IMPORTED_MODULE_3__/* .getState */ .Gu(additionalCachePrimaryKeyState(additionalCache.name));
const matchedKey = _actions_core__WEBPACK_IMPORTED_MODULE_3__/* .getState */ .Gu(additionalCacheMatchedKeyState(additionalCache.name));
if (!primaryKey) {
// The feature is not used by this project, nothing to save.
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`No primary key for the ${additionalCache.name} cache, not saving cache.`);
return;
}
else if (matchedKey === primaryKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Cache hit occurred on the ${additionalCache.name} primary key ${primaryKey}, not saving cache.`);
return;
}
const globber = await _actions_glob__WEBPACK_IMPORTED_MODULE_4__/* .create */ .v(additionalCache.path.join('\n'), {
implicitDescendants: false
});
const cachePaths = await globber.glob();
if (cachePaths.length === 0) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`${additionalCache.name} cache paths do not exist, not saving cache.`);
return;
}
try {
const cacheId = await _actions_cache__WEBPACK_IMPORTED_MODULE_2__/* .saveCache */ .Io(cachePaths, primaryKey);
if (cacheId === -1) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`${additionalCache.name} cache was not saved for the key: ${primaryKey}`);
return;
}
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`${additionalCache.name} cache saved with the key: ${primaryKey}`);
}
catch (error) {
const err = error;
if (err.name === _actions_cache__WEBPACK_IMPORTED_MODULE_2__/* .ValidationError */ .yI.name) {
// The cache paths did not resolve, e.g. the wrapper distribution was
// never downloaded because a system build tool was used or the download
// failed. Optional wrapper caches must not fail the post step, so skip.
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`${additionalCache.name} cache paths do not exist, not saving cache: ${err.message}`);
return;
}
if (err.name === _actions_cache__WEBPACK_IMPORTED_MODULE_2__/* .ReserveCacheError */ .Zh.name) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(err.message);
}
else {
if (isProbablyGradleDaemonProblem(packageManager, err)) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .warning */ .$e(`Failed to save ${additionalCache.name} cache on Windows. If tar.exe reported "Permission denied", try to run Gradle with \`--no-daemon\` option. Refer to https://github.com/actions/cache/issues/454 for details.`);
}
throw error;
}
}
}
/**
* @param packageManager the specified package manager by user
* @param error the error thrown by the saveCache
* @returns true if the given error seems related to the {@link https://github.com/actions/cache/issues/454|running Gradle Daemon issue}.
* @see {@link https://github.com/actions/cache/issues/454#issuecomment-840493935|why --no-daemon is necessary}
*/
function isProbablyGradleDaemonProblem(packageManager, error) {
if (packageManager.id !== 'gradle' ||
process.env['RUNNER_OS'] !== 'Windows') {
return false;
}
const message = error.message || '';
return message.startsWith('Tar failed with error: ');
}
/***/ })
};
+30 -4
View File
@@ -59543,7 +59543,7 @@ function combine(acc, pre, values, max, maxLength, dropEmpties) {
}
// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)
// sequence body.
function expandSequence(body, isAlphaSequence, max) {
function expandSequence(body, isAlphaSequence, max, maxLength) {
const n = body.split(/\.\./);
const N = [];
// A sequence body always splits into two or three parts, but the compiler
@@ -59566,6 +59566,7 @@ function expandSequence(body, isAlphaSequence, max) {
test = gte;
}
const pad = n.some(isPadded);
let length = 0;
for (let i = x; test(i, y) && N.length < max; i += incr) {
let c;
if (isAlphaSequence) {
@@ -59589,7 +59590,10 @@ function expandSequence(body, isAlphaSequence, max) {
}
}
}
if (length + c.length > maxLength)
break;
N.push(c);
length += c.length;
}
return N;
}
@@ -59643,7 +59647,7 @@ function expand_(str, max, maxLength, isTop) {
}
let values;
if (isSequence) {
values = expandSequence(m.body, isAlphaSequence, max);
values = expandSequence(m.body, isAlphaSequence, max, maxLength);
}
else {
let n = parseCommaParts(m.body);
@@ -59661,9 +59665,31 @@ function expand_(str, max, maxLength, isTop) {
}
/* c8 ignore stop */
}
// Values that `combine` is going to drop as empty produce no result, so
// they must not count against `max` - otherwise `{a,,b}` with `max: 2`
// would stop at `['a', '']` and yield one result instead of two. Skipping
// them outright keeps `values` bounded while leaving `max` a bound on
// *kept* results.
let dropsEmpties = dropEmpties && !m.post.length && !pre;
for (let d = 0; dropsEmpties && d < acc.length; d++) {
if (acc[d]) {
dropsEmpties = false;
}
}
values = [];
for (let j = 0; j < n.length; j++) {
values.push.apply(values, expand_(n[j], max, maxLength, false));
let valuesLength = 0;
outer: for (let j = 0; j < n.length; j++) {
const expanded = expand_(n[j], max, maxLength, false);
for (let k = 0; k < expanded.length; k++) {
const v = expanded[k];
if (dropsEmpties && !v)
continue;
if (values.length >= max || valuesLength + v.length > maxLength) {
break outer;
}
values.push(v);
valuesLength += v.length;
}
}
}
acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);
+925 -621
View File
File diff suppressed because it is too large Load Diff
+18 -16
View File
@@ -9,13 +9,13 @@ export const modules = {
/* harmony export */ CorrettoDistribution: () => (/* binding */ CorrettoDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4527);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4527);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _platform_types_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7444);
@@ -23,7 +23,7 @@ export const modules = {
const CORRETTO_VERSIONS_URL = 'https://corretto.github.io/corretto-downloads/latest_links/indexmap_with_checksum.json';
class CorrettoDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
class CorrettoDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Corretto', installerOptions);
}
@@ -31,15 +31,15 @@ class CorrettoDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .renameWinArchive */ .n2)(javaArchivePath);
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_1___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(version) {
@@ -66,7 +66,7 @@ class CorrettoDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5
.filter(item => item.version == version)
.map(item => {
return {
version: (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .convertVersionToSemver */ .ZY)(item.correttoVersion),
version: (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .convertVersionToSemver */ .ZY)(item.correttoVersion),
url: item.downloadLink,
checksum: {
algorithm: 'sha256',
@@ -112,7 +112,7 @@ class CorrettoDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5
for (const version in eligibleVersions) {
const availableVersion = eligibleVersions[version];
for (const fileType in availableVersion) {
const skipNonExtractableBinaries = fileType != (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getDownloadArchiveExtension */ .ag)();
const skipNonExtractableBinaries = fileType != (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .getDownloadArchiveExtension */ .ag)();
if (skipNonExtractableBinaries) {
continue;
}
@@ -138,6 +138,8 @@ class CorrettoDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5
return 'macos';
case 'win32':
return 'windows';
case 'linux':
return (0,_platform_types_js__WEBPACK_IMPORTED_MODULE_5__/* .isAlpineLinux */ .G6)() ? 'alpine' : 'linux';
default:
return process.platform;
}
+17 -19
View File
@@ -9,16 +9,14 @@ export const modules = {
/* harmony export */ KonaDistribution: () => (/* binding */ KonaDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
@@ -26,7 +24,7 @@ export const modules = {
const KONA_RELEASES_URL = 'https://tencent.github.io/konajdk/releases/kona-v1.json';
class KonaDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
class KonaDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Kona', installerOptions);
}
@@ -34,15 +32,15 @@ class KonaDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/*
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Kona JDK ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
const javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getDownloadArchiveExtension */ .ag)();
const archivePath = process.platform === 'win32'
? (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .renameWinArchive */ .n2)(javaArchivePath)
? (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .renameWinArchive */ .n2)(javaArchivePath)
: javaArchivePath;
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .extractJdkFile */ .PE)(archivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_3___default().readdirSync(extractedJavaPath)[0];
const jdkDirectory = path__WEBPACK_IMPORTED_MODULE_4___default().join(extractedJavaPath, archiveName);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .extractJdkFile */ .PE)(archivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const jdkDirectory = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(jdkDirectory, this.toolcacheFolderName, version, this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .cacheJdkDir */ .Vj)(jdkDirectory, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(version) {
@@ -55,7 +53,7 @@ class KonaDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/*
const availableReleases = await this.getAvailableReleases();
const releases = availableReleases
.filter(item => {
return (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .isVersionSatisfies */ .y)(version, item.version);
return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(version, item.version);
})
.map(item => {
return {
@@ -70,7 +68,7 @@ class KonaDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/*
: undefined
};
})
.sort((a, b) => -semver__WEBPACK_IMPORTED_MODULE_2___default().compareBuild(a.version, b.version));
.sort((a, b) => -semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(a.version, b.version));
if (!releases.length) {
throw new Error(`No Kona release for the specified version "${version}" on OS "${this.getOs()}" and arch "${this.getArch()}".`);
}
+33 -23
View File
@@ -9,15 +9,13 @@ export const modules = {
/* harmony export */ OracleDistribution: () => (/* binding */ OracleDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var _actions_http_client__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4942);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4527);
/* harmony import */ var _actions_http_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4942);
@@ -25,7 +23,7 @@ export const modules = {
const ORACLE_DL_BASE = 'https://download.oracle.com/java';
class OracleDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
class OracleDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_3__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Oracle', installerOptions);
}
@@ -33,16 +31,22 @@ class OracleDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .renameWinArchive */ .n2)(javaArchivePath);
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_1___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, archiveName);
const installedVersion = javaRelease.floating
? (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getJavaVersionFromReleaseFile */ .C4)(archivePath)
: javaRelease.version;
const version = this.getToolcacheVersionName(installedVersion);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: installedVersion, path: javaPath };
}
requiresRemoteResolution() {
return this.stable && !this.version.includes('.');
}
async findPackageForDownload(range) {
const arch = this.distributionArchitecture();
@@ -56,12 +60,12 @@ class OracleDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__
throw new Error('Oracle JDK provides only the `jdk` package type');
}
const platform = this.getPlatform();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getDownloadArchiveExtension */ .ag)();
// The `latest` alias is normalized to the SemVer wildcard. Oracle builds its
// download URLs from a concrete major and has no endpoint to list releases,
// so resolve the newest available GA major from the Adoptium API and use it.
if (this.latest) {
const latestMajor = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getLatestMajorVersion */ .ri)(this.http);
const latestMajor = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getLatestMajorVersion */ .ri)(this.http);
range = latestMajor.toString();
}
const isOnlyMajorProvided = !range.includes('.');
@@ -77,20 +81,26 @@ class OracleDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__
if (isOnlyMajorProvided) {
possibleUrls.push(`${ORACLE_DL_BASE}/${major}/latest/jdk-${major}_${platform}-${arch}_bin.${extension}`);
}
const floatingUrl = isOnlyMajorProvided ? possibleUrls[0] : undefined;
possibleUrls.push(`${ORACLE_DL_BASE}/${major}/archive/jdk-${range}_${platform}-${arch}_bin.${extension}`);
if (parseInt(major) < 17) {
throw new Error('Oracle JDK is only supported for JDK 17 and later');
}
for (const url of possibleUrls) {
const response = await this.http.head(url);
if (response.message.statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.OK) {
if (response.message.statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_5__/* .HttpCodes */ .Hv.OK) {
const floating = url === floatingUrl;
return {
url,
version: range,
checksum: await this.fetchChecksum(`${url}.sha256`, 'sha256')
checksum: await this.fetchChecksum(`${url}.sha256`, 'sha256'),
floating,
fingerprint: floating
? (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getArtifactFingerprint */ .VX)(response.message.headers)
: undefined
};
}
if (response.message.statusCode !== _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.NotFound) {
if (response.message.statusCode !== _actions_http_client__WEBPACK_IMPORTED_MODULE_5__/* .HttpCodes */ .Hv.NotFound) {
throw new Error(`Http request for Oracle JDK failed with status code: ${response.message.statusCode}`);
}
}
+74 -27
View File
@@ -8,15 +8,16 @@ export const modules = {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LocalDistribution: () => (/* binding */ LocalDistribution)
/* harmony export */ });
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9805);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3838);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4527);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7242);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_5__);
@@ -24,7 +25,8 @@ export const modules = {
class LocalDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
class LocalDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_3__/* .JavaBase */ .O {
jdkFile;
constructor(installerOptions, jdkFile) {
super('jdkfile', installerOptions);
@@ -34,42 +36,80 @@ class LocalDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/
if (this.latest) {
throw new Error("The 'latest' version alias is not supported for the 'jdkfile' distribution. Please specify a concrete version.");
}
if (this.verifySignature) {
throw new Error(`Input 'verify-signature' is not supported for distribution '${this.distribution}'.`);
}
let foundJava = this.forceDownload ? null : this.findInToolcache();
if (foundJava) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Resolved Java ${foundJava.version} from tool-cache`);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Resolved Java ${foundJava.version} from tool-cache`);
}
else {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Java ${this.version} was not found in tool-cache. Trying to unpack JDK file...`);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Java ${this.version} was not found in tool-cache. Trying to unpack JDK file...`);
if (!this.jdkFile) {
throw new Error("'jdkFile' is not specified");
}
const jdkFilePath = path__WEBPACK_IMPORTED_MODULE_3___default().resolve(this.jdkFile);
const stats = fs__WEBPACK_IMPORTED_MODULE_2___default().statSync(jdkFilePath);
const jdkFilePath = path__WEBPACK_IMPORTED_MODULE_2___default().resolve(this.jdkFile);
const stats = fs__WEBPACK_IMPORTED_MODULE_1___default().statSync(jdkFilePath);
if (!stats.isFile()) {
throw new Error(`JDK file was not found in path '${jdkFilePath}'`);
}
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Extracting Java from '${jdkFilePath}'`);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .extractJdkFile */ .PE)(jdkFilePath);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const javaVersion = this.version;
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_0__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaVersion), this.architecture);
foundJava = {
version: javaVersion,
path: javaPath
};
let jdkCache;
if (this.cacheJdk) {
const [{ getJdkVerificationIdentity }, source] = await Promise.all([
Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(779)]).then(__webpack_require__.bind(__webpack_require__, 5779)),
hashFile(jdkFilePath)
]);
jdkCache = {
distribution: this.distribution,
packageType: this.packageType,
architecture: this.architecture,
version: this.version,
source,
verification: getJdkVerificationIdentity(false),
path: this.getJdkCachePath(this.version)
};
}
if (!this.forceDownload && jdkCache) {
const { restoreJdk } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(779)]).then(__webpack_require__.bind(__webpack_require__, 5779));
const restored = await restoreJdk(jdkCache);
const restoredPath = restored
? this.getRestoredJdkPath(this.version)
: undefined;
if (restoredPath) {
foundJava = {
version: this.version,
path: restoredPath
};
}
}
if (!foundJava) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java from '${jdkFilePath}'`);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .extractJdkFile */ .PE)(jdkFilePath);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_1___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, archiveName);
const javaVersion = this.version;
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaVersion), this.architecture);
foundJava = {
version: javaVersion,
path: javaPath
};
if (jdkCache) {
const { registerJdk } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(779)]).then(__webpack_require__.bind(__webpack_require__, 5779));
registerJdk(jdkCache);
}
}
}
// JDK folder may contain postfix "Contents/Home" on macOS
const macOSPostfixPath = path__WEBPACK_IMPORTED_MODULE_3___default().join(foundJava.path, _constants_js__WEBPACK_IMPORTED_MODULE_6__/* .MACOS_JAVA_CONTENT_POSTFIX */ .PG);
if (process.platform === 'darwin' && fs__WEBPACK_IMPORTED_MODULE_2___default().existsSync(macOSPostfixPath)) {
const macOSPostfixPath = path__WEBPACK_IMPORTED_MODULE_2___default().join(foundJava.path, _constants_js__WEBPACK_IMPORTED_MODULE_6__/* .MACOS_JAVA_CONTENT_POSTFIX */ .PG);
if (process.platform === 'darwin' && fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(macOSPostfixPath)) {
foundJava.path = macOSPostfixPath;
}
if (this.setDefault) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Setting Java ${foundJava.version} as the default`);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Setting Java ${foundJava.version} as the default`);
this.setJavaDefault(foundJava.version, foundJava.path);
}
else {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Installing Java ${foundJava.version} (not setting as default)`);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Installing Java ${foundJava.version} (not setting as default)`);
this.setJavaEnvironment(foundJava.version, foundJava.path);
}
return foundJava;
@@ -83,6 +123,13 @@ class LocalDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/
throw new Error('This method should not be implemented in local file provider');
}
}
async function hashFile(file) {
const hash = (0,crypto__WEBPACK_IMPORTED_MODULE_5__.createHash)('sha256');
for await (const chunk of (0,fs__WEBPACK_IMPORTED_MODULE_1__.createReadStream)(file)) {
hash.update(chunk);
}
return hash.digest('hex');
}
/***/ })
+78 -52
View File
@@ -89,7 +89,7 @@ class MicrosoftDistributions extends base_installer/* JavaBase */.O {
const extractedJavaPath = await (0,util/* extractJdkFile */.PE)(javaArchivePath, extension);
const archiveName = external_fs_default().readdirSync(extractedJavaPath)[0];
const archivePath = external_path_default().join(extractedJavaPath, archiveName);
const javaPath = await tool_cache/* cacheDir */.e8(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
const javaPath = await (0,util/* cacheJdkDir */.Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(range) {
@@ -125,15 +125,10 @@ class MicrosoftDistributions extends base_installer/* JavaBase */.O {
return true;
}
async getAvailableVersions() {
// TODO get these dynamically!
// We will need Microsoft to add an endpoint where we can query for versions.
const owner = 'actions';
const repository = 'setup-java';
const branch = 'main';
const filePath = 'src/distributions/microsoft/microsoft-openjdk-versions.json';
let releases = null;
const fileUrl = `https://api.github.com/repos/${owner}/${repository}/contents/${filePath}?ref=${branch}`;
const headers = (0,util/* getGitHubHttpHeaders */.U_)();
const fileUrl = `https://aka.ms/download-jdk/microsoft-openjdk-versions.json`;
// Avoid leaking the GitHub token to a non-GitHub host (aka.ms redirects to a CDN).
const headers = { accept: 'application/json' };
let response = null;
if (core/* isDebug */._o()) {
console.time('Retrieving available versions for Microsoft took'); // eslint-disable-line no-console
@@ -170,25 +165,30 @@ class MicrosoftDistributions extends base_installer/* JavaBase */.O {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Fh: () => (/* binding */ importKey),
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature)
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature),
/* harmony export */ mS: () => (/* binding */ removeGpgHome),
/* harmony export */ nY: () => (/* binding */ toGpgPath)
/* harmony export */ });
/* unused harmony exports PRIVATE_KEY_FILE, toGpgPath, deleteKey */
/* unused harmony export GPG_HOME_PREFIX */
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8701);
/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5260);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9805);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8701);
/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5260);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9805);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
const PRIVATE_KEY_FILE = path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getTempDir */ .G4(), 'private-key.asc');
const PRIVATE_KEY_FINGERPRINT_REGEX = /\w{40}/;
const GPG_HOME_PREFIX = 'setup-java-gpg-';
const VERIFY_GPG_HOME_PREFIX = 'verify-signature-gpg-home-';
// Convert a Windows path (D:\a\_temp\...) to a POSIX path (/d/a/_temp/...).
// The Git-bundled GPG on Windows (MSYS2-based) uses POSIX path conventions
// internally. Passing Windows paths with backslashes can cause fatal GPG errors
@@ -200,45 +200,71 @@ function toGpgPath(p) {
.replace(/\\/g, '/')
.replace(/^([A-Za-z]):\//, (_, drive) => `/${drive.toLowerCase()}/`);
}
async function importKey(privateKey) {
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(PRIVATE_KEY_FILE, privateKey, {
encoding: 'utf-8',
flag: 'w'
});
let output = '';
const options = {
silent: true,
listeners: {
stdout: (data) => {
output += data.toString();
}
}
};
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
'--batch',
'--import-options',
'import-show',
'--import',
PRIVATE_KEY_FILE
], options);
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(PRIVATE_KEY_FILE);
const match = output.match(PRIVATE_KEY_FINGERPRINT_REGEX);
return match && match[0];
function createGpgHome(prefix) {
const gpgHome = fs__WEBPACK_IMPORTED_MODULE_0__.mkdtempSync(path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getTempDir */ .G4(), prefix));
if (process.platform !== 'win32') {
fs__WEBPACK_IMPORTED_MODULE_0__.chmodSync(gpgHome, 0o700);
}
return gpgHome;
}
async function deleteKey(keyFingerprint) {
await exec.exec('gpg', ['--batch', '--yes', '--delete-secret-and-public-key', keyFingerprint], {
silent: true
});
async function importKey(privateKey) {
const gpgHome = createGpgHome(GPG_HOME_PREFIX);
const privateKeyFile = path__WEBPACK_IMPORTED_MODULE_1__.join(gpgHome, `private-key-${(0,crypto__WEBPACK_IMPORTED_MODULE_2__.randomUUID)()}.asc`);
try {
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(privateKeyFile, privateKey, {
encoding: 'utf-8',
flag: 'wx',
mode: 0o600
});
try {
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(privateKeyFile)
], { silent: true });
}
finally {
fs__WEBPACK_IMPORTED_MODULE_0__.rmSync(privateKeyFile, { force: true });
}
return gpgHome;
}
catch (error) {
await removeGpgHome(gpgHome);
throw error;
}
}
async function removeGpgHome(gpgHome) {
if (!gpgHome) {
return;
}
const resolvedGpgHome = path__WEBPACK_IMPORTED_MODULE_1__.resolve(gpgHome);
const resolvedTempDir = path__WEBPACK_IMPORTED_MODULE_1__.resolve(_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getTempDir */ .G4());
if (path__WEBPACK_IMPORTED_MODULE_1__.dirname(resolvedGpgHome) !== resolvedTempDir ||
!path__WEBPACK_IMPORTED_MODULE_1__.basename(resolvedGpgHome).startsWith(GPG_HOME_PREFIX)) {
throw new Error(`Refusing to remove unexpected GPG home: ${gpgHome}`);
}
if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(resolvedGpgHome)) {
return;
}
try {
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpgconf', ['--homedir', toGpgPath(resolvedGpgHome), '--kill', 'gpg-agent'], { silent: true, ignoreReturnCode: true });
}
catch {
// gpgconf may be unavailable, but directory removal must still be attempted.
}
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(resolvedGpgHome);
}
async function verifyPackageSignature(archivePath, signatureUrl, publicKeyContent) {
const signaturePath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__/* .downloadTool */ .bq(signatureUrl);
const signaturePath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .downloadTool */ .bq(signatureUrl);
let gpgHome;
try {
gpgHome = fs__WEBPACK_IMPORTED_MODULE_0__.mkdtempSync(path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getTempDir */ .G4(), 'verify-signature-gpg-home-'));
gpgHome = createGpgHome(VERIFY_GPG_HOME_PREFIX);
}
catch (error) {
try {
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
}
catch {
// ignore cleanup failures
@@ -249,14 +275,14 @@ async function verifyPackageSignature(archivePath, signatureUrl, publicKeyConten
const publicKeyFile = path__WEBPACK_IMPORTED_MODULE_1__.join(gpgHome, 'public-key.asc');
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(publicKeyFile, publicKeyContent, { encoding: 'utf-8' });
const options = { silent: true };
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(publicKeyFile)
], options);
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
@@ -266,8 +292,8 @@ async function verifyPackageSignature(archivePath, signatureUrl, publicKeyConten
], options);
}
finally {
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(gpgHome);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(gpgHome);
}
}
+139
View File
@@ -0,0 +1,139 @@
export const id = 228;
export const ids = [228];
export const modules = {
/***/ 8228:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RedHatDistribution: () => (/* binding */ RedHatDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4527);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var _platform_types_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7444);
const DISCO_API_URL = 'https://api.foojay.io/disco/v3.0';
class RedHatDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
constructor(installerOptions) {
super('RedHat', installerOptions);
}
async findPackageForDownload(range) {
if (!this.stable) {
throw new Error('Early access versions are not supported');
}
const availablePackages = await this.getAvailablePackages();
const normalizedPackages = availablePackages
.map(item => ({
item,
version: this.normalizeDiscoVersion(item.java_version)
}))
.filter((item) => item.version !== null)
.sort((left, right) => -semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(left.version, right.version));
const selectedPackage = normalizedPackages.find(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .isVersionSatisfies */ .y)(range, item.version));
if (!selectedPackage) {
throw this.createVersionNotFoundError(range, normalizedPackages.map(item => item.version), `Operating system: ${this.getOperatingSystem()}`);
}
const detailsUrl = `${DISCO_API_URL}/ids/${selectedPackage.item.id}`;
const response = await this.http.getJson(detailsUrl);
const details = response.result?.result?.[0];
if (!details?.direct_download_uri) {
throw new Error(`Foojay Disco returned no direct Red Hat download URL for package '${selectedPackage.item.id}'.`);
}
const checksum = details.checksum?.trim();
if (details.checksum_type?.toLowerCase() !== 'sha256' || !checksum) {
throw new Error(`Foojay Disco returned no SHA-256 checksum for Red Hat package '${selectedPackage.item.id}'.`);
}
return {
version: selectedPackage.version,
url: details.direct_download_uri,
checksum: {
algorithm: 'sha256',
value: checksum,
source: detailsUrl
}
};
}
async downloadTool(javaRelease) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq('Extracting Java archive...');
const archiveType = this.getArchiveType();
if (archiveType === 'zip') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .extractJdkFile */ .PE)(javaArchivePath, archiveType);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_1___default().readdirSync(extractedJavaPath)[0];
if (!archiveName) {
throw new Error(`The Red Hat archive for Java ${javaRelease.version} was empty.`);
}
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, archiveName);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async getAvailablePackages() {
const operatingSystem = this.getOperatingSystem();
const archiveType = this.getArchiveType();
const query = new URLSearchParams({
distro: 'redhat',
release_status: 'ga',
operating_system: operatingSystem,
architecture: this.distributionArchitecture(),
package_type: this.packageType,
archive_type: archiveType,
directly_downloadable: 'true'
});
const url = `${DISCO_API_URL}/packages?${query.toString()}`;
const response = await this.http.getJson(url);
const packages = response.result?.result;
if (!Array.isArray(packages)) {
throw new Error(`Could not fetch Red Hat package metadata from Foojay Disco: ${url}`);
}
return packages.filter(item => item.distribution === 'redhat' &&
item.release_status === 'ga' &&
item.operating_system === operatingSystem &&
item.architecture === this.distributionArchitecture() &&
item.package_type === this.packageType &&
item.archive_type === archiveType &&
item.directly_downloadable);
}
getOperatingSystem(alpine = (0,_platform_types_js__WEBPACK_IMPORTED_MODULE_6__/* .isAlpineLinux */ .G6)()) {
if (alpine) {
throw new Error("Distribution 'redhat' does not support Alpine Linux because Red Hat portable archives require glibc.");
}
return process.platform === 'win32' ? 'windows' : 'linux';
}
getArchiveType() {
return process.platform === 'win32' ? 'zip' : 'tar.xz';
}
normalizeDiscoVersion(version) {
let normalizedVersion = version.trim();
if (/^\d+\+\d+$/.test(normalizedVersion)) {
normalizedVersion = normalizedVersion.replace('+', '.0.0+');
}
else if (/^\d+$/.test(normalizedVersion)) {
normalizedVersion = `${normalizedVersion}.0.0`;
}
else if (/^\d+\.\d+$/.test(normalizedVersion)) {
normalizedVersion = `${normalizedVersion}.0`;
}
return semver__WEBPACK_IMPORTED_MODULE_3___default().valid(normalizedVersion) ? normalizedVersion : null;
}
}
/***/ })
};
+231 -5
View File
@@ -217,6 +217,13 @@ class JavaBase {
latest;
checkLatest;
forceDownload;
cacheJdk;
/**
* Whether the concrete version of a floating release has been established
* from the checksum-bound resolution cache. Until then the release version is
* only the requested major and says nothing about the bytes behind the URL.
*/
floatingVersionVerified = false;
setDefault;
verifySignature;
verifySignaturePublicKey;
@@ -232,6 +239,7 @@ class JavaBase {
this.packageType = installerOptions.packageType;
this.checkLatest = installerOptions.checkLatest;
this.forceDownload = installerOptions.forceDownload ?? false;
this.cacheJdk = installerOptions.cacheJdk ?? false;
this.setDefault =
installerOptions.setDefault !== undefined
? installerOptions.setDefault
@@ -314,21 +322,76 @@ class JavaBase {
throw new Error(`Input 'verify-signature' is not supported for distribution '${this.distribution}'.`);
}
let foundJava = this.forceDownload ? null : this.findInToolcache();
if (foundJava && !this.checkLatest && !this.latest) {
if (foundJava &&
!this.checkLatest &&
!this.latest &&
!this.requiresRemoteResolution()) {
core/* info */.pq(`Resolved Java ${foundJava.version} from tool-cache`);
}
else {
core/* info */.pq('Trying to resolve the latest version from remote');
try {
const javaRelease = await this.findPackageForDownload(this.version);
let javaRelease = await this.resolveJavaRelease();
core/* info */.pq(`Resolved latest version as ${javaRelease.version}`);
if (javaRelease.floating) {
// A tool-cache entry has no source identity, and until the
// checksum-bound resolution cache maps the current artifact to a
// concrete version the release version is still just the requested
// major — so nothing already on the runner can be trusted. Once that
// mapping is known, an installation of exactly that version is the
// artifact we would otherwise download.
foundJava =
this.floatingVersionVerified && !this.forceDownload
? this.findConcreteVersionInToolcache(javaRelease.version)
: null;
}
if (!this.forceDownload && foundJava?.version === javaRelease.version) {
core/* info */.pq(`Resolved Java ${foundJava.version} from tool-cache`);
}
else {
core/* info */.pq('Trying to download...');
foundJava = await this.downloadTool(javaRelease);
core/* info */.pq(`Java ${foundJava.version} was downloaded`);
let jdkCache = this.cacheJdk &&
(!javaRelease.floating ||
(this.hasStableReleaseIdentity(javaRelease) &&
semver_default().valid(javaRelease.version)))
? await this.createJdkCache(javaRelease)
: undefined;
if (!this.forceDownload && jdkCache) {
const { restoreJdk } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(779)]).then(__webpack_require__.bind(__webpack_require__, 5779));
const restored = await restoreJdk(jdkCache);
if (restored) {
const restoredPath = this.getRestoredJdkPath(javaRelease.version);
if (restoredPath) {
foundJava = {
version: javaRelease.version,
path: restoredPath
};
}
}
}
if (!foundJava || foundJava.version !== javaRelease.version) {
core/* info */.pq('Trying to download...');
foundJava = await this.downloadTool(javaRelease);
core/* info */.pq(`Java ${foundJava.version} was downloaded`);
if (javaRelease.floating) {
if (!semver_default().valid(foundJava.version) ||
!(0,util/* isVersionSatisfies */.y)(this.version, foundJava.version)) {
throw new Error(`The downloaded ${this.distribution} artifact reported Java ${foundJava.version}, which does not satisfy '${this.version}'.`);
}
javaRelease = { ...javaRelease, version: foundJava.version };
await this.registerFloatingResolution(javaRelease);
jdkCache =
this.cacheJdk && this.hasStableReleaseIdentity(javaRelease)
? await this.createJdkCache(javaRelease)
: undefined;
}
if (jdkCache) {
// Register after the installation exists so its identity is
// captured; the post-job save refuses to upload a path whose
// installation was replaced afterwards.
const { registerJdk } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(779)]).then(__webpack_require__.bind(__webpack_require__, 5779));
registerJdk(jdkCache);
}
}
}
}
catch (error) {
@@ -354,6 +417,114 @@ class JavaBase {
}
return foundJava;
}
/**
* Resolves the release to install, preferring a cached resolution over the
* distribution's metadata API.
*
* Only Temurin is preinstalled on hosted runners, so for every other
* distribution the tool-cache lookup misses and the vendor API becomes a
* per-job dependency even when the JDK itself is already in the GitHub
* Actions cache. A cached resolution removes that dependency, and because it
* carries the download URL and checksum it also keeps a job working when the
* vendor API is unavailable but the JDK still has to be downloaded.
*/
async resolveJavaRelease() {
if (!this.cacheJdk ||
this.checkLatest ||
this.latest ||
this.forceDownload ||
this.requiresRemoteResolution()) {
const release = await this.findPackageForDownload(this.version);
return this.restoreFloatingResolution(release);
}
const { restoreJdkResolution, registerJdkResolution } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(348)]).then(__webpack_require__.bind(__webpack_require__, 967));
const request = {
distribution: this.distribution,
packageType: this.packageType,
platform: (0,platform_types/* getJavaPlatformIdentity */.U)(),
architecture: this.architecture,
versionSpec: this.version,
stable: this.stable
};
const restored = await restoreJdkResolution(request);
if (restored?.fresh) {
core/* info */.pq(`Resolved ${this.distribution} ${restored.release.version} from the resolution cache`);
return restored.release;
}
try {
const javaRelease = await this.findPackageForDownload(this.version);
if (!javaRelease.floating) {
registerJdkResolution(request, javaRelease);
}
return this.restoreFloatingResolution(javaRelease);
}
catch (error) {
if (!restored) {
throw error;
}
// The cached resolution is older than the current bucket, but falling
// back to it is strictly better than failing the job because the vendor
// metadata API is down.
core/* warning */.$e(`Failed to resolve ${this.distribution} ${this.version} from remote (${error instanceof Error ? error.message : String(error)}); falling back to the cached resolution for ${restored.release.version}.`);
return restored.release;
}
}
requiresRemoteResolution() {
return false;
}
async createJdkCache(javaRelease) {
const { getJdkVerificationIdentity } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(779)]).then(__webpack_require__.bind(__webpack_require__, 5779));
return {
distribution: this.distribution,
packageType: this.packageType,
architecture: this.architecture,
version: javaRelease.version,
source: this.getJdkReleaseIdentity(javaRelease),
verification: getJdkVerificationIdentity(this.verifySignature, this.verifySignaturePublicKey),
path: this.getJdkCachePath(javaRelease.version)
};
}
async restoreFloatingResolution(javaRelease) {
if (!javaRelease.floating ||
!this.hasStableReleaseIdentity(javaRelease) ||
!this.cacheJdk ||
this.forceDownload) {
return javaRelease;
}
const { restoreJdkResolution } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(348)]).then(__webpack_require__.bind(__webpack_require__, 967));
const restored = await restoreJdkResolution(this.getFloatingResolutionRequest(javaRelease));
if (!restored) {
return javaRelease;
}
if (!semver_default().valid(restored.release.version) ||
!(0,util/* isVersionSatisfies */.y)(this.version, restored.release.version)) {
core/* debug */.Yz(`Ignoring the cached concrete version '${restored.release.version}' for ${this.distribution} ${this.version}.`);
return javaRelease;
}
core/* info */.pq(`Resolved ${this.distribution} ${restored.release.version} for the current floating artifact`);
this.floatingVersionVerified = true;
return { ...javaRelease, version: restored.release.version };
}
async registerFloatingResolution(javaRelease) {
if (!this.hasStableReleaseIdentity(javaRelease) ||
!this.cacheJdk ||
this.forceDownload) {
return;
}
const { registerJdkResolution } = await Promise.all(/* import() */[__webpack_require__.e(824), __webpack_require__.e(971), __webpack_require__.e(348)]).then(__webpack_require__.bind(__webpack_require__, 967));
registerJdkResolution(this.getFloatingResolutionRequest(javaRelease), javaRelease);
}
getFloatingResolutionRequest(javaRelease) {
return {
distribution: this.distribution,
packageType: this.packageType,
platform: (0,platform_types/* getJavaPlatformIdentity */.U)(),
architecture: this.architecture,
versionSpec: this.version,
stable: this.stable,
source: this.getJdkReleaseIdentity(javaRelease)
};
}
logSetupError(error) {
const httpStatusCode = error instanceof tool_cache/* HTTPError */.Hl
? error.httpStatusCode
@@ -435,6 +606,61 @@ class JavaBase {
// related issue: https://github.com/actions/virtual-environments/issues/3014
return version.replace('+', '-');
}
getJdkCachePath(version) {
const toolCache = process.env['RUNNER_TOOL_CACHE'];
if (!toolCache) {
return '';
}
return external_path_default().join(toolCache, this.toolcacheFolderName, this.getToolcacheVersionName(version));
}
getRestoredJdkPath(version) {
const basePath = this.getJdkCachePath(version);
if (!basePath) {
return null;
}
const architecturePath = external_path_default().join(basePath, this.architecture);
return external_fs_.existsSync(architecturePath) &&
external_fs_.existsSync(`${architecturePath}.complete`)
? architecturePath
: null;
}
/**
* Locates an installation of an exact version in the tool cache, unlike
* `findInToolcache()` which returns the newest entry satisfying the requested
* range. Used to reuse a JDK the runner already holds instead of downloading
* the identical artifact again.
*/
findConcreteVersionInToolcache(version) {
if (!semver_default().valid(version)) {
return null;
}
const installedPath = this.getRestoredJdkPath(version);
return installedPath ? { version, path: installedPath } : null;
}
getJdkReleaseIdentity(javaRelease) {
if (javaRelease.checksum) {
return `${javaRelease.checksum.algorithm}:${javaRelease.checksum.value}`;
}
if (javaRelease.fingerprint) {
return javaRelease.fingerprint;
}
try {
const url = new URL(javaRelease.url);
return `${url.origin}${url.pathname}`;
}
catch {
return javaRelease.url;
}
}
/**
* Whether the release identity pins the exact bytes behind `url`. A floating
* URL is a constant string, so it only becomes a safe cache identity once a
* checksum or a response validator distinguishes one published build from the
* next.
*/
hasStableReleaseIdentity(javaRelease) {
return Boolean(javaRelease.checksum ?? javaRelease.fingerprint);
}
findInToolcache() {
// we can't use tc.find directly because firstly, we need to filter versions by stability flag
// if *-ea is provided, take only ea versions from toolcache, otherwise - only stable versions
+49 -42
View File
@@ -9,16 +9,15 @@ export const modules = {
/* harmony export */ JetBrainsDistribution: () => (/* binding */ JetBrainsDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
/* harmony import */ var _actions_http_client__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(4942);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var _actions_http_client__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4942);
@@ -26,8 +25,9 @@ export const modules = {
class JetBrainsDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
const JETBRAINS_RELEASES_URL = 'https://api.github.com/repos/JetBrains/JetBrainsRuntime/releases?per_page=100';
const GITHUB_API_ORIGIN = 'https://api.github.com';
class JetBrainsDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('JetBrains', installerOptions);
}
@@ -41,9 +41,9 @@ class JetBrainsDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_
};
});
const satisfiedVersions = versions
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .isVersionSatisfies */ .y)(range, item.version))
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(range, item.version))
.sort((a, b) => {
return -semver__WEBPACK_IMPORTED_MODULE_4___default().compareBuild(a.version, b.version);
return -semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(a.version, b.version);
});
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
@@ -63,11 +63,11 @@ class JetBrainsDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
const javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .extractJdkFile */ .PE)(javaArchivePath, 'tar.gz');
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .extractJdkFile */ .PE)(javaArchivePath, 'tar.gz');
const archiveName = fs__WEBPACK_IMPORTED_MODULE_1___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async getAvailableVersions() {
@@ -76,34 +76,41 @@ class JetBrainsDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
console.time('Retrieving available versions for JBR took'); // eslint-disable-line no-console
}
// need to iterate through all pages to retrieve the list of all versions
// GitHub API doesn't provide way to retrieve the count of pages to iterate so infinity loop
let page_index = 1;
const rawVersions = [];
const bearerToken = process.env.GITHUB_TOKEN;
while (true) {
const requestArguments = `per_page=100&page=${page_index}`;
const requestHeaders = {};
if (bearerToken) {
requestHeaders['Authorization'] = `Bearer ${bearerToken}`;
}
const rawUrl = `https://api.github.com/repos/JetBrains/JetBrainsRuntime/releases?${requestArguments}`;
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o() && page_index === 1) {
// url is identical except page_index so print it once for debug
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Gathering available versions from '${rawUrl}'`);
}
const paginationPageResult = (await this.http.getJson(rawUrl, requestHeaders)).result;
const bearerToken = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getGitHubToken */ .lK)();
const requestHeaders = {
Accept: 'application/vnd.github+json'
};
if (bearerToken) {
requestHeaders.Authorization = `Bearer ${bearerToken}`;
}
let releasesUrl = JETBRAINS_RELEASES_URL;
let pageCount = 0;
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Gathering available versions from '${releasesUrl}'`);
}
while (releasesUrl) {
pageCount++;
const response = await this.http.getJson(releasesUrl, requestHeaders);
const paginationPageResult = response.result;
if (!paginationPageResult || paginationPageResult.length === 0) {
// break infinity loop because we have reached end of pagination
break;
}
const paginationPage = paginationPageResult.filter(version => this.stable ? !version.prerelease : version.prerelease);
if (!paginationPage || paginationPage.length === 0) {
// break infinity loop because we have reached end of pagination
rawVersions.push(...paginationPageResult.filter(version => this.stable ? !version.prerelease : version.prerelease));
const nextUrl = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getNextPageUrlFromLinkHeader */ .rC)(response.headers);
if (nextUrl && !(0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .validatePaginationUrl */ .SA)(nextUrl, GITHUB_API_ORIGIN)) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .warning */ .$e(`Ignoring pagination link with unexpected origin: ${nextUrl}`);
releasesUrl = null;
}
else {
releasesUrl = nextUrl;
}
if (pageCount >= _util_js__WEBPACK_IMPORTED_MODULE_5__/* .MAX_PAGINATION_PAGES */ .Tp) {
if (releasesUrl) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .warning */ .$e(`Reached pagination safeguard limit (${_util_js__WEBPACK_IMPORTED_MODULE_5__/* .MAX_PAGINATION_PAGES */ .Tp} pages) while listing JetBrains Runtime releases.`);
}
break;
}
rawVersions.push(...paginationPage);
page_index++;
}
if (this.stable) {
// Add versions not available from the API but are downloadable
@@ -156,13 +163,13 @@ class JetBrainsDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_
let url = `https://cache-redirector.jetbrains.com/intellij-jbr/${type}-${semver}-${platform}-${arch}-b${build}.tar.gz`;
let include = false;
const res = await this.http.head(url);
if (res.message.statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_7__/* .HttpCodes */ .Hv.OK) {
if (res.message.statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.OK) {
include = true;
}
else {
url = `https://cache-redirector.jetbrains.com/intellij-jbr/${type}_nomod-${semver}-${platform}-${arch}-b${build}.tar.gz`;
const res2 = await this.http.head(url);
if (res2.message.statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_7__/* .HttpCodes */ .Hv.OK) {
if (res2.message.statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.OK) {
include = true;
}
}
+54323
View File
File diff suppressed because it is too large Load Diff
+280
View File
@@ -0,0 +1,280 @@
export const id = 348;
export const ids = [348];
export const modules = {
/***/ 967:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ registerJdkResolution: () => (/* binding */ registerJdkResolution),
/* harmony export */ restoreJdkResolution: () => (/* binding */ restoreJdkResolution)
/* harmony export */ });
/* unused harmony export saveJdkResolutionCaches */
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _actions_cache__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6971);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3838);
const STATE_JDK_RESOLUTIONS = 'jdk-resolutions';
const JDK_RESOLUTION_KEY_VERSION = 2;
const RESOLUTION_DIRECTORY = 'setup-java-jdk-resolution';
const RESOLUTION_FILE_NAME = 'release.json';
const pendingResolutions = [];
/**
* Restores a previously resolved release so a distribution can skip its vendor
* metadata API.
*
* The cache path deliberately excludes the freshness window: `@actions/cache`
* derives
* a cache version by hashing the requested paths, so a bucket-independent path
* is what allows the restore keys to fall back to an older bucket.
*/
async function restoreJdkResolution(request) {
// Deliberately not `isCacheFeatureAvailable()`: this is an optional
// optimization, and the JDK cache already warns once when the service is
// unreachable.
if (!_actions_cache__WEBPACK_IMPORTED_MODULE_3__/* .isFeatureAvailable */ .w3()) {
return undefined;
}
const cachePath = getResolutionCachePath(request);
if (!cachePath) {
return undefined;
}
const keyPrefix = getResolutionKeyPrefix(request);
const primaryKey = `${keyPrefix}${getFreshnessBucket()}`;
let matchedKey;
try {
matchedKey = await _actions_cache__WEBPACK_IMPORTED_MODULE_3__/* .restoreCache */ .P3([cachePath], primaryKey, [keyPrefix]);
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Failed to restore the JDK resolution cache: ${getErrorMessage(error)}`);
return undefined;
}
if (!matchedKey) {
return undefined;
}
let release;
try {
const contents = fs__WEBPACK_IMPORTED_MODULE_1___default().readFileSync(path__WEBPACK_IMPORTED_MODULE_2___default().join(cachePath, RESOLUTION_FILE_NAME), 'utf8');
release = parseResolvedRelease(contents);
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Ignoring the JDK resolution cache entry ${matchedKey}: ${getErrorMessage(error)}`);
return undefined;
}
return { release, fresh: matchedKey === primaryKey };
}
/**
* Persists a freshly resolved release for later jobs. The entry is written to
* disk immediately and uploaded by the post-job step.
*/
function registerJdkResolution(request, release) {
if (!_actions_cache__WEBPACK_IMPORTED_MODULE_3__/* .isFeatureAvailable */ .w3()) {
return;
}
const cachePath = getResolutionCachePath(request);
if (!cachePath) {
return;
}
const payload = JSON.stringify(release);
try {
fs__WEBPACK_IMPORTED_MODULE_1___default().mkdirSync(cachePath, { recursive: true });
fs__WEBPACK_IMPORTED_MODULE_1___default().writeFileSync(path__WEBPACK_IMPORTED_MODULE_2___default().join(cachePath, RESOLUTION_FILE_NAME), payload);
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Failed to record the JDK resolution cache entry: ${getErrorMessage(error)}`);
return;
}
const key = `${getResolutionKeyPrefix(request)}${getFreshnessBucket()}`;
if (!pendingResolutions.some(item => item.key === key)) {
pendingResolutions.push({ key, path: cachePath, release: payload });
}
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .saveState */ .LZ(STATE_JDK_RESOLUTIONS, JSON.stringify(pendingResolutions));
}
async function saveJdkResolutionCaches() {
const state = core.getState(STATE_JDK_RESOLUTIONS);
if (!state) {
return;
}
let resolutions;
try {
resolutions = parseJdkResolutionState(state);
}
catch (error) {
core.debug(`Invalid JDK resolution cache state, not saving: ${getErrorMessage(error)}`);
return;
}
for (const resolution of resolutions) {
// A restore performed by a later step overwrites this path, so the payload
// the key was computed for is written again rather than trusted to still be
// on disk.
try {
fs.mkdirSync(resolution.path, { recursive: true });
fs.writeFileSync(path.join(resolution.path, RESOLUTION_FILE_NAME), resolution.release);
}
catch (error) {
core.debug(`Failed to write the JDK resolution cache entry for the key ${resolution.key}: ${getErrorMessage(error)}`);
continue;
}
try {
await cache.saveCache([resolution.path], resolution.key);
}
catch (error) {
// A matrix of jobs resolving the same JDK races on the same daily key, so
// an already-reserved key is the expected outcome rather than a problem.
core.debug(`Failed to save the JDK resolution cache with the key ${resolution.key}: ${getErrorMessage(error)}`);
}
}
}
function getResolutionCachePath(request) {
const runnerTemp = process.env['RUNNER_TEMP'];
if (!runnerTemp) {
return undefined;
}
return path__WEBPACK_IMPORTED_MODULE_2___default().join(runnerTemp, RESOLUTION_DIRECTORY, getResolutionIdentity(request));
}
function getResolutionIdentity(request) {
const identity = JSON.stringify({
keyVersion: JDK_RESOLUTION_KEY_VERSION,
runnerOs: getRunnerOs(),
distribution: request.distribution.toLowerCase(),
packageType: request.packageType.toLowerCase(),
platform: request.platform.toLowerCase(),
architecture: request.architecture.toLowerCase(),
versionSpec: request.versionSpec,
stable: request.stable,
source: request.source
});
return (0,crypto__WEBPACK_IMPORTED_MODULE_0__.createHash)('sha256').update(identity).digest('hex');
}
function getResolutionKeyPrefix(request) {
const architecture = request.architecture.toLowerCase();
const digest = getResolutionIdentity(request);
return `setup-java-jdkres-v${JDK_RESOLUTION_KEY_VERSION}-${getRunnerOs()}-${architecture}-${digest}-`;
}
function getRunnerOs() {
return process.env['RUNNER_OS'] ?? process.platform;
}
/**
* Start of the seven-day window the entry was resolved in, which bounds how long
* a floating version spec such as `21` can keep resolving to an already known
* release.
*
* Seven days is the longest usable window: GitHub evicts cache entries that have
* not been accessed for seven days, so a longer one would mean the previous
* entry is already gone when the window rolls over, taking the stale-fallback
* path with it. It also comfortably covers the real release cadence, which is
* monthly at its fastest and usually quarterly.
*/
function getFreshnessBucket() {
const week = 7 * 24 * 60 * 60 * 1000;
return new Date(Math.floor(Date.now() / week) * week)
.toISOString()
.slice(0, 10);
}
/**
* The restored payload drives a download, so it is validated as untrusted input
* rather than trusted because it came back from the cache service.
*/
function parseResolvedRelease(contents) {
const value = JSON.parse(contents);
if (typeof value !== 'object' || value === null) {
throw new Error('The cached resolution is not an object.');
}
const candidate = value;
const version = candidate['version'];
const url = candidate['url'];
const signatureUrl = candidate['signatureUrl'];
const floating = candidate['floating'];
if (typeof version !== 'string' || !version) {
throw new Error('The cached resolution has no version.');
}
assertHttpsUrl(url, 'url');
if (signatureUrl !== undefined) {
assertHttpsUrl(signatureUrl, 'signatureUrl');
}
if (floating !== undefined && typeof floating !== 'boolean') {
throw new Error('The cached resolution has an invalid floating flag.');
}
const release = {
version,
url: url
};
if (signatureUrl !== undefined) {
release.signatureUrl = signatureUrl;
}
if (floating !== undefined) {
release.floating = floating;
}
const checksum = candidate['checksum'];
if (checksum !== undefined) {
release.checksum = parseChecksum(checksum);
}
return release;
}
function parseChecksum(value) {
if (typeof value !== 'object' || value === null) {
throw new Error('The cached checksum is not an object.');
}
const candidate = value;
const algorithm = candidate['algorithm'];
const checksumValue = candidate['value'];
const source = candidate['source'];
if (algorithm !== 'sha256' && algorithm !== 'sha512') {
throw new Error(`Unsupported cached checksum algorithm: ${algorithm}`);
}
if (typeof checksumValue !== 'string' || !checksumValue) {
throw new Error('The cached checksum has no value.');
}
if (source !== undefined && typeof source !== 'string') {
throw new Error('The cached checksum source is not a string.');
}
const checksum = { algorithm, value: checksumValue };
if (source !== undefined) {
checksum.source = source;
}
return checksum;
}
function assertHttpsUrl(value, field) {
if (typeof value !== 'string' || !value) {
throw new Error(`The cached resolution has no ${field}.`);
}
let parsed;
try {
parsed = new URL(value);
}
catch {
throw new Error(`The cached resolution has a malformed ${field}.`);
}
if (parsed.protocol !== 'https:') {
throw new Error(`The cached resolution ${field} does not use HTTPS: ${parsed.protocol}`);
}
}
function parseJdkResolutionState(state) {
const value = JSON.parse(state);
if (!Array.isArray(value) ||
!value.every(item => typeof item === 'object' &&
item !== null &&
typeof item.key === 'string' &&
typeof item.path === 'string' &&
typeof item.release === 'string')) {
throw new Error('Invalid JDK resolution information retrieved from state.');
}
return value;
}
function getErrorMessage(error) {
return error instanceof Error ? error.message : String(error);
}
/***/ })
};
+6 -1
View File
@@ -6,7 +6,8 @@ export const modules = {
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ restore: () => (/* binding */ restore)
/* harmony export */ restore: () => (/* binding */ restore),
/* harmony export */ validatePackageManager: () => (/* binding */ validatePackageManager)
/* harmony export */ });
/* unused harmony export save */
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6928);
@@ -56,6 +57,7 @@ const supportedPackageManager = [
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---gradle
pattern: [
'**/*.gradle*',
'**/gradle.properties',
'**/gradle-wrapper.properties',
'buildSrc/**/Versions.kt',
'buildSrc/**/Dependencies.kt',
@@ -107,6 +109,9 @@ function findPackageManager(id) {
}
return packageManager;
}
function validatePackageManager(id) {
findPackageManager(id);
}
function resolveCachePaths(packageManager, cachePaths) {
return cachePaths.length > 0 ? cachePaths : packageManager.path;
}
+78 -47
View File
@@ -16,8 +16,6 @@ __webpack_require__.d(__webpack_exports__, {
// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js + 7 modules
var core = __webpack_require__(3838);
// EXTERNAL MODULE: ./node_modules/@actions/tool-cache/lib/tool-cache.js + 2 modules
var tool_cache = __webpack_require__(9805);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(9896);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
@@ -70,6 +68,8 @@ var base_installer = __webpack_require__(6242);
var constants = __webpack_require__(7242);
// EXTERNAL MODULE: ./src/util.ts
var util = __webpack_require__(4527);
// EXTERNAL MODULE: ./src/distributions/platform-types.ts
var platform_types = __webpack_require__(7444);
;// CONCATENATED MODULE: ./src/distributions/temurin/installer.ts
@@ -150,7 +150,7 @@ class TemurinDistribution extends base_installer/* JavaBase */.O {
await this.installJmods(javaRelease.version, javaHome);
}
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tool_cache/* cacheDir */.e8(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await (0,util/* cacheJdkDir */.Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
supportsSignatureVerification() {
@@ -249,7 +249,7 @@ class TemurinDistribution extends base_installer/* JavaBase */.O {
case 'win32':
return 'windows';
case 'linux':
if (external_fs_default().existsSync('/etc/alpine-release')) {
if ((0,platform_types/* isAlpineLinux */.G6)()) {
return 'alpine-linux';
}
return 'linux';
@@ -271,25 +271,30 @@ class TemurinDistribution extends base_installer/* JavaBase */.O {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Fh: () => (/* binding */ importKey),
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature)
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature),
/* harmony export */ mS: () => (/* binding */ removeGpgHome),
/* harmony export */ nY: () => (/* binding */ toGpgPath)
/* harmony export */ });
/* unused harmony exports PRIVATE_KEY_FILE, toGpgPath, deleteKey */
/* unused harmony export GPG_HOME_PREFIX */
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8701);
/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5260);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9805);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8701);
/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5260);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9805);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
const PRIVATE_KEY_FILE = path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getTempDir */ .G4(), 'private-key.asc');
const PRIVATE_KEY_FINGERPRINT_REGEX = /\w{40}/;
const GPG_HOME_PREFIX = 'setup-java-gpg-';
const VERIFY_GPG_HOME_PREFIX = 'verify-signature-gpg-home-';
// Convert a Windows path (D:\a\_temp\...) to a POSIX path (/d/a/_temp/...).
// The Git-bundled GPG on Windows (MSYS2-based) uses POSIX path conventions
// internally. Passing Windows paths with backslashes can cause fatal GPG errors
@@ -301,45 +306,71 @@ function toGpgPath(p) {
.replace(/\\/g, '/')
.replace(/^([A-Za-z]):\//, (_, drive) => `/${drive.toLowerCase()}/`);
}
async function importKey(privateKey) {
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(PRIVATE_KEY_FILE, privateKey, {
encoding: 'utf-8',
flag: 'w'
});
let output = '';
const options = {
silent: true,
listeners: {
stdout: (data) => {
output += data.toString();
}
}
};
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
'--batch',
'--import-options',
'import-show',
'--import',
PRIVATE_KEY_FILE
], options);
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(PRIVATE_KEY_FILE);
const match = output.match(PRIVATE_KEY_FINGERPRINT_REGEX);
return match && match[0];
function createGpgHome(prefix) {
const gpgHome = fs__WEBPACK_IMPORTED_MODULE_0__.mkdtempSync(path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getTempDir */ .G4(), prefix));
if (process.platform !== 'win32') {
fs__WEBPACK_IMPORTED_MODULE_0__.chmodSync(gpgHome, 0o700);
}
return gpgHome;
}
async function deleteKey(keyFingerprint) {
await exec.exec('gpg', ['--batch', '--yes', '--delete-secret-and-public-key', keyFingerprint], {
silent: true
});
async function importKey(privateKey) {
const gpgHome = createGpgHome(GPG_HOME_PREFIX);
const privateKeyFile = path__WEBPACK_IMPORTED_MODULE_1__.join(gpgHome, `private-key-${(0,crypto__WEBPACK_IMPORTED_MODULE_2__.randomUUID)()}.asc`);
try {
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(privateKeyFile, privateKey, {
encoding: 'utf-8',
flag: 'wx',
mode: 0o600
});
try {
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(privateKeyFile)
], { silent: true });
}
finally {
fs__WEBPACK_IMPORTED_MODULE_0__.rmSync(privateKeyFile, { force: true });
}
return gpgHome;
}
catch (error) {
await removeGpgHome(gpgHome);
throw error;
}
}
async function removeGpgHome(gpgHome) {
if (!gpgHome) {
return;
}
const resolvedGpgHome = path__WEBPACK_IMPORTED_MODULE_1__.resolve(gpgHome);
const resolvedTempDir = path__WEBPACK_IMPORTED_MODULE_1__.resolve(_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getTempDir */ .G4());
if (path__WEBPACK_IMPORTED_MODULE_1__.dirname(resolvedGpgHome) !== resolvedTempDir ||
!path__WEBPACK_IMPORTED_MODULE_1__.basename(resolvedGpgHome).startsWith(GPG_HOME_PREFIX)) {
throw new Error(`Refusing to remove unexpected GPG home: ${gpgHome}`);
}
if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(resolvedGpgHome)) {
return;
}
try {
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpgconf', ['--homedir', toGpgPath(resolvedGpgHome), '--kill', 'gpg-agent'], { silent: true, ignoreReturnCode: true });
}
catch {
// gpgconf may be unavailable, but directory removal must still be attempted.
}
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(resolvedGpgHome);
}
async function verifyPackageSignature(archivePath, signatureUrl, publicKeyContent) {
const signaturePath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__/* .downloadTool */ .bq(signatureUrl);
const signaturePath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .downloadTool */ .bq(signatureUrl);
let gpgHome;
try {
gpgHome = fs__WEBPACK_IMPORTED_MODULE_0__.mkdtempSync(path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getTempDir */ .G4(), 'verify-signature-gpg-home-'));
gpgHome = createGpgHome(VERIFY_GPG_HOME_PREFIX);
}
catch (error) {
try {
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
}
catch {
// ignore cleanup failures
@@ -350,14 +381,14 @@ async function verifyPackageSignature(archivePath, signatureUrl, publicKeyConten
const publicKeyFile = path__WEBPACK_IMPORTED_MODULE_1__.join(gpgHome, 'public-key.asc');
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(publicKeyFile, publicKeyContent, { encoding: 'utf-8' });
const options = { silent: true };
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(publicKeyFile)
], options);
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
@@ -367,8 +398,8 @@ async function verifyPackageSignature(archivePath, signatureUrl, publicKeyConten
], options);
}
finally {
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(gpgHome);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(gpgHome);
}
}
+3 -3
View File
@@ -13,7 +13,7 @@ export const modules = {
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4527);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9805);
/* harmony import */ var _platform_types_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7444);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6928);
@@ -42,7 +42,7 @@ class LibericaNikDistributions extends _base_installer_js__WEBPACK_IMPORTED_MODU
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_5___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_6___default().join(extractedJavaPath, archiveName);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(range) {
@@ -120,7 +120,7 @@ class LibericaNikDistributions extends _base_installer_js__WEBPACK_IMPORTED_MODU
case 'cygwin':
return 'windows';
case 'linux':
return 'linux';
return (0,_platform_types_js__WEBPACK_IMPORTED_MODULE_4__/* .isAlpineLinux */ .G6)(platform) ? 'linux-musl' : 'linux';
default:
throw new Error(`Platform '${platform}' is not supported. Supported platforms: ${supportedPlatform}`);
}
+23 -23
View File
@@ -9,15 +9,15 @@ export const modules = {
/* harmony export */ SapMachineDistribution: () => (/* binding */ SapMachineDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6242);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4527);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var _platform_types_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7444);
@@ -25,7 +25,7 @@ export const modules = {
class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_6__/* .JavaBase */ .O {
class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
constructor(installerOptions) {
super('SapMachine', installerOptions);
}
@@ -37,7 +37,7 @@ class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
const availableVersions = await this.getAvailableVersions();
const matchedVersions = availableVersions
.filter(item => {
return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(version, item.version);
return (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .isVersionSatisfies */ .y)(version, item.version);
})
.map(item => {
return {
@@ -79,15 +79,15 @@ class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .renameWinArchive */ .n2)(javaArchivePath);
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_3___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_4___default().join(extractedJavaPath, archiveName);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
parseVersions(platform, arch, versions) {
@@ -104,14 +104,14 @@ class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
if (buildVersionWithoutPrefix.split('.').length > 3) {
buildVersionWithoutPrefix = buildVersionWithoutPrefix.replace('+', '.');
}
buildVersionWithoutPrefix = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .convertVersionToSemver */ .ZY)(buildVersionWithoutPrefix);
buildVersionWithoutPrefix = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .convertVersionToSemver */ .ZY)(buildVersionWithoutPrefix);
// ignore invalid version
if (!semver__WEBPACK_IMPORTED_MODULE_2___default().valid(buildVersionWithoutPrefix)) {
if (!semver__WEBPACK_IMPORTED_MODULE_1___default().valid(buildVersionWithoutPrefix)) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Invalid version: ${buildVersionWithoutPrefix}`);
continue;
}
// skip earlyAccessVersions if stable version requested
if (this.stable && buildVersionMap.ea === 'true') {
const isEarlyAccess = buildVersionMap.ea === true || buildVersionMap.ea === 'true';
if (this.stable === isEarlyAccess) {
continue;
}
for (const [edition, editionAssets] of Object.entries(buildVersionMap.assets)) {
@@ -153,7 +153,7 @@ class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
const sortedVersions = eligibleVersions.sort((versionObj1, versionObj2) => {
const version1 = versionObj1.version;
const version2 = versionObj2.version;
return semver__WEBPACK_IMPORTED_MODULE_2___default().compareBuild(version1, version2);
return semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(version1, version2);
});
return sortedVersions.reverse();
}
@@ -165,7 +165,7 @@ class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
return 'macos';
case 'linux':
// figure out if alpine/musl
if (fs__WEBPACK_IMPORTED_MODULE_3___default().existsSync('/etc/alpine-release')) {
if ((0,_platform_types_js__WEBPACK_IMPORTED_MODULE_6__/* .isAlpineLinux */ .G6)()) {
return 'linux-musl';
}
return 'linux';
+3 -3
View File
@@ -13,7 +13,7 @@ export const modules = {
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4527);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9805);
/* harmony import */ var _platform_types_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7444);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6928);
@@ -42,7 +42,7 @@ class LibericaDistributions extends _base_installer_js__WEBPACK_IMPORTED_MODULE_
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_5___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_6___default().join(extractedJavaPath, archiveName);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(range) {
@@ -120,7 +120,7 @@ class LibericaDistributions extends _base_installer_js__WEBPACK_IMPORTED_MODULE_
case 'cygwin':
return 'windows';
case 'linux':
return 'linux';
return (0,_platform_types_js__WEBPACK_IMPORTED_MODULE_4__/* .isAlpineLinux */ .G6)(platform) ? 'linux-musl' : 'linux';
case 'sunos':
return 'solaris';
default:
+22 -20
View File
@@ -9,15 +9,15 @@ export const modules = {
/* harmony export */ DragonwellDistribution: () => (/* binding */ DragonwellDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var _platform_types_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7444);
@@ -25,7 +25,7 @@ export const modules = {
class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Dragonwell', installerOptions);
}
@@ -39,7 +39,7 @@ class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
const availableVersions = await this.getAvailableVersions();
const matchedVersions = availableVersions
.filter(item => {
return (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .isVersionSatisfies */ .y)(version, item.jdk_version);
return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(version, item.jdk_version);
})
.map(item => {
return {
@@ -83,15 +83,15 @@ class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .renameWinArchive */ .n2)(javaArchivePath);
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_3___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_4___default().join(extractedJavaPath, archiveName);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
parseVersions(platform, arch, dragonwellVersions) {
@@ -116,7 +116,7 @@ class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
const jdkVersionNums = jdkVersion
.replace('+', '.')
.split('.');
jdkVersion = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .convertVersionToSemver */ .ZY)(`${jdkVersionNums.slice(0, 3).join('.')}.${jdkVersionNums[jdkVersionNums.length - 1]}`);
jdkVersion = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .convertVersionToSemver */ .ZY)(`${jdkVersionNums.slice(0, 3).join('.')}.${jdkVersionNums[jdkVersionNums.length - 1]}`);
for (const edition in archMap) {
eligibleVersions.push({
os: platform,
@@ -139,7 +139,7 @@ class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
const sortedVersions = eligibleVersions.sort((versionObj1, versionObj2) => {
const version1 = versionObj1.jdk_version;
const version2 = versionObj2.jdk_version;
return semver__WEBPACK_IMPORTED_MODULE_2___default().compareBuild(version1, version2);
return semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(version1, version2);
});
return sortedVersions.reverse();
}
@@ -147,6 +147,8 @@ class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
switch (process.platform) {
case 'win32':
return 'windows';
case 'linux':
return (0,_platform_types_js__WEBPACK_IMPORTED_MODULE_6__/* .isAlpineLinux */ .G6)() ? 'alpine-linux' : 'linux';
default:
return process.platform;
}
@@ -169,7 +171,7 @@ class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE
const branch = 'main';
const filePath = 'releases.json';
const backupUrl = `https://api.github.com/repos/${owner}/${repository}/contents/${filePath}?ref=${branch}`;
const headers = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getGitHubHttpHeaders */ .U_)();
const headers = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getGitHubHttpHeaders */ .U_)();
try {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Trying to fetch available Dragonwell versions info from the backup url: ${backupUrl}`);
const fetchedDragonwellJson = (await this.http.getJson(backupUrl, headers)).result;
+17 -19
View File
@@ -9,16 +9,14 @@ export const modules = {
/* harmony export */ OpenJdkDistribution: () => (/* binding */ OpenJdkDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
@@ -26,7 +24,7 @@ export const modules = {
const OPENJDK_BASE_URL = 'https://jdk.java.net';
class OpenJdkDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
class OpenJdkDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Oracle OpenJDK', installerOptions);
}
@@ -41,8 +39,8 @@ class OpenJdkDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
const platform = this.getPlatform();
const releases = await this.getAvailableVersions(platform, arch);
const matchingReleases = releases
.filter(release => (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .isVersionSatisfies */ .y)(range, release.version))
.sort((left, right) => -semver__WEBPACK_IMPORTED_MODULE_4___default().compareBuild(left.version, right.version));
.filter(release => (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(range, release.version))
.sort((left, right) => -semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(left.version, right.version));
if (!matchingReleases.length) {
throw this.createVersionNotFoundError(range, releases.map(release => release.version), `Platform: ${platform}`);
}
@@ -58,12 +56,12 @@ class OpenJdkDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extension = javaRelease.url.endsWith('.zip') ? 'zip' : 'tar.gz';
if (extension === 'zip') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .renameWinArchive */ .n2)(javaArchivePath);
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, archiveName);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_1___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, archiveName);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async getAvailableVersions(platform, arch) {
@@ -106,7 +104,7 @@ class OpenJdkDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
toSemver(version, urlBuild) {
const [javaVersion, filenameBuild] = version.replace('-ea', '').split('+');
const versionParts = javaVersion.split('.');
const normalizedVersion = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .convertVersionToSemver */ .ZY)(versionParts.length === 1 ? `${javaVersion}.0.0` : javaVersion);
const normalizedVersion = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .convertVersionToSemver */ .ZY)(versionParts.length === 1 ? `${javaVersion}.0.0` : javaVersion);
const build = filenameBuild ?? (versionParts.length <= 3 ? urlBuild : undefined);
return build ? `${normalizedVersion}+${build}` : normalizedVersion;
}
+361
View File
@@ -0,0 +1,361 @@
export const id = 758;
export const ids = [758];
export const modules = {
/***/ 7377:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ restore: () => (/* binding */ restore),
/* harmony export */ validatePackageManager: () => (/* binding */ validatePackageManager)
/* harmony export */ });
/* unused harmony export save */
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(857);
/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _actions_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5295);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* harmony import */ var _actions_glob__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2377);
/**
* @fileoverview this file provides methods handling dependency cache
*/
const STATE_CACHE_PRIMARY_KEY = 'cache-primary-key';
const STATE_CACHE_PATHS = 'cache-paths';
const CACHE_MATCHED_KEY = 'cache-matched-key';
const CACHE_KEY_PREFIX = 'setup-java';
const supportedPackageManager = [
{
id: 'maven',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.m2', 'repository')],
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---maven
pattern: [
'**/pom.xml',
'**/.mvn/wrapper/maven-wrapper.properties',
'**/.mvn/extensions.xml'
],
// The Maven wrapper distribution only depends on the wrapper properties,
// which change very rarely, so it is cached separately from the local
// repository. This keeps it available across the frequent pom.xml changes
// that rotate the main cache key. See issue #1095.
additionalCaches: [
{
name: 'maven-wrapper',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.m2', 'wrapper', 'dists')],
pattern: ['**/.mvn/wrapper/maven-wrapper.properties']
}
]
},
{
id: 'gradle',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.gradle', 'caches')],
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---gradle
pattern: [
'**/*.gradle*',
'**/gradle.properties',
'**/gradle-wrapper.properties',
'buildSrc/**/Versions.kt',
'buildSrc/**/Dependencies.kt',
'gradle/*.versions.toml',
'**/versions.properties'
],
// The Gradle wrapper distribution only depends on the wrapper properties,
// which change very rarely, so it is cached separately from the Gradle
// caches. This keeps it available across the frequent *.gradle* changes
// that rotate the main cache key. See issue #269.
additionalCaches: [
{
name: 'gradle-wrapper',
path: [(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.gradle', 'wrapper')],
pattern: ['**/gradle-wrapper.properties']
}
]
},
{
id: 'sbt',
path: [
(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.ivy2', 'cache'),
(0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.sbt'),
getCoursierCachePath(),
// Some files should not be cached to avoid resolution problems.
// In particular the resolution of snapshots (ideological gap between maven/ivy).
'!' + (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.sbt', '*.lock'),
'!' + (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '**', 'ivydata-*.properties')
],
pattern: [
'**/*.sbt',
'**/project/build.properties',
'**/project/**.scala',
'**/project/**.sbt'
]
}
];
function getCoursierCachePath() {
if (os__WEBPACK_IMPORTED_MODULE_1___default().type() === 'Linux')
return (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), '.cache', 'coursier');
if (os__WEBPACK_IMPORTED_MODULE_1___default().type() === 'Darwin')
return (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), 'Library', 'Caches', 'Coursier');
return (0,path__WEBPACK_IMPORTED_MODULE_0__.join)(os__WEBPACK_IMPORTED_MODULE_1___default().homedir(), 'AppData', 'Local', 'Coursier', 'Cache');
}
function findPackageManager(id) {
const packageManager = supportedPackageManager.find(packageManager => packageManager.id === id);
if (packageManager === undefined) {
throw new Error(`unknown package manager specified: ${id}`);
}
return packageManager;
}
function validatePackageManager(id) {
findPackageManager(id);
}
function resolveCachePaths(packageManager, cachePaths) {
return cachePaths.length > 0 ? cachePaths : packageManager.path;
}
function getCachePathsFromState(packageManager) {
const cachePathsState = core.getState(STATE_CACHE_PATHS);
if (!cachePathsState) {
return packageManager.path;
}
const cachePaths = JSON.parse(cachePathsState);
if (!Array.isArray(cachePaths) ||
!cachePaths.every(cachePath => typeof cachePath === 'string')) {
throw new Error('Invalid cache paths retrieved from state.');
}
return cachePaths;
}
/**
* State keys used to carry an additional cache's restore-time information over
* to the post (save) action, scoped by the additional cache name.
*/
function additionalCachePrimaryKeyState(name) {
return `${STATE_CACHE_PRIMARY_KEY}-${name}`;
}
function additionalCacheMatchedKeyState(name) {
return `${CACHE_MATCHED_KEY}-${name}`;
}
function buildCacheKey(id, fileHash) {
return `${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${process.arch}-${id}-${fileHash}`;
}
/**
* A function that generates a cache key to use.
* Format of the generated key will be "${{ platform }}-${{ id }}-${{ fileHash }}"".
* @see {@link https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows#matching-a-cache-key|spec of cache key}
*/
async function computeCacheKey(packageManager, cacheDependencyPath) {
const pattern = cacheDependencyPath
? cacheDependencyPath.trim().split('\n')
: packageManager.pattern;
const fileHash = await _actions_glob__WEBPACK_IMPORTED_MODULE_4__/* .hashFiles */ .y(pattern.join('\n'));
if (!fileHash) {
throw new Error(`No file in ${process.cwd()} matched to [${pattern}], make sure you have checked out the target repository`);
}
return buildCacheKey(packageManager.id, fileHash);
}
/**
* Computes the cache key for an additional cache. Unlike {@link computeCacheKey}
* this returns undefined (instead of throwing) when no file matches the pattern,
* because additional caches are optional features that many projects do not use.
*/
async function computeAdditionalCacheKey(additionalCache) {
const fileHash = await _actions_glob__WEBPACK_IMPORTED_MODULE_4__/* .hashFiles */ .y(additionalCache.pattern.join('\n'));
if (!fileHash) {
return undefined;
}
return buildCacheKey(additionalCache.name, fileHash);
}
/**
* Restore the dependency cache
* @param id ID of the package manager, should be "maven", "gradle", or "sbt"
* @param cacheDependencyPath The path to a dependency file
* @param cachePaths Paths to cache instead of the package manager defaults
*/
async function restore(id, cacheDependencyPath, cachePaths = []) {
const packageManager = findPackageManager(id);
const resolvedCachePaths = resolveCachePaths(packageManager, cachePaths);
const [primaryKey, preparedAdditionalCaches] = await Promise.all([
computeCacheKey(packageManager, cacheDependencyPath),
prepareAdditionalCaches(packageManager.additionalCaches ?? [])
]);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`primary key is ${primaryKey}`);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .saveState */ .LZ(STATE_CACHE_PRIMARY_KEY, primaryKey);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .saveState */ .LZ(STATE_CACHE_PATHS, JSON.stringify(resolvedCachePaths));
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .setOutput */ .uH(STATE_CACHE_PRIMARY_KEY, primaryKey);
for (const preparedCache of preparedAdditionalCaches) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`${preparedCache.cache.name} primary key is ${preparedCache.primaryKey}`);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .saveState */ .LZ(additionalCachePrimaryKeyState(preparedCache.cache.name), preparedCache.primaryKey);
}
await Promise.all([
restorePrimaryCache(packageManager, resolvedCachePaths, primaryKey),
...preparedAdditionalCaches.map(preparedCache => restoreAdditionalCache(preparedCache))
]);
}
async function restorePrimaryCache(packageManager, cachePaths, primaryKey) {
// No "restoreKeys" is set, to start with a clear cache after dependency update (see https://github.com/actions/setup-java/issues/269)
const matchedKey = await _actions_cache__WEBPACK_IMPORTED_MODULE_2__/* .restoreCache */ .P3(cachePaths, primaryKey);
if (matchedKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .saveState */ .LZ(CACHE_MATCHED_KEY, matchedKey);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .setOutput */ .uH('cache-hit', matchedKey === primaryKey);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Cache restored from key: ${matchedKey}`);
}
else {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .setOutput */ .uH('cache-hit', false);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`${packageManager.id} cache is not found`);
}
}
/**
* Compute keys for additional caches (e.g. build-tool wrapper distributions).
* Additional caches without a matching configuration file are omitted.
*/
async function prepareAdditionalCaches(additionalCaches) {
const preparedCaches = await Promise.all(additionalCaches.map(async (additionalCache) => {
const primaryKey = await computeAdditionalCacheKey(additionalCache);
if (!primaryKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`No file matched [${additionalCache.pattern}] for the ${additionalCache.name} cache, skipping.`);
return undefined;
}
return { cache: additionalCache, primaryKey };
}));
return preparedCaches.filter((preparedCache) => preparedCache !== undefined);
}
/**
* Restore an additional cache keyed independently of the main dependency cache.
*/
async function restoreAdditionalCache(preparedCache) {
const { cache: additionalCache, primaryKey } = preparedCache;
const matchedKey = await _actions_cache__WEBPACK_IMPORTED_MODULE_2__/* .restoreCache */ .P3(additionalCache.path, primaryKey);
if (matchedKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .saveState */ .LZ(additionalCacheMatchedKeyState(additionalCache.name), matchedKey);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`${additionalCache.name} cache restored from key: ${matchedKey}`);
}
else {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`${additionalCache.name} cache is not found`);
}
}
/**
* Save the dependency cache
* @param id ID of the package manager, should be "maven" or "gradle"
*/
async function save(id) {
const packageManager = findPackageManager(id);
const cachePaths = getCachePathsFromState(packageManager);
const matchedKey = core.getState(CACHE_MATCHED_KEY);
// Inputs are re-evaluated before the post action, so we want the original key used for restore
const primaryKey = core.getState(STATE_CACHE_PRIMARY_KEY);
for (const additionalCache of packageManager.additionalCaches ?? []) {
try {
await saveAdditionalCache(packageManager, additionalCache);
}
catch (error) {
const err = error;
core.warning(`Failed to save ${additionalCache.name} cache: ${err.message}. Continuing with primary cache save.`);
}
}
if (!primaryKey) {
core.warning('Error retrieving key from state.');
return;
}
else if (matchedKey === primaryKey) {
// no change in target directories
core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`);
return;
}
try {
const cacheId = await cache.saveCache(cachePaths, primaryKey);
if (cacheId === -1) {
// saveCache returns -1 without throwing when the cache was not saved,
// e.g. a reserve collision or a read-only token (fork PR). @actions/cache
// has already logged the reason at the appropriate severity, so just
// trace it instead of misreporting that the cache was saved.
core.debug(`Cache was not saved for the key: ${primaryKey}`);
return;
}
core.info(`Cache saved with the key: ${primaryKey}`);
}
catch (error) {
const err = error;
if (err.name === cache.ReserveCacheError.name) {
core.info(err.message);
}
else {
if (isProbablyGradleDaemonProblem(packageManager, err)) {
core.warning('Failed to save Gradle cache on Windows. If tar.exe reported "Permission denied", try to run Gradle with `--no-daemon` option. Refer to https://github.com/actions/cache/issues/454 for details.');
}
throw error;
}
}
}
/**
* Save an additional cache under its own key. Skips when no key was recorded at
* restore time (feature unused) or when the exact key was already restored.
*/
async function saveAdditionalCache(packageManager, additionalCache) {
const primaryKey = core.getState(additionalCachePrimaryKeyState(additionalCache.name));
const matchedKey = core.getState(additionalCacheMatchedKeyState(additionalCache.name));
if (!primaryKey) {
// The feature is not used by this project, nothing to save.
core.debug(`No primary key for the ${additionalCache.name} cache, not saving cache.`);
return;
}
else if (matchedKey === primaryKey) {
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(cachePaths, primaryKey);
if (cacheId === -1) {
core.debug(`${additionalCache.name} cache was not saved for the key: ${primaryKey}`);
return;
}
core.info(`${additionalCache.name} cache saved with the key: ${primaryKey}`);
}
catch (error) {
const err = error;
if (err.name === cache.ValidationError.name) {
// The cache paths did not resolve, e.g. the wrapper distribution was
// never downloaded because a system build tool was used or the download
// failed. Optional wrapper caches must not fail the post step, so skip.
core.debug(`${additionalCache.name} cache paths do not exist, not saving cache: ${err.message}`);
return;
}
if (err.name === cache.ReserveCacheError.name) {
core.info(err.message);
}
else {
if (isProbablyGradleDaemonProblem(packageManager, err)) {
core.warning(`Failed to save ${additionalCache.name} cache on Windows. If tar.exe reported "Permission denied", try to run Gradle with \`--no-daemon\` option. Refer to https://github.com/actions/cache/issues/454 for details.`);
}
throw error;
}
}
}
/**
* @param packageManager the specified package manager by user
* @param error the error thrown by the saveCache
* @returns true if the given error seems related to the {@link https://github.com/actions/cache/issues/454|running Gradle Daemon issue}.
* @see {@link https://github.com/actions/cache/issues/454#issuecomment-840493935|why --no-daemon is necessary}
*/
function isProbablyGradleDaemonProblem(packageManager, error) {
if (packageManager.id !== 'gradle' ||
process.env['RUNNER_OS'] !== 'Windows') {
return false;
}
const message = error.message || '';
return message.startsWith('Tar failed with error: ');
}
/***/ })
};
+229
View File
@@ -0,0 +1,229 @@
export const id = 779;
export const ids = [779,394];
export const modules = {
/***/ 1394:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ isCacheFeatureAvailable: () => (/* binding */ isCacheFeatureAvailable)
/* harmony export */ });
/* harmony import */ var _actions_cache__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6971);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3838);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4527);
function isCacheFeatureAvailable() {
if (_actions_cache__WEBPACK_IMPORTED_MODULE_0__/* .isFeatureAvailable */ .w3()) {
return true;
}
if ((0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .isGhes */ .aT)()) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .warning */ .$e('Caching is only supported on GHES version >= 3.5. If you are on a version >= 3.5, please check with your GHES admin if the Actions cache service is enabled or not.');
return false;
}
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .warning */ .$e('The runner was not able to contact the cache service. Caching will be skipped');
return false;
}
/***/ }),
/***/ 5779:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ buildJdkCacheKey: () => (/* binding */ buildJdkCacheKey),
/* harmony export */ getJdkVerificationIdentity: () => (/* binding */ getJdkVerificationIdentity),
/* harmony export */ registerJdk: () => (/* binding */ registerJdk),
/* harmony export */ restoreJdk: () => (/* binding */ restoreJdk),
/* harmony export */ saveJdkCaches: () => (/* binding */ saveJdkCaches)
/* harmony export */ });
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _actions_cache__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6971);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3838);
/* harmony import */ var _cache_feature_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1394);
const STATE_JDK_CACHES = 'jdk-caches';
const JDK_CACHE_KEY_VERSION = 1;
const restoredCaches = [];
async function restoreJdk(jdk) {
if (!jdk.path || !(0,_cache_feature_js__WEBPACK_IMPORTED_MODULE_5__.isCacheFeatureAvailable)()) {
return false;
}
const key = buildJdkCacheKey(jdk);
let matchedKey;
try {
matchedKey = await _actions_cache__WEBPACK_IMPORTED_MODULE_3__/* .restoreCache */ .P3([jdk.path], key);
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .warning */ .$e(`Failed to restore JDK cache: ${error.message}`);
}
const architecturePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(jdk.path, jdk.architecture);
if (matchedKey &&
(!fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(architecturePath) ||
!fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(`${architecturePath}.complete`))) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .warning */ .$e(`JDK cache key ${matchedKey} was restored without the expected tool-cache path; downloading the JDK instead.`);
matchedKey = undefined;
}
recordJdkCache({
key,
path: jdk.path,
architecture: jdk.architecture,
matchedKey
});
if (matchedKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .info */ .pq(`JDK cache restored from key: ${matchedKey}`);
return true;
}
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .info */ .pq(`JDK cache is not found for ${jdk.distribution} ${jdk.version}`);
return false;
}
function registerJdk(jdk) {
if (!jdk.path) {
return;
}
recordJdkCache({
key: buildJdkCacheKey(jdk),
path: jdk.path,
architecture: jdk.architecture,
installation: getInstallationIdentity(jdk.path, jdk.architecture)
});
}
/**
* Cheap fingerprint of the installation stored at a tool-cache path. The
* `<architecture>.complete` marker is (re)created by `tc.cacheDir` every time an
* installation is written, so its inode and timestamps change whenever the
* installation is replaced. This avoids rehashing a multi-hundred-megabyte JDK
* directory while still detecting that the bytes behind a key were swapped.
*/
function getInstallationIdentity(jdkPath, architecture) {
const architecturePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(jdkPath, architecture);
try {
const marker = fs__WEBPACK_IMPORTED_MODULE_1___default().statSync(`${architecturePath}.complete`);
const installation = fs__WEBPACK_IMPORTED_MODULE_1___default().statSync(architecturePath);
return [
marker.ino,
marker.mtimeMs,
marker.ctimeMs,
marker.size,
installation.ino,
installation.mtimeMs,
installation.ctimeMs
].join(':');
}
catch {
return undefined;
}
}
function getJdkVerificationIdentity(verifySignature, publicKey) {
if (!verifySignature) {
return 'unverified';
}
if (!publicKey) {
return 'verified:bundled';
}
const normalizedKey = publicKey.replace(/\r\n?/g, '\n').trim();
const fingerprint = (0,crypto__WEBPACK_IMPORTED_MODULE_0__.createHash)('sha256').update(normalizedKey).digest('hex');
return `verified:custom:sha256:${fingerprint}`;
}
async function saveJdkCaches() {
const state = _actions_core__WEBPACK_IMPORTED_MODULE_4__/* .getState */ .Gu(STATE_JDK_CACHES);
if (!state) {
return;
}
const caches = parseJdkCacheState(state);
for (const jdk of caches) {
if (jdk.matchedKey === jdk.key) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .info */ .pq(`Cache hit occurred on the JDK primary key ${jdk.key}, not saving cache.`);
continue;
}
if (!fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(jdk.path)) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`JDK cache path does not exist, not saving: ${jdk.path}`);
continue;
}
if (!jdk.installation) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`No JDK installation was registered for the key ${jdk.key}, not saving cache.`);
continue;
}
if (getInstallationIdentity(jdk.path, jdk.architecture) !== jdk.installation) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .warning */ .$e(`The JDK installation in ${jdk.path} was replaced after it was registered for the key ${jdk.key}; not saving cache.`);
continue;
}
try {
const cacheId = await _actions_cache__WEBPACK_IMPORTED_MODULE_3__/* .saveCache */ .Io([jdk.path], jdk.key);
if (cacheId !== -1) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .info */ .pq(`JDK cache saved with the key: ${jdk.key}`);
}
}
catch (error) {
const err = error;
if (err.name === _actions_cache__WEBPACK_IMPORTED_MODULE_3__/* .ReserveCacheError */ .Zh.name) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .info */ .pq(err.message);
}
else {
// Saving is best-effort and per entry: one failure must not suppress
// the remaining JDK caches.
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .warning */ .$e(`Failed to save the JDK cache with the key ${jdk.key}: ${err.message}`);
}
}
}
}
function buildJdkCacheKey(jdk) {
const runnerOs = process.env['RUNNER_OS'] ?? process.platform;
const normalizedArchitecture = jdk.architecture.toLowerCase();
const identity = JSON.stringify({
keyVersion: JDK_CACHE_KEY_VERSION,
runnerOs,
distribution: jdk.distribution.toLowerCase(),
packageType: jdk.packageType.toLowerCase(),
architecture: normalizedArchitecture,
version: jdk.version,
source: jdk.source,
verification: jdk.verification
});
const digest = (0,crypto__WEBPACK_IMPORTED_MODULE_0__.createHash)('sha256').update(identity).digest('hex');
return `setup-java-jdk-v${JDK_CACHE_KEY_VERSION}-${runnerOs}-${normalizedArchitecture}-${digest}`;
}
function recordJdkCache(jdk) {
const existing = restoredCaches.findIndex(item => item.key === jdk.key && item.path === jdk.path);
if (existing === -1) {
restoredCaches.push(jdk);
}
else {
restoredCaches[existing] = { ...restoredCaches[existing], ...jdk };
}
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .saveState */ .LZ(STATE_JDK_CACHES, JSON.stringify(restoredCaches));
}
function parseJdkCacheState(state) {
const value = JSON.parse(state);
if (!Array.isArray(value) ||
!value.every(item => typeof item === 'object' &&
item !== null &&
typeof item.key === 'string' &&
typeof item.path === 'string' &&
typeof item.architecture === 'string' &&
(item.matchedKey === undefined ||
typeof item.matchedKey === 'string') &&
(item.installation === undefined ||
typeof item.installation === 'string'))) {
throw new Error('Invalid JDK cache information retrieved from state.');
}
return value;
}
/***/ })
};
+233 -63
View File
@@ -10,7 +10,11 @@ __webpack_require__.r(__webpack_exports__);
/* harmony export */ configureAuthentication: () => (/* binding */ configureAuthentication),
/* harmony export */ createAuthenticationSettings: () => (/* binding */ createAuthenticationSettings),
/* harmony export */ generate: () => (/* binding */ generate),
/* harmony export */ getInputWithDeprecatedAlias: () => (/* binding */ getInputWithDeprecatedAlias)
/* harmony export */ getInputWithDeprecatedAlias: () => (/* binding */ getInputWithDeprecatedAlias),
/* harmony export */ getMavenRepositorySettings: () => (/* binding */ getMavenRepositorySettings),
/* harmony export */ getMavenServerSettings: () => (/* binding */ getMavenServerSettings),
/* harmony export */ parseMavenRepositories: () => (/* binding */ parseMavenRepositories),
/* harmony export */ parseMavenServerCredentials: () => (/* binding */ parseMavenServerCredentials)
/* harmony export */ });
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
@@ -34,9 +38,8 @@ __webpack_require__.r(__webpack_exports__);
async function configureAuthentication() {
const id = _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getInput */ .V4(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_ID */ .fd);
const usernameEnvVar = getInputWithDeprecatedAlias(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_USERNAME_ENV_VAR */ .sc, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_USERNAME_DEPRECATED */ .sp, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_DEFAULT_SERVER_USERNAME */ .Wj);
const passwordEnvVar = getInputWithDeprecatedAlias(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_PASSWORD_ENV_VAR */ .r4, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_PASSWORD_DEPRECATED */ .Vt, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_DEFAULT_SERVER_PASSWORD */ .xp);
const servers = getMavenServerSettings();
const repositorySettings = getMavenRepositorySettings();
const settingsDirectory = _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getInput */ .V4(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SETTINGS_PATH */ .Xh) ||
path__WEBPACK_IMPORTED_MODULE_0__.join(os__WEBPACK_IMPORTED_MODULE_4__.homedir(), _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .M2_DIR */ .iT);
const overwriteSettings = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getBooleanInput */ .Vt)(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_OVERWRITE_SETTINGS */ .TS, true);
@@ -46,11 +49,18 @@ async function configureAuthentication() {
if (gpgPrivateKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .setSecret */ .Pq(gpgPrivateKey);
}
await createAuthenticationSettings(id, usernameEnvVar, passwordEnvVar, settingsDirectory, overwriteSettings, gpgPassphraseEnvVar);
await createAuthenticationSettings(servers, settingsDirectory, overwriteSettings, gpgPassphraseEnvVar, repositorySettings);
if (gpgPrivateKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq('Importing private gpg key');
const keyFingerprint = (await _gpg_js__WEBPACK_IMPORTED_MODULE_5__/* .importKey */ .Fh(gpgPrivateKey)) || '';
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .saveState */ .LZ(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .STATE_GPG_PRIVATE_KEY_FINGERPRINT */ .wm, keyFingerprint);
const gpgHome = await _gpg_js__WEBPACK_IMPORTED_MODULE_5__/* .importKey */ .Fh(gpgPrivateKey);
try {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .saveState */ .LZ(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .STATE_GPG_HOME */ .Fi, gpgHome);
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .exportVariable */ .dN('GNUPGHOME', _gpg_js__WEBPACK_IMPORTED_MODULE_5__/* .toGpgPath */ .nY(gpgHome));
}
catch (error) {
await _gpg_js__WEBPACK_IMPORTED_MODULE_5__/* .removeGpgHome */ .mS(gpgHome);
throw error;
}
}
}
function getInputWithDeprecatedAlias(inputName, deprecatedInputName, defaultValue) {
@@ -61,15 +71,106 @@ function getInputWithDeprecatedAlias(inputName, deprecatedInputName, defaultValu
}
return value || deprecatedValue || defaultValue || '';
}
async function createAuthenticationSettings(id, usernameEnvVar, passwordEnvVar, settingsDirectory, overwriteSettings, gpgPassphraseEnvVar = undefined) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Creating ${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MVN_SETTINGS_FILE */ .vO} with server-id: ${id}`);
// only exported for testing purposes
function getMavenServerSettings() {
const entries = _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getMultilineInput */ .q3(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_MVN_SERVER_CREDENTIALS */ .MM);
if (entries.some(entry => entry.trim())) {
return parseMavenServerCredentials(entries);
}
return [
{
id: _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getInput */ .V4(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_ID */ .fd),
usernameEnvVar: getInputWithDeprecatedAlias(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_USERNAME_ENV_VAR */ .sc, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_USERNAME_DEPRECATED */ .sp, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_DEFAULT_SERVER_USERNAME */ .Wj),
passwordEnvVar: getInputWithDeprecatedAlias(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_PASSWORD_ENV_VAR */ .r4, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_SERVER_PASSWORD_DEPRECATED */ .Vt, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_DEFAULT_SERVER_PASSWORD */ .xp)
}
];
}
// only exported for testing purposes
function parseMavenServerCredentials(entries) {
const servers = [];
const serverIds = new Set();
entries.forEach((entry, index) => {
if (!entry.trim()) {
return;
}
const fields = entry.split(':');
if (fields.length !== 3) {
throw new Error(`Invalid mvn-server-credentials entry at line ${index + 1}. Expected format: server-id:USERNAME_ENV:PASSWORD_ENV`);
}
const [id, usernameEnvVar, passwordEnvVar] = fields.map(field => field.trim());
if (!id || !usernameEnvVar || !passwordEnvVar) {
throw new Error(`Invalid mvn-server-credentials entry at line ${index + 1}. server-id, username environment variable, and password environment variable are required`);
}
if (serverIds.has(id)) {
throw new Error(`Duplicate server-id '${id}' in mvn-server-credentials input`);
}
serverIds.add(id);
servers.push({ id, usernameEnvVar, passwordEnvVar });
});
return servers;
}
// only exported for testing purposes
function getMavenRepositorySettings() {
const entries = _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getMultilineInput */ .q3(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_MVN_REPOSITORIES */ .W2);
if (!entries.some(entry => entry.trim())) {
return undefined;
}
const includeCentral = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getBooleanInput */ .Vt)(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_MVN_REPOSITORIES_INCLUDE_CENTRAL */ .H5, true);
return {
repositories: parseMavenRepositories(entries, includeCentral),
includeCentral,
prioritizeCentral: (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getBooleanInput */ .Vt)(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_MVN_REPOSITORIES_PRIORITIZE_CENTRAL */ .OT, true)
};
}
// only exported for testing purposes
function parseMavenRepositories(entries, includeCentral) {
const repositories = [];
const repositoryIds = new Set();
entries.forEach((entry, index) => {
if (!entry.trim()) {
return;
}
const firstSeparator = entry.indexOf(':');
const lastSeparator = entry.lastIndexOf(':');
if (firstSeparator <= 0 || lastSeparator <= firstSeparator) {
throw new Error(`Invalid mvn-repositories entry at line ${index + 1}. Expected format: repository-id:repository-url:snapshots-enabled`);
}
const id = entry.slice(0, firstSeparator).trim();
const url = entry.slice(firstSeparator + 1, lastSeparator).trim();
const snapshotsValue = entry
.slice(lastSeparator + 1)
.trim()
.toLowerCase();
if (!id || !url || !snapshotsValue) {
throw new Error(`Invalid mvn-repositories entry at line ${index + 1}. repository-id, repository URL, and snapshots-enabled are required`);
}
if (snapshotsValue !== 'true' && snapshotsValue !== 'false') {
throw new Error(`Invalid snapshots-enabled value '${snapshotsValue}' in mvn-repositories entry at line ${index + 1}. Expected true or false`);
}
if (repositoryIds.has(id)) {
throw new Error(`Duplicate repository-id '${id}' in mvn-repositories input`);
}
if (includeCentral && id === _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_CENTRAL_REPOSITORY_ID */ .xg) {
throw new Error(`Repository-id '${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_CENTRAL_REPOSITORY_ID */ .xg}' is reserved when ${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_MVN_REPOSITORIES_INCLUDE_CENTRAL */ .H5} is enabled`);
}
repositoryIds.add(id);
repositories.push({
id,
url,
snapshotsEnabled: snapshotsValue === 'true'
});
});
return repositories;
}
async function createAuthenticationSettings(servers, settingsDirectory, overwriteSettings, gpgPassphraseEnvVar = undefined, repositorySettings = undefined) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Creating ${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MVN_SETTINGS_FILE */ .vO} with server-id: ${servers.map(server => server.id).join(', ')}`);
// when an alternate m2 location is specified use only that location (no .m2 directory)
// otherwise use the home/.m2/ path
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .mkdirP */ .U$(settingsDirectory);
await write(settingsDirectory, generate(id, usernameEnvVar, passwordEnvVar, gpgPassphraseEnvVar), overwriteSettings);
await write(settingsDirectory, generate(servers, gpgPassphraseEnvVar, repositorySettings), overwriteSettings);
}
// only exported for testing purposes
function generate(id, usernameEnvVar, passwordEnvVar, gpgPassphraseEnvVar) {
function generate(servers, gpgPassphraseEnvVar, repositorySettings) {
// The maven-gpg-plugin reads the passphrase from the environment variable
// named by the `gpg.passphraseEnvName` property (default MAVEN_GPG_PASSPHRASE).
// Only configure it when the requested env var name differs from that default;
@@ -83,16 +184,54 @@ function generate(id, usernameEnvVar, passwordEnvVar, gpgPassphraseEnvVar) {
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
' xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">',
' <interactiveMode>false</interactiveMode>',
' <servers>',
' <server>',
` <id>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(id)}</id>`,
` <username>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(`\${env.${usernameEnvVar}}`)}</username>`,
` <password>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(`\${env.${passwordEnvVar}}`)}</password>`,
' </server>',
' </servers>'
' <servers>'
];
if (includeGpgPassphraseProfile) {
lines.push(' <profiles>', ' <profile>', ` <id>${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .GPG_PASSPHRASE_PROFILE_ID */ .K$}</id>`, ' <properties>', ` <gpg.passphraseEnvName>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(gpgPassphraseEnvVar)}</gpg.passphraseEnvName>`, ' </properties>', ' </profile>', ' </profiles>', ' <activeProfiles>', ` <activeProfile>${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .GPG_PASSPHRASE_PROFILE_ID */ .K$}</activeProfile>`, ' </activeProfiles>');
for (const server of servers) {
lines.push(' <server>', ` <id>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(server.id)}</id>`, ` <username>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(`\${env.${server.usernameEnvVar}}`)}</username>`, ` <password>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(`\${env.${server.passwordEnvVar}}`)}</password>`, ' </server>');
}
lines.push(' </servers>');
if (repositorySettings || includeGpgPassphraseProfile) {
lines.push(' <profiles>');
if (repositorySettings) {
const centralRepository = {
id: _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_CENTRAL_REPOSITORY_ID */ .xg,
url: _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_CENTRAL_REPOSITORY_URL */ .jv,
snapshotsEnabled: false
};
const customCentralConfigured = repositorySettings.repositories.some(repository => repository.id === _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_CENTRAL_REPOSITORY_ID */ .xg);
const repositories = repositorySettings.includeCentral
? repositorySettings.prioritizeCentral
? [centralRepository, ...repositorySettings.repositories]
: [...repositorySettings.repositories, centralRepository]
: customCentralConfigured
? repositorySettings.repositories
: [
...repositorySettings.repositories,
{ ...centralRepository, releasesEnabled: false }
];
lines.push(' <profile>', ` <id>${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_REPOSITORIES_PROFILE_ID */ .hq}</id>`, ' <repositories>');
for (const repository of repositories) {
lines.push(' <repository>', ` <id>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(repository.id)}</id>`, ` <url>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(repository.url)}</url>`, ...(repository.releasesEnabled === undefined
? []
: [
' <releases>',
` <enabled>${repository.releasesEnabled}</enabled>`,
' </releases>'
]), ' <snapshots>', ` <enabled>${repository.snapshotsEnabled}</enabled>`, ' </snapshots>', ' </repository>');
}
lines.push(' </repositories>', ' </profile>');
}
if (includeGpgPassphraseProfile) {
lines.push(' <profile>', ` <id>${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .GPG_PASSPHRASE_PROFILE_ID */ .K$}</id>`, ' <properties>', ` <gpg.passphraseEnvName>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_8__/* .escapeXmlText */ .I)(gpgPassphraseEnvVar)}</gpg.passphraseEnvName>`, ' </properties>', ' </profile>');
}
lines.push(' </profiles>', ' <activeProfiles>');
if (repositorySettings) {
lines.push(` <activeProfile>${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_REPOSITORIES_PROFILE_ID */ .hq}</activeProfile>`);
}
if (includeGpgPassphraseProfile) {
lines.push(` <activeProfile>${_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .GPG_PASSPHRASE_PROFILE_ID */ .K$}</activeProfile>`);
}
lines.push(' </activeProfiles>');
}
lines.push('</settings>');
return lines.join('\n');
@@ -124,25 +263,30 @@ async function write(directory, settings, overwriteSettings) {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Fh: () => (/* binding */ importKey),
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature)
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature),
/* harmony export */ mS: () => (/* binding */ removeGpgHome),
/* harmony export */ nY: () => (/* binding */ toGpgPath)
/* harmony export */ });
/* unused harmony exports PRIVATE_KEY_FILE, toGpgPath, deleteKey */
/* unused harmony export GPG_HOME_PREFIX */
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8701);
/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5260);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9805);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8701);
/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5260);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9805);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
const PRIVATE_KEY_FILE = path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getTempDir */ .G4(), 'private-key.asc');
const PRIVATE_KEY_FINGERPRINT_REGEX = /\w{40}/;
const GPG_HOME_PREFIX = 'setup-java-gpg-';
const VERIFY_GPG_HOME_PREFIX = 'verify-signature-gpg-home-';
// Convert a Windows path (D:\a\_temp\...) to a POSIX path (/d/a/_temp/...).
// The Git-bundled GPG on Windows (MSYS2-based) uses POSIX path conventions
// internally. Passing Windows paths with backslashes can cause fatal GPG errors
@@ -154,45 +298,71 @@ function toGpgPath(p) {
.replace(/\\/g, '/')
.replace(/^([A-Za-z]):\//, (_, drive) => `/${drive.toLowerCase()}/`);
}
async function importKey(privateKey) {
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(PRIVATE_KEY_FILE, privateKey, {
encoding: 'utf-8',
flag: 'w'
});
let output = '';
const options = {
silent: true,
listeners: {
stdout: (data) => {
output += data.toString();
}
}
};
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
'--batch',
'--import-options',
'import-show',
'--import',
PRIVATE_KEY_FILE
], options);
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(PRIVATE_KEY_FILE);
const match = output.match(PRIVATE_KEY_FINGERPRINT_REGEX);
return match && match[0];
function createGpgHome(prefix) {
const gpgHome = fs__WEBPACK_IMPORTED_MODULE_0__.mkdtempSync(path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getTempDir */ .G4(), prefix));
if (process.platform !== 'win32') {
fs__WEBPACK_IMPORTED_MODULE_0__.chmodSync(gpgHome, 0o700);
}
return gpgHome;
}
async function deleteKey(keyFingerprint) {
await exec.exec('gpg', ['--batch', '--yes', '--delete-secret-and-public-key', keyFingerprint], {
silent: true
});
async function importKey(privateKey) {
const gpgHome = createGpgHome(GPG_HOME_PREFIX);
const privateKeyFile = path__WEBPACK_IMPORTED_MODULE_1__.join(gpgHome, `private-key-${(0,crypto__WEBPACK_IMPORTED_MODULE_2__.randomUUID)()}.asc`);
try {
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(privateKeyFile, privateKey, {
encoding: 'utf-8',
flag: 'wx',
mode: 0o600
});
try {
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(privateKeyFile)
], { silent: true });
}
finally {
fs__WEBPACK_IMPORTED_MODULE_0__.rmSync(privateKeyFile, { force: true });
}
return gpgHome;
}
catch (error) {
await removeGpgHome(gpgHome);
throw error;
}
}
async function removeGpgHome(gpgHome) {
if (!gpgHome) {
return;
}
const resolvedGpgHome = path__WEBPACK_IMPORTED_MODULE_1__.resolve(gpgHome);
const resolvedTempDir = path__WEBPACK_IMPORTED_MODULE_1__.resolve(_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getTempDir */ .G4());
if (path__WEBPACK_IMPORTED_MODULE_1__.dirname(resolvedGpgHome) !== resolvedTempDir ||
!path__WEBPACK_IMPORTED_MODULE_1__.basename(resolvedGpgHome).startsWith(GPG_HOME_PREFIX)) {
throw new Error(`Refusing to remove unexpected GPG home: ${gpgHome}`);
}
if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(resolvedGpgHome)) {
return;
}
try {
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpgconf', ['--homedir', toGpgPath(resolvedGpgHome), '--kill', 'gpg-agent'], { silent: true, ignoreReturnCode: true });
}
catch {
// gpgconf may be unavailable, but directory removal must still be attempted.
}
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(resolvedGpgHome);
}
async function verifyPackageSignature(archivePath, signatureUrl, publicKeyContent) {
const signaturePath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__/* .downloadTool */ .bq(signatureUrl);
const signaturePath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .downloadTool */ .bq(signatureUrl);
let gpgHome;
try {
gpgHome = fs__WEBPACK_IMPORTED_MODULE_0__.mkdtempSync(path__WEBPACK_IMPORTED_MODULE_1__.join(_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getTempDir */ .G4(), 'verify-signature-gpg-home-'));
gpgHome = createGpgHome(VERIFY_GPG_HOME_PREFIX);
}
catch (error) {
try {
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
}
catch {
// ignore cleanup failures
@@ -203,14 +373,14 @@ async function verifyPackageSignature(archivePath, signatureUrl, publicKeyConten
const publicKeyFile = path__WEBPACK_IMPORTED_MODULE_1__.join(gpgHome, 'public-key.asc');
fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(publicKeyFile, publicKeyContent, { encoding: 'utf-8' });
const options = { silent: true };
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(publicKeyFile)
], options);
await _actions_exec__WEBPACK_IMPORTED_MODULE_3__/* .exec */ .m('gpg', [
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
@@ -220,8 +390,8 @@ async function verifyPackageSignature(archivePath, signatureUrl, publicKeyConten
], options);
}
finally {
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_2__/* .rmRF */ .Yz(gpgHome);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(gpgHome);
}
}
+7 -9
View File
@@ -13,12 +13,10 @@ export const modules = {
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4527);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9805);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_5__);
@@ -90,10 +88,10 @@ class SemeruDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_0__
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_5___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_6___default().join(extractedJavaPath, archiveName);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_4___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_5___default().join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_4__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
get toolcacheFolderName() {
+50 -37
View File
@@ -10,17 +10,15 @@ export const modules = {
/* harmony export */ GraalVMDistribution: () => (/* binding */ GraalVMDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var _actions_http_client__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4942);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(4527);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _actions_http_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4942);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
@@ -39,7 +37,7 @@ const IS_WINDOWS = process.platform === 'win32';
const GRAALVM_PLATFORM = IS_WINDOWS ? 'windows' : process.platform;
const GRAALVM_MIN_VERSION = 17;
const SUPPORTED_ARCHITECTURES = ['x64', 'aarch64'];
class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions, distributionName = 'GraalVM') {
super(distributionName, installerOptions);
}
@@ -48,29 +46,37 @@ class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
if (IS_WINDOWS) {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .renameWinArchive */ .n2)(javaArchivePath);
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
// Add validation for extracted path
if (!fs__WEBPACK_IMPORTED_MODULE_2___default().existsSync(extractedJavaPath)) {
if (!fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(extractedJavaPath)) {
throw new Error(`Extraction failed: path ${extractedJavaPath} does not exist`);
}
const dirContents = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath);
const dirContents = fs__WEBPACK_IMPORTED_MODULE_1___default().readdirSync(extractedJavaPath);
if (dirContents.length === 0) {
throw new Error('Extraction failed: no files found in extracted directory');
}
const archivePath = path__WEBPACK_IMPORTED_MODULE_3___default().join(extractedJavaPath, dirContents[0]);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, dirContents[0]);
const installedVersion = javaRelease.floating
? (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getJavaVersionFromReleaseFile */ .C4)(archivePath)
: javaRelease.version;
const version = this.getToolcacheVersionName(installedVersion);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: installedVersion, path: javaPath };
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .error */ .z3(`Failed to download and extract GraalVM: ${error}`);
throw error;
}
}
requiresRemoteResolution() {
return (this.distribution === 'GraalVM' &&
this.stable &&
!this.version.includes('.'));
}
setJavaDefault(version, toolPath) {
super.setJavaDefault(version, toolPath);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .exportVariable */ .dN('GRAALVM_HOME', toolPath);
@@ -85,16 +91,23 @@ class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
// builds its download URLs from a concrete major and has no endpoint to list
// releases, so resolve the newest available GA major from the Adoptium API.
if (this.latest) {
range = (await (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .getLatestMajorVersion */ .ri)(this.http)).toString();
range = (await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getLatestMajorVersion */ .ri)(this.http)).toString();
}
const { platform, extension, major } = this.validateStableBuildRequest(range);
const fileUrl = this.constructFileUrl(range, major, platform, arch, extension);
const response = await this.http.head(fileUrl);
this.handleHttpResponse(response, range);
// A major-only range resolves to the vendor's `/latest/` path, whose
// contents change when a new build is published.
const floating = !range.includes('.');
return {
url: fileUrl,
version: range,
checksum: await this.fetchChecksum(`${fileUrl}.sha256`, 'sha256')
checksum: await this.fetchChecksum(`${fileUrl}.sha256`, 'sha256'),
floating,
fingerprint: floating
? (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getArtifactFingerprint */ .VX)(response.message.headers)
: undefined
};
}
validateVersionRange(range) {
@@ -114,7 +127,7 @@ class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
throw new Error(`${this.distribution} provides only the \`jdk\` package type`);
}
const platform = this.getPlatform();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .getDownloadArchiveExtension */ .ag)();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
const major = range.includes('.') ? range.split('.')[0] : range;
const majorVersion = parseInt(major);
if (isNaN(majorVersion)) {
@@ -136,7 +149,7 @@ class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
}
handleHttpResponse(response, range) {
const statusCode = response.message.statusCode;
if (statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.NotFound) {
if (statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_5__/* .HttpCodes */ .Hv.NotFound) {
// Create the standard error with additional hint about checking the download URL
const error = this.createVersionNotFoundError(range);
if (this.latest) {
@@ -145,11 +158,11 @@ class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
error.message += `\nPlease check if this version is available at ${GRAALVM_DOWNLOAD_URL} . Pick a version from the list.`;
throw error;
}
if (statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.Unauthorized ||
statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.Forbidden) {
if (statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_5__/* .HttpCodes */ .Hv.Unauthorized ||
statusCode === _actions_http_client__WEBPACK_IMPORTED_MODULE_5__/* .HttpCodes */ .Hv.Forbidden) {
throw new Error(`Access denied when downloading GraalVM. Status code: ${statusCode}. Please check your credentials or permissions.`);
}
if (statusCode !== _actions_http_client__WEBPACK_IMPORTED_MODULE_6__/* .HttpCodes */ .Hv.OK) {
if (statusCode !== _actions_http_client__WEBPACK_IMPORTED_MODULE_5__/* .HttpCodes */ .Hv.OK) {
throw new Error(`HTTP request for GraalVM failed with status code: ${statusCode} (${response.message.statusMessage || 'Unknown error'})`);
}
}
@@ -182,7 +195,7 @@ class GraalVMDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5_
}
async fetchEAJson(javaEaVersion) {
const url = `https://api.github.com/repos/graalvm/oracle-graalvm-ea-builds/contents/versions/${javaEaVersion}.json?ref=main`;
const headers = (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .getGitHubHttpHeaders */ .U_)();
const headers = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getGitHubHttpHeaders */ .U_)();
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Trying to fetch available version info for GraalVM EA builds from '${url}'`);
try {
const response = await this.http.getJson(url, headers);
@@ -243,7 +256,7 @@ class GraalVMCommunityDistribution extends GraalVMDistribution {
throw new Error(`${this.distribution} provides only the \`jdk\` package type`);
}
platform = this.getPlatform();
extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .getDownloadArchiveExtension */ .ag)();
extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
}
else {
({ platform, extension } = this.validateStableBuildRequest(range));
@@ -253,8 +266,8 @@ class GraalVMCommunityDistribution extends GraalVMDistribution {
const assetSuffix = `_${platform}-${arch}_bin.${extension}`;
const availableVersions = await this.getAvailableVersions(assetSuffix);
const satisfiedVersion = availableVersions
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .isVersionSatisfies */ .y)(range, item.version))
.sort((a, b) => -semver__WEBPACK_IMPORTED_MODULE_4___default().compareBuild(a.version, b.version))[0];
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .isVersionSatisfies */ .y)(range, item.version))
.sort((a, b) => -semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(a.version, b.version))[0];
if (!satisfiedVersion) {
const error = this.createVersionNotFoundError(range, availableVersions.map(item => item.version), `Platform: ${platform}`);
error.message += `\nPlease check if this version is available at ${GRAALVM_COMMUNITY_DOWNLOAD_URL}.`;
@@ -263,10 +276,10 @@ class GraalVMCommunityDistribution extends GraalVMDistribution {
return satisfiedVersion;
}
async getAvailableVersions(assetSuffix) {
const headers = (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .getGitHubHttpHeaders */ .U_)();
const headers = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getGitHubHttpHeaders */ .U_)();
const versions = new Map();
let releasesUrl = GRAALVM_COMMUNITY_RELEASES_URL;
for (let pageIndex = 0; releasesUrl && pageIndex < _util_js__WEBPACK_IMPORTED_MODULE_7__/* .MAX_PAGINATION_PAGES */ .Tp; pageIndex++) {
for (let pageIndex = 0; releasesUrl && pageIndex < _util_js__WEBPACK_IMPORTED_MODULE_6__/* .MAX_PAGINATION_PAGES */ .Tp; pageIndex++) {
const response = await this.http.getJson(releasesUrl, headers);
// A successful GitHub releases listing is always a JSON array (possibly
// empty). Anything else indicates an unexpected/error payload (rate
@@ -322,12 +335,12 @@ class GraalVMCommunityDistribution extends GraalVMDistribution {
if (!GRAALVM_COMMUNITY_VERSION_PATTERN.test(rawVersion)) {
return null;
}
return (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .convertVersionToSemver */ .ZY)(rawVersion);
return (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .convertVersionToSemver */ .ZY)(rawVersion);
}
getNextReleasesUrl(headers) {
const nextUrl = (0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .getNextPageUrlFromLinkHeader */ .rC)(headers);
const nextUrl = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getNextPageUrlFromLinkHeader */ .rC)(headers);
if (nextUrl &&
!(0,_util_js__WEBPACK_IMPORTED_MODULE_7__/* .validatePaginationUrl */ .SA)(nextUrl, GRAALVM_COMMUNITY_RELEASES_PAGE_ORIGIN)) {
!(0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .validatePaginationUrl */ .SA)(nextUrl, GRAALVM_COMMUNITY_RELEASES_PAGE_ORIGIN)) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .warning */ .$e(`Ignoring pagination link with unexpected origin: ${nextUrl}`);
return null;
}
+210 -185
View File
File diff suppressed because it is too large Load Diff
+18 -17
View File
@@ -9,14 +9,14 @@ export const modules = {
/* harmony export */ ZuluDistribution: () => (/* binding */ ZuluDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9805);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6242);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _platform_types_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7444);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
@@ -25,7 +25,7 @@ export const modules = {
class ZuluDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
class ZuluDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Zulu', installerOptions);
}
@@ -50,8 +50,8 @@ class ZuluDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/*
.sort((a, b) => {
// Azul provides two versions: java_version and distro_version
// we should sort by both fields by descending
return (-semver__WEBPACK_IMPORTED_MODULE_4___default().compareBuild(a.version, b.version) ||
-semver__WEBPACK_IMPORTED_MODULE_4___default().compareBuild(a.zuluVersion, b.zuluVersion));
return (-semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(a.version, b.version) ||
-semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(a.zuluVersion, b.zuluVersion));
})
.map((item) => ({
version: item.version,
@@ -90,9 +90,9 @@ class ZuluDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/*
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .renameWinArchive */ .n2)(javaArchivePath);
}
const extractedJavaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .extractJdkFile */ .PE)(javaArchivePath, extension);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_3___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_2___default().join(extractedJavaPath, archiveName);
const javaPath = await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_1__/* .cacheDir */ .e8(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
const archiveName = fs__WEBPACK_IMPORTED_MODULE_2___default().readdirSync(extractedJavaPath)[0];
const archivePath = path__WEBPACK_IMPORTED_MODULE_1___default().join(extractedJavaPath, archiveName);
const javaPath = await (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async getAvailableVersions() {
@@ -182,9 +182,10 @@ class ZuluDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/*
case 'win32':
return 'windows';
case 'linux':
// The new Metadata API's "linux" value returns both glibc and musl packages;
// use "linux_glibc" to target only glibc, which is what standard runners use.
return 'linux_glibc';
// The new Metadata API's "linux" value returns both glibc and musl
// packages, so target the libc the runner actually has. A glibc JDK
// cannot run on Alpine.
return (0,_platform_types_js__WEBPACK_IMPORTED_MODULE_5__/* .isAlpineLinux */ .G6)() ? 'linux_musl' : 'linux_glibc';
default:
return process.platform;
}
+304 -41
View File
@@ -30770,16 +30770,22 @@ module.exports = {
/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
/* harmony export */ At: () => (/* binding */ INPUT_CACHE_DEPENDENCY_PATH),
/* harmony export */ E8: () => (/* binding */ INPUT_SET_DEFAULT),
/* harmony export */ Fi: () => (/* binding */ STATE_GPG_HOME),
/* harmony export */ GL: () => (/* binding */ INPUT_CACHE_JDK),
/* harmony export */ H5: () => (/* binding */ INPUT_MVN_REPOSITORIES_INCLUDE_CENTRAL),
/* harmony export */ I9: () => (/* binding */ INPUT_FORCE_DOWNLOAD),
/* harmony export */ K$: () => (/* binding */ GPG_PASSPHRASE_PROFILE_ID),
/* harmony export */ LS: () => (/* binding */ INPUT_ARCHITECTURE),
/* harmony export */ MM: () => (/* binding */ INPUT_MVN_SERVER_CREDENTIALS),
/* harmony export */ OD: () => (/* binding */ INPUT_DEFAULT_GPG_PRIVATE_KEY),
/* harmony export */ OT: () => (/* binding */ INPUT_MVN_REPOSITORIES_PRIORITIZE_CENTRAL),
/* harmony export */ PG: () => (/* binding */ MACOS_JAVA_CONTENT_POSTFIX),
/* harmony export */ QM: () => (/* binding */ INPUT_JAVA_VERSION),
/* harmony export */ RX: () => (/* binding */ INPUT_DEFAULT_GPG_PASSPHRASE),
/* harmony export */ TS: () => (/* binding */ INPUT_OVERWRITE_SETTINGS),
/* harmony export */ TY: () => (/* binding */ INPUT_GPG_PASSPHRASE_DEPRECATED),
/* harmony export */ Vt: () => (/* binding */ INPUT_SERVER_PASSWORD_DEPRECATED),
/* harmony export */ W2: () => (/* binding */ INPUT_MVN_REPOSITORIES),
/* harmony export */ Wj: () => (/* binding */ INPUT_DEFAULT_SERVER_USERNAME),
/* harmony export */ Wt: () => (/* binding */ INPUT_PROBLEM_MATCHER),
/* harmony export */ Xh: () => (/* binding */ INPUT_SETTINGS_PATH),
@@ -30790,7 +30796,9 @@ module.exports = {
/* harmony export */ fd: () => (/* binding */ INPUT_SERVER_ID),
/* harmony export */ g_: () => (/* binding */ INPUT_DISTRIBUTION),
/* harmony export */ gk: () => (/* binding */ INPUT_CACHE),
/* harmony export */ hq: () => (/* binding */ MAVEN_REPOSITORIES_PROFILE_ID),
/* harmony export */ iT: () => (/* binding */ M2_DIR),
/* harmony export */ jv: () => (/* binding */ MAVEN_CENTRAL_REPOSITORY_URL),
/* harmony export */ kM: () => (/* binding */ INPUT_JDK_FILE),
/* harmony export */ kN: () => (/* binding */ MAVEN_NO_TRANSFER_PROGRESS_LONG_FLAG),
/* harmony export */ ko: () => (/* binding */ MAVEN_GPG_PASSPHRASE_DEFAULT_ENV),
@@ -30809,8 +30817,8 @@ module.exports = {
/* harmony export */ vO: () => (/* binding */ MVN_SETTINGS_FILE),
/* harmony export */ wX: () => (/* binding */ INPUT_SHOW_DOWNLOAD_PROGRESS),
/* harmony export */ wc: () => (/* binding */ INPUT_JDK_FILE_DEPRECATED),
/* harmony export */ wm: () => (/* binding */ STATE_GPG_PRIVATE_KEY_FINGERPRINT),
/* harmony export */ wz: () => (/* binding */ INPUT_GPG_PRIVATE_KEY),
/* harmony export */ xg: () => (/* binding */ MAVEN_CENTRAL_REPOSITORY_ID),
/* harmony export */ xp: () => (/* binding */ INPUT_DEFAULT_SERVER_PASSWORD)
/* harmony export */ });
/* unused harmony exports INPUT_CACHE_READ_ONLY, INPUT_JOB_STATUS */
@@ -30828,6 +30836,10 @@ const INPUT_SET_DEFAULT = 'set-default';
const INPUT_PROBLEM_MATCHER = 'problem-matcher';
const INPUT_VERIFY_SIGNATURE = 'verify-signature';
const INPUT_VERIFY_SIGNATURE_PUBLIC_KEY = 'verify-signature-public-key';
const INPUT_MVN_SERVER_CREDENTIALS = 'mvn-server-credentials';
const INPUT_MVN_REPOSITORIES = 'mvn-repositories';
const INPUT_MVN_REPOSITORIES_INCLUDE_CENTRAL = 'mvn-repositories-include-central';
const INPUT_MVN_REPOSITORIES_PRIORITIZE_CENTRAL = 'mvn-repositories-prioritize-central';
const INPUT_SERVER_ID = 'server-id';
const INPUT_SERVER_USERNAME_ENV_VAR = 'server-username-env-var';
const INPUT_SERVER_PASSWORD_ENV_VAR = 'server-password-env-var';
@@ -30848,12 +30860,16 @@ const INPUT_DEFAULT_GPG_PASSPHRASE = 'GPG_PASSPHRASE';
const MAVEN_GPG_PASSPHRASE_DEFAULT_ENV = 'MAVEN_GPG_PASSPHRASE';
// Id of the settings.xml profile used to set `gpg.passphraseEnvName`.
const GPG_PASSPHRASE_PROFILE_ID = 'setup-java-gpg';
const MAVEN_REPOSITORIES_PROFILE_ID = 'setup-java-repositories';
const MAVEN_CENTRAL_REPOSITORY_ID = 'central';
const MAVEN_CENTRAL_REPOSITORY_URL = 'https://repo.maven.apache.org/maven2';
const INPUT_CACHE = 'cache';
const INPUT_CACHE_JDK = 'cache-jdk';
const INPUT_CACHE_DEPENDENCY_PATH = 'cache-dependency-path';
const INPUT_CACHE_PATH = 'cache-path';
const INPUT_CACHE_READ_ONLY = 'cache-read-only';
const INPUT_JOB_STATUS = 'job-status';
const STATE_GPG_PRIVATE_KEY_FINGERPRINT = 'gpg-private-key-fingerprint';
const STATE_GPG_HOME = 'gpg-home';
const M2_DIR = '.m2';
const MVN_SETTINGS_FILE = 'settings.xml';
const MVN_TOOLCHAINS_FILE = 'toolchains.xml';
@@ -30899,6 +30915,7 @@ var JavaDistribution;
JavaDistribution["JetBrains"] = "jetbrains";
JavaDistribution["Kona"] = "kona";
JavaDistribution["OracleOpenJdk"] = "oracle-openjdk";
JavaDistribution["RedHat"] = "redhat";
})(JavaDistribution || (JavaDistribution = {}));
const JAVA_PACKAGE_CAPABILITIES = {
[JavaDistribution.Temurin]: ['jdk', 'jre', 'jdk+jmods'],
@@ -30930,7 +30947,8 @@ const JAVA_PACKAGE_CAPABILITIES = {
'jre+ft'
],
[JavaDistribution.Kona]: ['jdk'],
[JavaDistribution.OracleOpenJdk]: ['jdk']
[JavaDistribution.OracleOpenJdk]: ['jdk'],
[JavaDistribution.RedHat]: ['jdk', 'jre']
};
function validateJavaPackage(distributionName, packageType, version) {
if (!isJavaDistribution(distributionName)) {
@@ -30986,33 +31004,38 @@ function createUnsupportedPackageError(distributionName, packageType, supportedP
/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
/* harmony export */ G6: () => (/* binding */ isAlpineLinux),
/* harmony export */ U: () => (/* binding */ getJavaPlatformIdentity),
/* harmony export */ dV: () => (/* binding */ normalizeArchitecture),
/* harmony export */ sZ: () => (/* binding */ validateJavaPlatform)
/* harmony export */ });
/* unused harmony exports JAVA_PLATFORM_CAPABILITIES, normalizePlatform */
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(semver__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _package_types_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(7835);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(9896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(2088);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__nccwpck_require__.n(semver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _package_types_js__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(7835);
const X64_ARM64 = ['x64', 'aarch64'];
const STANDARD_LINUX = ['x64', 'x86', 'aarch64', 'ppc64le', 's390x'];
const JAVA_PLATFORM_CAPABILITIES = {
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Temurin]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Temurin]: {
platforms: {
linux: [...STANDARD_LINUX, { architecture: 'armv7', versionRange: '<18' }],
macos: X64_ARM64,
windows: ['x64', 'x86', 'aarch64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Zulu]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Zulu]: {
platforms: {
linux: ['x64', 'x86', 'armv7', 'aarch64'],
macos: X64_ARM64,
windows: ['x64', 'x86', 'aarch64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Liberica]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Liberica]: {
platforms: {
linux: ['x64', 'x86', 'armv7', 'aarch64', 'ppc64le'],
macos: X64_ARM64,
@@ -31020,31 +31043,31 @@ const JAVA_PLATFORM_CAPABILITIES = {
solaris: ['x64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.LibericaNik]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.LibericaNik]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: X64_ARM64
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.JdkFile]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.JdkFile]: {
unrestricted: true
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Microsoft]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Microsoft]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: X64_ARM64
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Semeru]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Semeru]: {
platforms: {
linux: ['x64', 'x86', 'ppc64le', 'ppc64', 's390x', 'aarch64'],
macos: X64_ARM64,
windows: ['x64', 'aarch64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Corretto]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Corretto]: {
platforms: {
linux: [
'x64',
@@ -31056,60 +31079,73 @@ const JAVA_PLATFORM_CAPABILITIES = {
windows: ['x64', { architecture: 'x86', versionRange: '<12' }]
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Oracle]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Oracle]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: ['x64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Dragonwell]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Dragonwell]: {
platforms: {
linux: X64_ARM64,
windows: ['x64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.SapMachine]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.SapMachine]: {
platforms: {
linux: ['x64', 'aarch64', 'ppc64le'],
macos: X64_ARM64,
windows: X64_ARM64
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.GraalVM]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.GraalVM]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: ['x64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.GraalVMCommunity]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.GraalVMCommunity]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: ['x64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.JetBrains]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.JetBrains]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: X64_ARM64
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.Kona]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.Kona]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: ['x64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_1__/* .JavaDistribution */ .zS.OracleOpenJdk]: {
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.OracleOpenJdk]: {
platforms: {
linux: X64_ARM64,
macos: X64_ARM64,
windows: ['x64']
}
},
[_package_types_js__WEBPACK_IMPORTED_MODULE_2__/* .JavaDistribution */ .zS.RedHat]: {
platforms: {
linux: [
'x64',
{ architecture: 'aarch64', versionRange: '<12' },
{ architecture: 'ppc64le', versionRange: '<12' }
],
windows: [
{ architecture: 'x64', versionRange: '<22' },
{ architecture: 'x86', versionRange: '<11' }
]
}
}
};
const ARCHITECTURE_ALIASES = {
@@ -31144,6 +31180,18 @@ function normalizeArchitecture(architecture) {
function normalizePlatform(platform) {
return PLATFORM_ALIASES[platform];
}
function isAlpineLinux(platform = process.platform, alpineReleaseExists) {
return (platform === 'linux' &&
(alpineReleaseExists ?? fs__WEBPACK_IMPORTED_MODULE_0___default().existsSync('/etc/alpine-release')));
}
function getJavaPlatformIdentity(platform = process.platform, alpineReleaseExists) {
if (platform === 'linux') {
return isAlpineLinux(platform, alpineReleaseExists)
? 'linux-musl'
: 'linux-glibc';
}
return normalizePlatform(platform) ?? platform;
}
function validateJavaPlatform(distributionName, platform, architecture, version) {
const normalizedArchitecture = normalizeArchitecture(architecture);
if (!isJavaDistribution(distributionName)) {
@@ -31179,8 +31227,8 @@ function isVersionCompatible(version, supportedRange) {
if (/^\d+(\.\d+){3,}$/.test(normalizedVersion)) {
normalizedVersion = normalizeExtendedVersionToSemver(normalizedVersion);
}
const requestedRange = semver__WEBPACK_IMPORTED_MODULE_0___default().validRange(normalizedVersion.replace(/-ea$/, ''));
const capabilityRange = semver__WEBPACK_IMPORTED_MODULE_0___default().validRange(supportedRange);
const requestedRange = semver__WEBPACK_IMPORTED_MODULE_1___default().validRange(normalizedVersion.replace(/-ea$/, ''));
const capabilityRange = semver__WEBPACK_IMPORTED_MODULE_1___default().validRange(supportedRange);
if (!requestedRange || !capabilityRange) {
return true;
}
@@ -31192,7 +31240,7 @@ function isVersionCompatible(version, supportedRange) {
}
return version;
}
return semver__WEBPACK_IMPORTED_MODULE_0___default().intersects(requestedRange, capabilityRange, {
return semver__WEBPACK_IMPORTED_MODULE_1___default().intersects(requestedRange, capabilityRange, {
includePrerelease: true
});
}
@@ -31233,16 +31281,21 @@ function validateToolchainIds(versions, versionFile, toolchainIds) {
/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
/* harmony export */ C4: () => (/* binding */ getJavaVersionFromReleaseFile),
/* harmony export */ G4: () => (/* binding */ getTempDir),
/* harmony export */ OS: () => (/* binding */ getVersionFromFileContent),
/* harmony export */ PE: () => (/* binding */ extractJdkFile),
/* harmony export */ SA: () => (/* binding */ validatePaginationUrl),
/* harmony export */ Tp: () => (/* binding */ MAX_PAGINATION_PAGES),
/* harmony export */ U_: () => (/* binding */ getGitHubHttpHeaders),
/* harmony export */ VX: () => (/* binding */ getArtifactFingerprint),
/* harmony export */ Vj: () => (/* binding */ cacheJdkDir),
/* harmony export */ Vt: () => (/* binding */ getBooleanInput),
/* harmony export */ ZY: () => (/* binding */ convertVersionToSemver),
/* harmony export */ aT: () => (/* binding */ isGhes),
/* harmony export */ ag: () => (/* binding */ getDownloadArchiveExtension),
/* harmony export */ lK: () => (/* binding */ getGitHubToken),
/* harmony export */ lN: () => (/* binding */ isJdkCacheEnabled),
/* harmony export */ n2: () => (/* binding */ renameWinArchive),
/* harmony export */ rC: () => (/* binding */ getNextPageUrlFromLinkHeader),
/* harmony export */ ri: () => (/* binding */ getLatestMajorVersion),
@@ -31260,7 +31313,14 @@ function validateToolchainIds(versions, versionFile, toolchainIds) {
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__nccwpck_require__.n(semver__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(3838);
/* harmony import */ var _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(9805);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_6__ = __nccwpck_require__(7242);
/* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_6__ = __nccwpck_require__(5260);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_7__ = __nccwpck_require__(8701);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_8__ = __nccwpck_require__(6982);
/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__nccwpck_require__.n(crypto__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_9__ = __nccwpck_require__(7242);
@@ -31286,6 +31346,11 @@ function getBooleanInput(inputName, defaultValue = false) {
}
throw new Error(`Invalid value '${inputValue}' for boolean input '${inputName}'. Expected 'true' or 'false'.`);
}
function isJdkCacheEnabled(cache) {
return _actions_core__WEBPACK_IMPORTED_MODULE_4__/* .getInput */ .V4(_constants_js__WEBPACK_IMPORTED_MODULE_9__/* .INPUT_CACHE_JDK */ .GL).trim()
? getBooleanInput(_constants_js__WEBPACK_IMPORTED_MODULE_9__/* .INPUT_CACHE_JDK */ .GL)
: Boolean(cache.trim());
}
function getVersionFromToolcachePath(toolPath) {
if (toolPath) {
return path.basename(path.dirname(toolPath));
@@ -31296,21 +31361,167 @@ async function extractJdkFile(toolPath, extension) {
if (!extension) {
extension = toolPath.endsWith('.tar.gz')
? 'tar.gz'
: path__WEBPACK_IMPORTED_MODULE_1___default().extname(toolPath);
: toolPath.endsWith('.tar.xz')
? 'tar.xz'
: path__WEBPACK_IMPORTED_MODULE_1___default().extname(toolPath);
if (extension.startsWith('.')) {
extension = extension.substring(1);
}
}
switch (extension) {
case 'tar.gz':
return await extractTarGz(toolPath);
case 'tar.xz':
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .extractTar */ .nN(toolPath, undefined, 'xJ');
case 'tar':
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .extractTar */ .nN(toolPath);
case 'zip':
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .extractZip */ .JE(toolPath);
return await extractZipArchive(toolPath);
default:
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .extract7z */ .$E(toolPath);
}
}
async function createExtractFolder() {
const dest = path__WEBPACK_IMPORTED_MODULE_1___default().join(getTempDir(), (0,crypto__WEBPACK_IMPORTED_MODULE_8__.randomUUID)());
await _actions_io__WEBPACK_IMPORTED_MODULE_7__/* .mkdirP */ .U$(dest);
return dest;
}
/**
* Decompressing a JDK tarball with the default single-threaded gzip is one of the
* slowest parts of the install, so hand the decompression to `pigz` when the runner
* provides it. Any failure falls back to the stock extraction.
*/
async function extractTarGz(toolPath) {
const pigzPath = await _actions_io__WEBPACK_IMPORTED_MODULE_7__/* .which */ .K7('pigz');
// tar splits --use-compress-program on whitespace, so a path containing a
// space would be word-split into a bogus command.
if (pigzPath && !/\s/.test(pigzPath)) {
const dest = await createExtractFolder();
try {
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .extractTar */ .nN(toolPath, dest, [
'--use-compress-program',
`${pigzPath} -d`,
'-x'
]);
}
catch (error) {
await _actions_io__WEBPACK_IMPORTED_MODULE_7__/* .rmRF */ .Yz(dest);
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Failed to extract '${toolPath}' with pigz, falling back to gzip: ${getErrorMessage(error)}`);
}
}
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .extractTar */ .nN(toolPath);
}
/**
* `tc.extractZip` shells out to PowerShell's `Expand-Archive` on Windows, which is
* several times slower than the bundled bsdtar. Prefer `tar.exe` and fall back to
* the stock extraction when it is unavailable or fails.
*/
async function extractZipArchive(toolPath) {
if (process.platform === 'win32') {
const systemTar = path__WEBPACK_IMPORTED_MODULE_1___default().join(process.env['SystemRoot'] || 'C:\\Windows', 'System32', 'tar.exe');
if (fs__WEBPACK_IMPORTED_MODULE_2__.existsSync(systemTar)) {
const dest = await createExtractFolder();
try {
await _actions_exec__WEBPACK_IMPORTED_MODULE_6__/* .exec */ .m(`"${systemTar}"`, ['-xf', toolPath, '-C', dest], {
silent: true
});
return dest;
}
catch (error) {
await _actions_io__WEBPACK_IMPORTED_MODULE_7__/* .rmRF */ .Yz(dest);
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Failed to extract '${toolPath}' with tar.exe, falling back to Expand-Archive: ${getErrorMessage(error)}`);
}
}
}
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .extractZip */ .JE(toolPath);
}
/**
* Equivalent of `tc.cacheDir`, but moves the extracted JDK into the tool-cache
* instead of copying it. `tc.cacheDir` recursively copies the whole tree, which
* means a several hundred megabyte JDK is written to disk twice. The extraction
* directory and the tool-cache normally live on the same filesystem, so a rename
* is effectively free. Anything unexpected (a different filesystem, or a file
* handle held open by anti-virus software on Windows) falls back to the copy.
*/
async function cacheJdkDir(sourceDir, toolName, version, architecture) {
const destPath = getToolcacheDestination(toolName, version, architecture);
if (destPath) {
let moved = false;
try {
// lstat, not stat: renaming a symlinked source would put the link itself
// in the tool-cache, leaving a dangling JAVA_HOME once RUNNER_TEMP is
// cleaned. tc.cacheDir dereferences it, so let it handle that case.
if (fs__WEBPACK_IMPORTED_MODULE_2__.lstatSync(sourceDir).isDirectory()) {
await _actions_io__WEBPACK_IMPORTED_MODULE_7__/* .rmRF */ .Yz(destPath);
await _actions_io__WEBPACK_IMPORTED_MODULE_7__/* .rmRF */ .Yz(`${destPath}.complete`);
await _actions_io__WEBPACK_IMPORTED_MODULE_7__/* .mkdirP */ .U$(path__WEBPACK_IMPORTED_MODULE_1___default().dirname(destPath));
// Renaming is atomic, so a failure here leaves sourceDir untouched and
// the copy-based fallback below can still run.
fs__WEBPACK_IMPORTED_MODULE_2__.renameSync(sourceDir, destPath);
moved = true;
}
}
catch (error) {
_actions_core__WEBPACK_IMPORTED_MODULE_4__/* .debug */ .Yz(`Failed to move '${sourceDir}' into the tool-cache, falling back to a copy: ${getErrorMessage(error)}`);
}
if (moved) {
fs__WEBPACK_IMPORTED_MODULE_2__.writeFileSync(`${destPath}.complete`, '');
return destPath;
}
}
return await _actions_tool_cache__WEBPACK_IMPORTED_MODULE_5__/* .cacheDir */ .e8(sourceDir, toolName, version, architecture);
}
function getJavaVersionFromReleaseFile(javaHome) {
const releasePaths = [
path__WEBPACK_IMPORTED_MODULE_1___default().join(javaHome, 'release'),
path__WEBPACK_IMPORTED_MODULE_1___default().join(javaHome, 'Contents', 'Home', 'release')
];
const releasePath = releasePaths.find(candidate => fs__WEBPACK_IMPORTED_MODULE_2__.existsSync(candidate));
if (!releasePath) {
throw new Error(`Unable to determine the installed Java version: no release file found under '${javaHome}'.`);
}
const properties = new Map();
for (const line of fs__WEBPACK_IMPORTED_MODULE_2__.readFileSync(releasePath, 'utf8').split(/\r?\n/)) {
const match = line.match(/^([A-Z0-9_]+)="(.*)"$/);
if (match) {
properties.set(match[1], match[2]);
}
}
const runtimeVersion = properties.get('JAVA_RUNTIME_VERSION');
const runtimeMatch = runtimeVersion?.match(/^(\d+(?:\.\d+)*(?:\+\d+(?:\.\d+)*)?)/);
if (runtimeMatch) {
return normalizeJavaReleaseVersion(runtimeMatch[1]);
}
const javaVersion = properties.get('JAVA_VERSION');
if (javaVersion && /^\d+(?:\.\d+)*$/.test(javaVersion)) {
return normalizeJavaReleaseVersion(javaVersion);
}
throw new Error(`Unable to determine the installed Java version from '${releasePath}'.`);
}
function normalizeJavaReleaseVersion(version) {
const [numericVersion, buildVersion] = version.split('+', 2);
const components = numericVersion.split('.');
while (components.length < 3) {
components.push('0');
}
const mainVersion = components.slice(0, 3).join('.');
const build = [
...components.slice(3),
...(buildVersion ? [buildVersion] : [])
];
return build.length > 0 ? `${mainVersion}+${build.join('.')}` : mainVersion;
}
function getToolcacheDestination(toolName, version, architecture) {
const toolcacheRoot = process.env['RUNNER_TOOL_CACHE'];
if (!toolcacheRoot) {
return null;
}
// Mirrors the destination layout used by `tc.cacheDir`.
return path__WEBPACK_IMPORTED_MODULE_1___default().join(toolcacheRoot, toolName, semver__WEBPACK_IMPORTED_MODULE_3__.clean(version) || version, architecture || os__WEBPACK_IMPORTED_MODULE_0___default().arch());
}
function getErrorMessage(error) {
return error instanceof Error ? error.message : String(error);
}
function getDownloadArchiveExtension() {
return process.platform === 'win32' ? 'zip' : 'tar.gz';
}
@@ -31407,7 +31618,7 @@ function getVersionFromFileContent(content, distributionName, versionFile) {
}
// Apply DISTRIBUTIONS_ONLY_MAJOR_VERSION logic whenever the effective distribution
// (either explicitly provided or extracted from the version file) is in the list.
if (_constants_js__WEBPACK_IMPORTED_MODULE_6__/* .DISTRIBUTIONS_ONLY_MAJOR_VERSION */ ._V.includes(extractedDistribution || distributionName)) {
if (_constants_js__WEBPACK_IMPORTED_MODULE_9__/* .DISTRIBUTIONS_ONLY_MAJOR_VERSION */ ._V.includes(extractedDistribution || distributionName)) {
const coerceVersion = semver__WEBPACK_IMPORTED_MODULE_3__.coerce(version) ?? version;
version = semver__WEBPACK_IMPORTED_MODULE_3__.major(coerceVersion).toString();
}
@@ -31490,8 +31701,43 @@ function convertVersionToSemver(version) {
}
return mainVersion;
}
/**
* Builds a validator for the bytes currently served by a URL from the response
* headers of a HEAD request. A vendor's `/latest/` URL never changes, so this
* is what lets a republished artifact be told apart from the previous one when
* no checksum is published alongside it.
*
* Returns `undefined` when the response carries no usable validator, in which
* case the caller must not treat the URL as a stable identity.
*/
function getArtifactFingerprint(headers) {
const readHeader = (name) => {
const value = headers?.[name];
const resolved = Array.isArray(value) ? value[0] : value;
return typeof resolved === 'string' && resolved.trim()
? resolved.trim()
: undefined;
};
// A strong or weak ETag already identifies a specific representation.
const etag = readHeader('etag');
if (etag) {
return `etag:${etag}`;
}
// Otherwise combine the two validators a static file server reliably sends.
// Neither alone is sufficient: `last-modified` has one-second granularity and
// `content-length` is unchanged by a same-size rebuild.
const lastModified = readHeader('last-modified');
const contentLength = readHeader('content-length');
if (lastModified && contentLength) {
return `mtime:${lastModified};length:${contentLength}`;
}
return undefined;
}
function getGitHubToken() {
return _actions_core__WEBPACK_IMPORTED_MODULE_4__/* .getInput */ .V4('token') || process.env.GITHUB_TOKEN;
}
function getGitHubHttpHeaders() {
const resolvedToken = _actions_core__WEBPACK_IMPORTED_MODULE_4__/* .getInput */ .V4('token') || process.env.GITHUB_TOKEN;
const resolvedToken = getGitHubToken();
const auth = !resolvedToken ? undefined : `token ${resolvedToken}`;
const headers = {
accept: 'application/vnd.github.VERSION.raw'
@@ -31890,6 +32136,7 @@ __nccwpck_require__.d(__webpack_exports__, {
dN: () => (/* binding */ exportVariable),
V4: () => (/* binding */ getInput),
q3: () => (/* binding */ getMultilineInput),
Gu: () => (/* binding */ getState),
pq: () => (/* binding */ info),
_o: () => (/* binding */ isDebug),
LZ: () => (/* binding */ saveState),
@@ -31900,7 +32147,7 @@ __nccwpck_require__.d(__webpack_exports__, {
$e: () => (/* binding */ warning)
});
// UNUSED EXPORTS: ExitCode, getBooleanInput, getIDToken, getState, group, markdownSummary, notice, platform, setCommandEcho, summary, toPlatformPath, toPosixPath, toWin32Path
// UNUSED EXPORTS: ExitCode, getBooleanInput, getIDToken, group, markdownSummary, notice, platform, setCommandEcho, summary, toPlatformPath, toPosixPath, toWin32Path
// EXTERNAL MODULE: external "os"
var external_os_ = __nccwpck_require__(857);
@@ -36081,6 +36328,10 @@ async function getJavaDistribution(distributionName, installerOptions, jdkFile)
const { OpenJdkDistribution } = await Promise.all(/* import() */[__nccwpck_require__.e(242), __nccwpck_require__.e(735)]).then(__nccwpck_require__.bind(__nccwpck_require__, 3735));
return new OpenJdkDistribution(normalizedInstallerOptions);
}
case package_types/* JavaDistribution */.zS.RedHat: {
const { RedHatDistribution } = await Promise.all(/* import() */[__nccwpck_require__.e(242), __nccwpck_require__.e(228)]).then(__nccwpck_require__.bind(__nccwpck_require__, 8228));
return new RedHatDistribution(normalizedInstallerOptions);
}
default:
return null;
}
@@ -36119,6 +36370,7 @@ async function run() {
const packageType = setup_java_core/* getInput */.V4(constants/* INPUT_JAVA_PACKAGE */.p1);
const jdkFile = getJdkFileInput();
const cache = setup_java_core/* getInput */.V4(constants/* INPUT_CACHE */.gk);
const cacheJdk = (0,util/* isJdkCacheEnabled */.lN)(cache);
const cacheDependencyPath = setup_java_core/* getInput */.V4(constants/* INPUT_CACHE_DEPENDENCY_PATH */.At);
const cachePath = setup_java_core/* getMultilineInput */.q3(constants/* INPUT_CACHE_PATH */.uW);
const checkLatest = (0,util/* getBooleanInput */.Vt)(constants/* INPUT_CHECK_LATEST */.YM, false);
@@ -36157,6 +36409,7 @@ async function run() {
packageType,
checkLatest,
forceDownload,
cacheJdk,
setDefault,
verifySignature,
verifySignaturePublicKey,
@@ -36164,8 +36417,9 @@ async function run() {
jdkFile,
toolchainIds
};
await validateCacheInput(cache);
cacheRestore = cache
? startCacheRestore(cache, cacheDependencyPath, cachePath)
? settle(startCacheRestore(cache, cacheDependencyPath, cachePath))
: undefined;
toolchainConfigurations.push(await installVersion(versionInfo.version, installerInputsOptions));
}
@@ -36179,6 +36433,7 @@ async function run() {
packageType,
checkLatest,
forceDownload,
cacheJdk,
setDefault,
verifySignature,
verifySignaturePublicKey,
@@ -36186,8 +36441,9 @@ async function run() {
jdkFile,
toolchainIds
};
await validateCacheInput(cache);
cacheRestore = cache
? startCacheRestore(cache, cacheDependencyPath, cachePath)
? settle(startCacheRestore(cache, cacheDependencyPath, cachePath))
: undefined;
for (const [index, version] of versions.entries()) {
toolchainConfigurations.push(await installVersion(version, installerInputsOptions, index));
@@ -36202,19 +36458,25 @@ async function run() {
actionError = error;
}
if (cacheRestore) {
try {
await cacheRestore;
}
catch (error) {
if (!actionError) {
actionError = error;
}
const cacheResult = await cacheRestore;
if (cacheResult.status === 'rejected' && !actionError) {
actionError = cacheResult.reason;
}
}
if (actionError) {
setup_java_core/* setFailed */.C1(actionError.message);
}
}
async function validateCacheInput(cache) {
if (!cache) {
return;
}
const { validatePackageManager } = await Promise.all(/* import() */[__nccwpck_require__.e(824), __nccwpck_require__.e(971), __nccwpck_require__.e(377)]).then(__nccwpck_require__.bind(__nccwpck_require__, 7377));
validatePackageManager(cache);
}
function settle(promise) {
return promise.then(value => ({ status: 'fulfilled', value }), reason => ({ status: 'rejected', reason }));
}
if (process.argv[1] === (0,external_url_.fileURLToPath)(import.meta.url)) {
run();
}
@@ -36231,12 +36493,13 @@ function getJdkFileInput() {
return jdkFile || deprecatedJdkFile;
}
async function installVersion(version, options, toolchainId = 0) {
const { distributionName, jdkFile, architecture, packageType, checkLatest, forceDownload, setDefault, verifySignature, verifySignaturePublicKey, toolchainIds } = options;
const { distributionName, jdkFile, architecture, packageType, checkLatest, forceDownload, cacheJdk, setDefault, verifySignature, verifySignaturePublicKey, toolchainIds } = options;
const installerOptions = {
architecture,
packageType,
checkLatest,
forceDownload,
cacheJdk,
setDefault,
verifySignature,
verifySignaturePublicKey,
+299 -8
View File
@@ -5,8 +5,10 @@
- [Liberica](#Liberica)
- [Liberica Native Image Kit](#Liberica-Native-Image-Kit)
- [Microsoft](#Microsoft)
- [IBM Semeru](#IBM-Semeru)
- [Amazon Corretto](#Amazon-Corretto)
- [Oracle](#Oracle)
- [Oracle OpenJDK](#Oracle-OpenJDK)
- [Alibaba Dragonwell](#Alibaba-Dragonwell)
- [SapMachine](#SapMachine)
- [GraalVM](#GraalVM)
@@ -17,13 +19,18 @@
- [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)
- [Caching JDK installations](#caching-jdk-installations)
- [Platform and architecture compatibility](#platform-and-architecture-compatibility)
- [Installing custom Java architecture](#Installing-custom-Java-architecture)
- [Installing JDK without setting as default](#Installing-JDK-without-setting-as-default)
- [Installing custom Java distribution from local file](#Installing-Java-from-local-file)
- [Testing against different Java distributions](#Testing-against-different-Java-distributions)
- [Testing against different platforms](#Testing-against-different-platforms)
- [Publishing using Apache Maven](#Publishing-using-Apache-Maven)
- [Publishing to multiple Maven servers](#publishing-to-multiple-maven-servers)
- [Apache Maven with a settings path](#apache-maven-with-a-settings-path)
- [Maven transfer progress (download logs)](#Maven-transfer-progress-download-logs)
- [Java problem matcher (compiler annotations)](#java-problem-matcher-compiler-annotations)
- [Publishing using Gradle](#Publishing-using-Gradle)
- [Hosted Tool Cache](#Hosted-Tool-Cache)
- [Modifying Maven Toolchains](#Modifying-Maven-Toolchains)
@@ -32,8 +39,17 @@
See [action.yml](../action.yml) for more details on task inputs.
> [!NOTE]
> The examples on this page reference `actions/setup-java@v6`, which is still in
> development on the `main` branch and is not yet published as a release tag. To
> try the V6 features documented here (`cache-jdk`, `force-download`,
> `problem-matcher`, `cache-path`, `cache-read-only`, `java-version: latest`,
> `oracle-openjdk`, and the `*-env-var` input names), reference
> `actions/setup-java@main`. For production workflows use the latest stable
> release, `actions/setup-java@v5`, as shown in the [README](../README.md).
## Selecting a Java distribution
Inputs `java-version` and `distribution` are mandatory and needs to be provided. See [Supported distributions](../README.md#Supported-distributions) for a list of available options.
`java-version` and `distribution` select what gets installed. `java-version` may be replaced by `java-version-file`, and `distribution` is optional only when `java-version-file` points to a `.sdkmanrc` or `.tool-versions` file that carries a recognized vendor identifier. In every other case both inputs must be provided. See [Supported distributions](../README.md#Supported-distributions) for a list of available options.
### Eclipse Temurin
@@ -61,6 +77,19 @@ steps:
- run: java --version
```
### Red Hat Build of OpenJDK
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: 'redhat'
java-version: '21'
java-package: jdk # optional (jdk or jre) - defaults to jdk
- run: java --version
```
### Liberica
```yaml
@@ -116,6 +145,20 @@ with:
If the runner is not able to access github.com, any Java versions requested during a workflow run must come from the runner's tool cache. See "[Setting up the tool cache on self-hosted runners without internet access](https://docs.github.com/en/enterprise-server@3.2/admin/github-actions/managing-access-to-actions-from-githubcom/setting-up-the-tool-cache-on-self-hosted-runners-without-internet-access)" for more information.
### IBM Semeru
**NOTE:** IBM Semeru Runtime Open Edition provides OpenJ9-based builds. Stable releases only; `jdk` and `jre` packages are available.
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: 'semeru'
java-version: '21'
java-package: jdk # optional (jdk or jre) - defaults to jdk
- run: java --version
```
### Amazon Corretto
**NOTE:** Amazon Corretto only supports the major version specification.
@@ -293,12 +336,13 @@ The package types have these meanings:
| `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. |
| `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. |
| `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. Any other `java-package` value is rejected. |
| `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. |
| `redhat` | `jdk`, `jre` | Stable builds only. Version availability follows the Foojay Disco catalog for Red Hat Build of OpenJDK and can lag Red Hat's downloads page. |
| `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. |
@@ -468,6 +512,133 @@ jobs:
> which provides purpose-built caching (see the
> [setup-gradle documentation](https://github.com/gradle/actions/blob/main/docs/setup-gradle.md)).
## Caching JDK installations
`cache-jdk` controls caching for downloaded JDK installations. The JDK cache is
stored and restored as its own cache entry, separate from the dependency and
build-tool wrapper caches selected by `cache`. Whether it is *enabled*, however,
is coupled to `cache`: setting `cache` turns JDK caching on as well, unless
`cache-jdk` is set explicitly.
| `cache` | `cache-jdk` | Dependency and wrapper caches | JDK cache |
| --- | --- | --- | --- |
| Omitted | Omitted | Disabled | Disabled |
| Omitted | `true` | Disabled | Enabled |
| Omitted | `false` | Disabled | Disabled |
| Set | Omitted | Enabled | Enabled |
| Set | `true` | Enabled | Enabled |
| Set | `false` | Enabled | Disabled |
JDK entries are specific to the runner operating system and normalized
architecture. They are additionally separated by distribution, package type,
exact resolved Java version, release identity, and signature-verification
identity. The release identity is the authoritative checksum when available and
otherwise the download URL without its query string. These dimensions prevent
incompatible JDKs from sharing an entry. They also mean that a matrix or workflow
using multiple JDK versions, distributions, package types, architectures, or
operating systems stores a separate JDK entry for each identity and consumes
cache storage for each one.
For `distribution: jdkfile`, the release source is a SHA-256 hash of the local
`jdk-file` contents, streamed so the archive is not held in memory. Changing the
archive therefore creates a different JDK cache entry, even when its path and
requested version are unchanged. The archive is only read when the runner tool
cache holds no installation satisfying the requested version: a matching
tool-cache installation short-circuits setup, so a changed `jdk-file` is not
re-extracted for a version that is already installed. Use
`force-download: true` when the archive contents change but the version does not.
The verification identity separates unverified downloads from packages verified
with the distribution's bundled signing key and from packages verified with each
custom key. Custom public keys are represented by a SHA-256 fingerprint of
normalized key material; the key itself is not placed in the cache key, the logs,
or action state. A verified exact-key hit reuses content that was
signature-verified when it was downloaded by the run that saved the entry,
instead of downloading and verifying it again.
> [!IMPORTANT]
> The JDK cache **key** is what isolates verification modes and release
> identity: a JDK cache entry created by an unverified download can never be
> restored for a request that sets `verify-signature: true`, and vice versa.
> `cache-jdk` does not change how the runner tool cache is used. setup-java
> first looks for an installation in the runner tool cache — a preinstalled
> JDK, or one installed by an earlier step of the same job — and uses it as-is. Such an installation is not downloaded again, and its checksum
> and signature are not reverified, even when `verify-signature: true` is set,
> because its verification history is not recorded in the tool cache. Use
> `force-download: true` for a request that must download and verify the archive
> itself.
`check-latest: true` and `java-version: latest` resolve remote metadata before
looking up the exact resolved JDK entry. `force-download: true` bypasses both the
runner tool cache and JDK cache restore, but an enabled JDK cache still records
the downloaded installation for a post-job save. `cache-read-only: true` allows
restores but suppresses post-job saves for JDK, dependency, and wrapper caches.
If the cache service fails to restore an entry, or the restored entry lacks the
expected completed tool-cache path, setup continues by downloading the JDK.
Post-job saves are best-effort and do not fail the job: cache keys are immutable,
so an existing key or a concurrent job winning the save race is left unchanged,
and a failure to save one JDK entry is reported as a warning without preventing
the remaining entries from being saved.
A key is only ever populated with the installation it was computed for. Because
tool-cache paths are shared per version and architecture, a later step — for
example one using `force-download: true` — can replace the installation an
earlier step registered. setup-java detects that replacement in the post-job
step and skips the save with a warning, so a key is never saved with content
other than the installation it identifies. This guarantee holds without
rehashing hundreds of megabytes of JDK content on every job.
### Caching release resolution
Only Temurin is preinstalled in the runner tool cache, so for every other
distribution setup-java has to ask the distribution's metadata API which release
satisfies `java-version` before it can look up a JDK cache entry. That makes the
vendor API a dependency of every job, even one whose JDK is already cached.
When JDK caching is enabled, setup-java also stores the resolved release itself
in a small companion cache entry, keyed on the runner operating system,
architecture, distribution, package type, requested version, and stability. A job
that finds a current entry installs the JDK without contacting the distribution's
metadata API at all.
Entries carry the seven-day window they were resolved in. An entry from an
earlier window is not used directly: setup-java still queries the metadata API,
so a floating request such as `java-version: 21` keeps picking up new releases.
The older entry is used only when that query fails, which keeps a job working
through a vendor outage or rate limit. Because the entry also holds the download
URL and checksum, this fallback works even when the JDK itself is not cached and
still has to be downloaded. When the fallback is used, setup-java reports it with
a warning.
Seven days is deliberate. GitHub removes cache entries that have not been
accessed for seven days, so a longer window would mean the previous entry is
already evicted by the time the window rolls over, leaving no fallback at the
moment one is most likely to be needed. It also comfortably covers JDK release
cadence, which is monthly at its fastest and usually quarterly, and it means a
repository whose workflows run infrequently still benefits. Use
`check-latest: true` for a workflow that must resolve the newest release on every
run.
Restored entries are validated before use: the download URL and any signature URL
must be well-formed HTTPS URLs and the checksum must use a supported algorithm.
An entry that fails validation is ignored and the metadata API is queried
instead. `check-latest: true`, `java-version: latest`, and `force-download: true`
always query the metadata API and never read or write these entries.
Releases whose download URL is not content-addressed are never stored. Oracle JDK
and Oracle GraalVM build a `/latest/` URL when `java-version` names only a major
version, and the bytes behind that URL change whenever a new build is published,
so its URL and checksum are only consistent with each other at the moment they
are resolved. Requesting a more specific version, such as `java-version: 21.0.2`,
resolves an archived URL that is stored normally.
JDK caching trades cache storage and cold-run save work for faster warm setup.
A warm run restores the installed JDK instead of downloading, verifying, and
extracting it, while the first run pays to upload it and every cached identity
consumes repository cache storage. How much time this saves depends on the
runner, distribution, JDK size, network, and cache eviction pressure.
## Platform and architecture compatibility
The `architecture` input is normalized before setup-java checks the tool cache
@@ -487,6 +658,7 @@ absent from a vendor catalog.
| `corretto` | `x64`, `x86`, `armv7`, `aarch64` | `x64`, `aarch64` | `x64`, `x86` | `x86` is limited to Java 11 or earlier; Linux `armv7` is available for Java 11. |
| `oracle` | `x64`, `aarch64` | `x64`, `aarch64` | `x64` | |
| `oracle-openjdk` | `x64`, `aarch64` | `x64`, `aarch64` | `x64` | |
| `redhat` | `x64`, `aarch64`, `ppc64le` | — | `x64`, `x86` | Linux requires glibc; Alpine is unsupported. Linux `aarch64` and `ppc64le` are limited to Java 11 or earlier. Windows `x64` is limited to Java 21 or earlier and `x86` to Java 10 or earlier. |
| `dragonwell` | `x64`, `aarch64` | — | `x64` | |
| `sapmachine` | `x64`, `aarch64`, `ppc64le` | `x64`, `aarch64` | `x64`, `aarch64` | |
| `graalvm`, `graalvm-community` | `x64`, `aarch64` | `x64`, `aarch64` | `x64` | |
@@ -590,7 +762,7 @@ steps:
```yaml
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
strategy:
matrix:
distribution: [ 'zulu', 'temurin' ]
@@ -606,7 +778,7 @@ jobs:
- run: java --version
```
#### Testing against different platforms
## Testing against different platforms
```yaml
jobs:
build:
@@ -707,6 +879,125 @@ The two `settings.xml` files created from the above example look like the follow
If you don't want to overwrite the `settings.xml` file, you can set `overwrite-settings: false`
### Publishing to multiple Maven servers
Use `mvn-server-credentials` to add more than one credential entry to the generated `settings.xml`. Each line has the format `server-id:USERNAME_ENV:PASSWORD_ENV`. The username and password fields are environment variable names, not credential values.
When this input is set, it replaces the single server configured by `server-id`, `server-username-env-var`, and `server-password-env-var`.
```yaml
steps:
- uses: actions/checkout@v7
- name: Set up release and snapshot repositories
uses: actions/setup-java@v6
with:
distribution: 'temurin'
java-version: '21'
mvn-server-credentials: |
releases:RELEASES_USERNAME:RELEASES_PASSWORD
snapshots:SNAPSHOTS_USERNAME:SNAPSHOTS_PASSWORD
- name: Publish with Maven
run: mvn deploy
env:
RELEASES_USERNAME: ${{ secrets.RELEASES_USERNAME }}
RELEASES_PASSWORD: ${{ secrets.RELEASES_PASSWORD }}
SNAPSHOTS_USERNAME: ${{ secrets.SNAPSHOTS_USERNAME }}
SNAPSHOTS_PASSWORD: ${{ secrets.SNAPSHOTS_PASSWORD }}
```
This configuration produces the following server entries:
```xml
<servers>
<server>
<id>releases</id>
<username>${env.RELEASES_USERNAME}</username>
<password>${env.RELEASES_PASSWORD}</password>
</server>
<server>
<id>snapshots</id>
<username>${env.SNAPSHOTS_USERNAME}</username>
<password>${env.SNAPSHOTS_PASSWORD}</password>
</server>
</servers>
```
### Resolving Maven dependencies from custom repositories
Use `mvn-repositories` when Maven must download dependencies from repositories
outside Maven Central. Each line has the format
`repository-id:repository-url:snapshots-enabled`. The parser uses the first and
last colons as separators, so repository URLs can contain a scheme or port.
The repository ID can match a `mvn-server-credentials` server ID to authenticate
requests to a private repository:
```yaml
steps:
- uses: actions/checkout@v7
- name: Set up Java and private Maven repositories
uses: actions/setup-java@v6
with:
distribution: 'temurin'
java-version: '21'
mvn-server-credentials: |
private:PRIVATE_REPOSITORY_USERNAME:PRIVATE_REPOSITORY_TOKEN
mvn-repositories: |
private:https://maven.example.com:8443/releases:false
snapshots:https://maven.example.com:8443/snapshots:true
mvn-repositories-include-central: true
mvn-repositories-prioritize-central: true
- run: mvn --batch-mode verify
env:
PRIVATE_REPOSITORY_USERNAME: ${{ secrets.PRIVATE_REPOSITORY_USERNAME }}
PRIVATE_REPOSITORY_TOKEN: ${{ secrets.PRIVATE_REPOSITORY_TOKEN }}
```
This configuration adds the following active profile to `settings.xml`:
```xml
<profiles>
<profile>
<id>setup-java-repositories</id>
<repositories>
<repository>
<id>central</id>
<url>https://repo.maven.apache.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>private</id>
<url>https://maven.example.com:8443/releases</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>snapshots</id>
<url>https://maven.example.com:8443/snapshots</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>setup-java-repositories</activeProfile>
</activeProfiles>
```
Maven Central is included first by default. Set
`mvn-repositories-prioritize-central: false` to place custom repositories
first, or set `mvn-repositories-include-central: false` to disable Central. The
generated profile overrides the Central repository inherited from Maven's Super
POM with releases and snapshots disabled. When automatic Central inclusion is
off, the ID `central` may instead be declared explicitly in `mvn-repositories`
to replace it with a user-specified repository; otherwise that ID is reserved
to prevent duplicate entries.
### GPG
The example above uses the [Maven GPG Plugin](https://maven.apache.org/plugins/maven-gpg-plugin/)'s Bouncy Castle signer (`-Dgpg.signer=bc`, available since `maven-gpg-plugin` 3.2.0). It is a pure-Java signer that reads the key directly from the `MAVEN_GPG_KEY` environment variable, so it does **not** require the `gpg` executable, importing the key into a GPG keychain, or the `--pinentry-mode loopback` workaround in your `pom.xml`. The key must be an ASCII-armored secret key (transferable secret key format).
@@ -717,7 +1008,7 @@ See the help docs on [Publishing a Package](https://help.github.com/en/github/ma
#### Legacy / alternative: let setup-java import the key
If you prefer signing with the `gpg` executable (for example because you are using `maven-gpg-plugin` older than 3.2.0), you can let setup-java import the key instead by providing the `gpg-private-key` and `gpg-passphrase-env-var` inputs. The private key is written to a file in the runner's temp directory, imported into the GPG keychain, and the file is promptly removed before proceeding with the rest of the setup process. A cleanup step removes the imported private key from the GPG keychain after the job completes regardless of the job status. This ensures that the private key is no longer accessible on self-hosted runners and cannot "leak" between jobs (hosted runners are always clean instances).
If you prefer signing with the `gpg` executable (for example because you are using `maven-gpg-plugin` older than 3.2.0), you can let setup-java import the key instead by providing the `gpg-private-key` and `gpg-passphrase-env-var` inputs. setup-java creates a uniquely named, permission-restricted GPG home in the runner's temp directory, imports the key only into that isolated keyring, and exports `GNUPGHOME` for subsequent Maven and GPG commands. The temporary key file is permission-restricted and removed whether the import succeeds or fails. A cleanup step removes the complete action-owned GPG home after the job regardless of job status, without modifying the runner user's default keyring. Each setup-java invocation owns a separate keyring, including on persistent self-hosted runners.
setup-java imports the key independently of the plugin version, but the generated passphrase profile described below uses `gpg.passphraseEnvName`, which requires `maven-gpg-plugin` 3.2.0 or newer. Since `gpg-passphrase-env-var` defaults to `GPG_PASSPHRASE`, setup-java writes that profile unless you override the input to `MAVEN_GPG_PASSPHRASE`.
@@ -945,7 +1236,7 @@ The result is a Toolchain with entries for JDKs 8, 11 and 15. You can even combi
architecture: x64
```
This will generate a Toolchains entry with the following values: `version: 1.6`, `vendor: jdkfile`, `id: Oracle_1.6`.
This will generate a Toolchains entry with the following values: `version: 1.6`, `vendor: jdkfile`, `id: jdkfile_1.6`.
### Modifying The Toolchain Vendor For JDKs
Each JDK provider will receive a default `vendor` using the `distribution` input value but this can be overridden with the `mvn-toolchain-vendor` parameter as follows.
@@ -979,7 +1270,7 @@ steps:
```
### Modifying The Toolchain ID For JDKs
Each JDK provider will receive a default `id` based on the combination of `distribution` and `java-version` in the format of `distribution_java-version` (e.g. `temurin_11`) but this can be overridden with the `mvn-toolchain-id` parameter as follows.
Each JDK provider will receive a default `id` based on the combination of the toolchain vendor and `java-version` in the format of `vendor_java-version` (e.g. `temurin_11`). The vendor defaults to the `distribution` input, so overriding `mvn-toolchain-vendor` also changes the generated default `id`. Set `mvn-toolchain-id` to override the `id` directly.
```yaml
steps:
@@ -1144,7 +1435,7 @@ On **GitHub Enterprise Server**, traffic from your runners frequently passes thr
### Security warning: do not disable certificate verification
Do **not** work around this error by disabling TLS verification (for example, by setting `NODE_TLS_REJECT_UNAUTHORIZED=0`). `setup-java` does not verify a pinned checksum or signature of the downloaded archive, so **TLS is effectively the only integrity guarantee** on the JDK download. Disabling verification would expose your workflow to a man-in-the-middle attacker who could serve a tampered JDK — which then becomes the `java` used by the rest of your pipeline, with access to your secrets and credentials. Always extend trust to your CA instead of turning verification off.
Do **not** work around this error by disabling TLS verification (for example, by setting `NODE_TLS_REJECT_UNAUTHORIZED=0`). Disabling verification would expose your workflow to a man-in-the-middle attacker who could serve a tampered JDK — which then becomes the `java` used by the rest of your pipeline, with access to your secrets and credentials. It also weakens the version metadata requests, which are not checksum-verified at all: a tampered manifest can redirect setup-java to an attacker-controlled download URL. `setup-java` does verify authoritative checksums for [supported distributions](../README.md#download-integrity-and-signatures), and can verify package signatures with `verify-signature: true`, but those checks are not a substitute for a trusted TLS chain. Always extend trust to your CA instead of turning verification off.
### Trusting an internal CA inside the installed JDK
+73 -73
View File
@@ -23,18 +23,18 @@
"@eslint/js": "^10.0.1",
"@jest/globals": "^30.4.1",
"@types/node": "^26.1.1",
"@types/semver": "^7.7.0",
"@typescript-eslint/eslint-plugin": "^8.64.0",
"@types/semver": "^7.8.0",
"@typescript-eslint/eslint-plugin": "^8.67.0",
"@typescript-eslint/parser": "^8.65.0",
"@vercel/ncc": "^0.44.0",
"eslint": "^10.7.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-jest": "^29.15.4",
"eslint-plugin-n": "^18.2.2",
"globals": "^17.7.0",
"globals": "^17.9.0",
"husky": "^9.1.7",
"jest": "^30.4.2",
"lint-staged": "^17.2.0",
"lint-staged": "^17.3.0",
"prettier": "^3.9.5",
"ts-jest": "^29.4.11",
"typescript": "^6.0.3"
@@ -1736,9 +1736,9 @@
}
},
"node_modules/@types/semver": {
"version": "7.7.1",
"resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.7.1.tgz",
"integrity": "sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==",
"version": "7.8.0",
"resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz",
"integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==",
"dev": true,
"license": "MIT"
},
@@ -1767,17 +1767,17 @@
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.65.0.tgz",
"integrity": "sha512-IEgob78X12rHpUmtcwFsXhZdVGJtwTVP8FiCLZkR6GlYVrl2PcuB+KhCE5BlVC/eQpQnu8WXRtkHZuPar+gCRA==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.67.0.tgz",
"integrity": "sha512-Un7Heoyj65NREbKAyIrFxeM143NZpExWmy1Nep4DLeQOeLlTeumPjoNKnBrU5D5moWXbPJgRa5Uwcdu0faVNGQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.12.2",
"@typescript-eslint/scope-manager": "8.65.0",
"@typescript-eslint/type-utils": "8.65.0",
"@typescript-eslint/utils": "8.65.0",
"@typescript-eslint/visitor-keys": "8.65.0",
"@typescript-eslint/scope-manager": "8.67.0",
"@typescript-eslint/type-utils": "8.67.0",
"@typescript-eslint/utils": "8.67.0",
"@typescript-eslint/visitor-keys": "8.67.0",
"ignore": "^7.0.5",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.5.0"
@@ -1790,22 +1790,22 @@
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"@typescript-eslint/parser": "^8.65.0",
"@typescript-eslint/parser": "^8.67.0",
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
"typescript": ">=4.8.4 <6.1.0"
}
},
"node_modules/@typescript-eslint/parser": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.65.0.tgz",
"integrity": "sha512-CZ4nMxWwgu1HEEFNkeaCptra9QCtkmKdgf3sWh1rl1trIhmxLilgTV4cwcbQ4wemnT4sWQN8CaKOmdYx+g2gMA==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.67.0.tgz",
"integrity": "sha512-fUBfTuuEulWqX6V8+O3PtScV01tzYYRUDTAirHFKoRAt7nOzoGiPt0M/bB47wWNy0coOOcgEwAMUtBpykMxl6w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/scope-manager": "8.65.0",
"@typescript-eslint/types": "8.65.0",
"@typescript-eslint/typescript-estree": "8.65.0",
"@typescript-eslint/visitor-keys": "8.65.0",
"@typescript-eslint/scope-manager": "8.67.0",
"@typescript-eslint/types": "8.67.0",
"@typescript-eslint/typescript-estree": "8.67.0",
"@typescript-eslint/visitor-keys": "8.67.0",
"debug": "^4.4.3"
},
"engines": {
@@ -1821,14 +1821,14 @@
}
},
"node_modules/@typescript-eslint/project-service": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.65.0.tgz",
"integrity": "sha512-SxnPhbTsGahizDgbu7oqFH/xVtzIqMd/s+WtnSxNxJZJpLbdT5IPdzg8EZxO3+PoKahXmwJLeNQOpKJb3/bi7Q==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.67.0.tgz",
"integrity": "sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/tsconfig-utils": "^8.65.0",
"@typescript-eslint/types": "^8.65.0",
"@typescript-eslint/tsconfig-utils": "^8.67.0",
"@typescript-eslint/types": "^8.67.0",
"debug": "^4.4.3"
},
"engines": {
@@ -1843,14 +1843,14 @@
}
},
"node_modules/@typescript-eslint/scope-manager": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.65.0.tgz",
"integrity": "sha512-Esbl8OSYiVxBokYgWPf7VVWg/BE798wXhimnn9ML9Pt5qoDf8bfQlgjlKXR/k98+AcNzlLKYrpCcrcuZ9DZLgg==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.67.0.tgz",
"integrity": "sha512-EgvsleTwS4E+WzzSvem8fAUubLwatMNF1B5hHSLQxcvs7q2dtRhGyujHwLJSYlG41niJ7GP24Aha2+0mb1b2kg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.65.0",
"@typescript-eslint/visitor-keys": "8.65.0"
"@typescript-eslint/types": "8.67.0",
"@typescript-eslint/visitor-keys": "8.67.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -1861,9 +1861,9 @@
}
},
"node_modules/@typescript-eslint/tsconfig-utils": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.65.0.tgz",
"integrity": "sha512-j6GzGqCiRdA7Qhur2VVmKZAkBLfnHFQfx4TaJGL9RMveZqCo48jSHHO0DTgizEnGhtWnqmbtCUSrqSkdiY/0Hg==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.67.0.tgz",
"integrity": "sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -1878,15 +1878,15 @@
}
},
"node_modules/@typescript-eslint/type-utils": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.65.0.tgz",
"integrity": "sha512-YjaZ7PRI5qY7ax2L3PbvX0rRyGtipAReCWs0mhhDBHjH/vl0g0BonaGXrKdKpMbIIsMIwDgbk/xzkBTyAltS5g==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.67.0.tgz",
"integrity": "sha512-aVWDXbRmdXO9siTfX4ditQI1T9+zVcNazT48EJCD0v40/9RIFoUgZ05CmGEq9H2gixRpjUn/iplwvlcvutJW/Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.65.0",
"@typescript-eslint/typescript-estree": "8.65.0",
"@typescript-eslint/utils": "8.65.0",
"@typescript-eslint/types": "8.67.0",
"@typescript-eslint/typescript-estree": "8.67.0",
"@typescript-eslint/utils": "8.67.0",
"debug": "^4.4.3",
"ts-api-utils": "^2.5.0"
},
@@ -1903,9 +1903,9 @@
}
},
"node_modules/@typescript-eslint/types": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.65.0.tgz",
"integrity": "sha512-JSSwWNy+H0E/01jJEM+hrX6N0OFDzFzeIhHFSAS01tlVaevpG8cFyYRPhS5yjGOvBUx3sqQHVMjCL1CAZZMxBg==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.67.0.tgz",
"integrity": "sha512-sBtgslww8nsMYUjhdPBiSyUqSzT8uR6g93A2QXnQC8+cGdjz0CyaOdqHDRJb1AtORbZCNUJBBeFA/tNR2uQmww==",
"dev": true,
"license": "MIT",
"engines": {
@@ -1917,16 +1917,16 @@
}
},
"node_modules/@typescript-eslint/typescript-estree": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.65.0.tgz",
"integrity": "sha512-JboAE2swaYt4tb1fHhHTABE2K+OLy09XfcTbhnk4Pw96f9dd2e9iYsJ28gBggHlo5z5x1rkyWvcPoTuNTd4oGg==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.67.0.tgz",
"integrity": "sha512-EKQBCE9yNlRJYm7jdTW5AhDacDUmSwQb0FAJAmK2EKYrNXIsa2vxcSZx6PvJ/dEdI6lS+Y9W+EXckLj0iPFGcw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/project-service": "8.65.0",
"@typescript-eslint/tsconfig-utils": "8.65.0",
"@typescript-eslint/types": "8.65.0",
"@typescript-eslint/visitor-keys": "8.65.0",
"@typescript-eslint/project-service": "8.67.0",
"@typescript-eslint/tsconfig-utils": "8.67.0",
"@typescript-eslint/types": "8.67.0",
"@typescript-eslint/visitor-keys": "8.67.0",
"debug": "^4.4.3",
"minimatch": "^10.2.2",
"semver": "^7.7.3",
@@ -1945,16 +1945,16 @@
}
},
"node_modules/@typescript-eslint/utils": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.65.0.tgz",
"integrity": "sha512-gXiwIHsYreboxeJucHKPvgwl7dXt50mF8s1/c00cP/WoVTyWKFdtfhRWwZiXYFU5H2O8vVoSLNrexFZjYS/SGA==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.67.0.tgz",
"integrity": "sha512-U9D1FdwEWBwok3hxxSdhclMb0twvt9QnjIQ0VfQ1AiX2epnpSgv2ubVDsayOFyY8K6FX+AQ7E0FKWVG3iKsj1A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.9.1",
"@typescript-eslint/scope-manager": "8.65.0",
"@typescript-eslint/types": "8.65.0",
"@typescript-eslint/typescript-estree": "8.65.0"
"@typescript-eslint/scope-manager": "8.67.0",
"@typescript-eslint/types": "8.67.0",
"@typescript-eslint/typescript-estree": "8.67.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -1969,13 +1969,13 @@
}
},
"node_modules/@typescript-eslint/visitor-keys": {
"version": "8.65.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.65.0.tgz",
"integrity": "sha512-8C71BQkGjiMmXtop7pHVJu1l2NNShFdkCyD6a2ezzs5vU/L3LRtb69EtcteFwz0mYMPzIgOw0n6OV4VBUWZd7A==",
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.67.0.tgz",
"integrity": "sha512-fkv8dHRDqfGtTHuJeebdrQ7cX6Ad4WAS00rgHh9UGvMycF1mjBfsxry1XsLIFhWZ6Judlh6UdzK+TYlbpCXgnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.65.0",
"@typescript-eslint/types": "8.67.0",
"eslint-visitor-keys": "^5.0.0"
},
"engines": {
@@ -2635,9 +2635,9 @@
}
},
"node_modules/brace-expansion": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz",
"integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
@@ -3691,9 +3691,9 @@
}
},
"node_modules/globals": {
"version": "17.8.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-17.8.0.tgz",
"integrity": "sha512-Zz/LMDZScFmkakeL2cTHzf+PbWKdpU3uclqkZT7TjDG58j5WPt0PpA+n9uPI24fZtlw07q0OtEi84K+umsRzqQ==",
"version": "17.9.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-17.9.0.tgz",
"integrity": "sha512-m/MvAW61QVU5VDNF1Vj8axt016h8w7L5TU1e9zlab7XIttAT2YAlCwl75K1fOqvMM9apmD7lbCIRhpfkhmxhCg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -4605,9 +4605,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "3.15.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz",
"integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==",
"version": "3.15.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz",
"integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4714,9 +4714,9 @@
"license": "MIT"
},
"node_modules/lint-staged": {
"version": "17.2.0",
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-17.2.0.tgz",
"integrity": "sha512-FchGnFe4i4B1C/a35SPU9bNGPEHSC1+1iV0plLjzBmKVe9klZrlRfSgK6Cw4VeHyqOXbJUXP0vON61uRftNQ0A==",
"version": "17.3.0",
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-17.3.0.tgz",
"integrity": "sha512-woZS3vNe3UKqBaLPvbLOtKRY4tLANpWQhom12MGWqC8Mh1lCOO+WgSwmX2amjJAqTY9BkXYW87fCUH5H9Ph6xw==",
"dev": true,
"license": "MIT",
"dependencies": {
+5 -5
View File
@@ -18,7 +18,7 @@
"fix": "npm run format && npm run lint:fix && npm run build",
"prepare": "husky install",
"prerelease": "npm run-script build",
"release": "git add -f dist/setup/*.js dist/setup/package.json dist/cleanup/index.js",
"release": "git add -f dist/setup/*.js dist/setup/package.json dist/cleanup/*.js",
"test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --runInBand --coverage"
},
"lint-staged": {
@@ -56,18 +56,18 @@
"@eslint/js": "^10.0.1",
"@jest/globals": "^30.4.1",
"@types/node": "^26.1.1",
"@types/semver": "^7.7.0",
"@typescript-eslint/eslint-plugin": "^8.64.0",
"@types/semver": "^7.8.0",
"@typescript-eslint/eslint-plugin": "^8.67.0",
"@typescript-eslint/parser": "^8.65.0",
"@vercel/ncc": "^0.44.0",
"eslint": "^10.7.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-jest": "^29.15.4",
"eslint-plugin-n": "^18.2.2",
"globals": "^17.7.0",
"globals": "^17.9.0",
"husky": "^9.1.7",
"jest": "^30.4.2",
"lint-staged": "^17.2.0",
"lint-staged": "^17.3.0",
"prettier": "^3.9.5",
"ts-jest": "^29.4.11",
"typescript": "^6.0.3"
+269 -46
View File
@@ -9,18 +9,28 @@ import * as gpg from './gpg.js';
import {getBooleanInput} from './util.js';
import {escapeXmlText} from './xml.js';
export interface MavenServerCredentials {
id: string;
usernameEnvVar: string;
passwordEnvVar: string;
}
export interface MavenRepository {
id: string;
url: string;
snapshotsEnabled: boolean;
releasesEnabled?: boolean;
}
export interface MavenRepositorySettings {
repositories: MavenRepository[];
includeCentral: boolean;
prioritizeCentral: boolean;
}
export async function configureAuthentication() {
const id = core.getInput(constants.INPUT_SERVER_ID);
const usernameEnvVar = getInputWithDeprecatedAlias(
constants.INPUT_SERVER_USERNAME_ENV_VAR,
constants.INPUT_SERVER_USERNAME_DEPRECATED,
constants.INPUT_DEFAULT_SERVER_USERNAME
);
const passwordEnvVar = getInputWithDeprecatedAlias(
constants.INPUT_SERVER_PASSWORD_ENV_VAR,
constants.INPUT_SERVER_PASSWORD_DEPRECATED,
constants.INPUT_DEFAULT_SERVER_PASSWORD
);
const servers = getMavenServerSettings();
const repositorySettings = getMavenRepositorySettings();
const settingsDirectory =
core.getInput(constants.INPUT_SETTINGS_PATH) ||
path.join(os.homedir(), constants.M2_DIR);
@@ -42,18 +52,23 @@ export async function configureAuthentication() {
}
await createAuthenticationSettings(
id,
usernameEnvVar,
passwordEnvVar,
servers,
settingsDirectory,
overwriteSettings,
gpgPassphraseEnvVar
gpgPassphraseEnvVar,
repositorySettings
);
if (gpgPrivateKey) {
core.info('Importing private gpg key');
const keyFingerprint = (await gpg.importKey(gpgPrivateKey)) || '';
core.saveState(constants.STATE_GPG_PRIVATE_KEY_FINGERPRINT, keyFingerprint);
const gpgHome = await gpg.importKey(gpgPrivateKey);
try {
core.saveState(constants.STATE_GPG_HOME, gpgHome);
core.exportVariable('GNUPGHOME', gpg.toGpgPath(gpgHome));
} catch (error) {
await gpg.removeGpgHome(gpgHome);
throw error;
}
}
}
@@ -74,31 +89,179 @@ export function getInputWithDeprecatedAlias(
return value || deprecatedValue || defaultValue || '';
}
// only exported for testing purposes
export function getMavenServerSettings(): MavenServerCredentials[] {
const entries = core.getMultilineInput(
constants.INPUT_MVN_SERVER_CREDENTIALS
);
if (entries.some(entry => entry.trim())) {
return parseMavenServerCredentials(entries);
}
return [
{
id: core.getInput(constants.INPUT_SERVER_ID),
usernameEnvVar: getInputWithDeprecatedAlias(
constants.INPUT_SERVER_USERNAME_ENV_VAR,
constants.INPUT_SERVER_USERNAME_DEPRECATED,
constants.INPUT_DEFAULT_SERVER_USERNAME
),
passwordEnvVar: getInputWithDeprecatedAlias(
constants.INPUT_SERVER_PASSWORD_ENV_VAR,
constants.INPUT_SERVER_PASSWORD_DEPRECATED,
constants.INPUT_DEFAULT_SERVER_PASSWORD
)
}
];
}
// only exported for testing purposes
export function parseMavenServerCredentials(
entries: string[]
): MavenServerCredentials[] {
const servers: MavenServerCredentials[] = [];
const serverIds = new Set<string>();
entries.forEach((entry, index) => {
if (!entry.trim()) {
return;
}
const fields = entry.split(':');
if (fields.length !== 3) {
throw new Error(
`Invalid mvn-server-credentials entry at line ${index + 1}. Expected format: server-id:USERNAME_ENV:PASSWORD_ENV`
);
}
const [id, usernameEnvVar, passwordEnvVar] = fields.map(field =>
field.trim()
);
if (!id || !usernameEnvVar || !passwordEnvVar) {
throw new Error(
`Invalid mvn-server-credentials entry at line ${index + 1}. server-id, username environment variable, and password environment variable are required`
);
}
if (serverIds.has(id)) {
throw new Error(
`Duplicate server-id '${id}' in mvn-server-credentials input`
);
}
serverIds.add(id);
servers.push({id, usernameEnvVar, passwordEnvVar});
});
return servers;
}
// only exported for testing purposes
export function getMavenRepositorySettings():
MavenRepositorySettings | undefined {
const entries = core.getMultilineInput(constants.INPUT_MVN_REPOSITORIES);
if (!entries.some(entry => entry.trim())) {
return undefined;
}
const includeCentral = getBooleanInput(
constants.INPUT_MVN_REPOSITORIES_INCLUDE_CENTRAL,
true
);
return {
repositories: parseMavenRepositories(entries, includeCentral),
includeCentral,
prioritizeCentral: getBooleanInput(
constants.INPUT_MVN_REPOSITORIES_PRIORITIZE_CENTRAL,
true
)
};
}
// only exported for testing purposes
export function parseMavenRepositories(
entries: string[],
includeCentral: boolean
): MavenRepository[] {
const repositories: MavenRepository[] = [];
const repositoryIds = new Set<string>();
entries.forEach((entry, index) => {
if (!entry.trim()) {
return;
}
const firstSeparator = entry.indexOf(':');
const lastSeparator = entry.lastIndexOf(':');
if (firstSeparator <= 0 || lastSeparator <= firstSeparator) {
throw new Error(
`Invalid mvn-repositories entry at line ${index + 1}. Expected format: repository-id:repository-url:snapshots-enabled`
);
}
const id = entry.slice(0, firstSeparator).trim();
const url = entry.slice(firstSeparator + 1, lastSeparator).trim();
const snapshotsValue = entry
.slice(lastSeparator + 1)
.trim()
.toLowerCase();
if (!id || !url || !snapshotsValue) {
throw new Error(
`Invalid mvn-repositories entry at line ${index + 1}. repository-id, repository URL, and snapshots-enabled are required`
);
}
if (snapshotsValue !== 'true' && snapshotsValue !== 'false') {
throw new Error(
`Invalid snapshots-enabled value '${snapshotsValue}' in mvn-repositories entry at line ${index + 1}. Expected true or false`
);
}
if (repositoryIds.has(id)) {
throw new Error(
`Duplicate repository-id '${id}' in mvn-repositories input`
);
}
if (includeCentral && id === constants.MAVEN_CENTRAL_REPOSITORY_ID) {
throw new Error(
`Repository-id '${constants.MAVEN_CENTRAL_REPOSITORY_ID}' is reserved when ${constants.INPUT_MVN_REPOSITORIES_INCLUDE_CENTRAL} is enabled`
);
}
repositoryIds.add(id);
repositories.push({
id,
url,
snapshotsEnabled: snapshotsValue === 'true'
});
});
return repositories;
}
export async function createAuthenticationSettings(
id: string,
usernameEnvVar: string,
passwordEnvVar: string,
servers: MavenServerCredentials[],
settingsDirectory: string,
overwriteSettings: boolean,
gpgPassphraseEnvVar: string | undefined = undefined
gpgPassphraseEnvVar: string | undefined = undefined,
repositorySettings: MavenRepositorySettings | undefined = undefined
) {
core.info(`Creating ${constants.MVN_SETTINGS_FILE} with server-id: ${id}`);
core.info(
`Creating ${constants.MVN_SETTINGS_FILE} with server-id: ${servers.map(server => server.id).join(', ')}`
);
// when an alternate m2 location is specified use only that location (no .m2 directory)
// otherwise use the home/.m2/ path
await io.mkdirP(settingsDirectory);
await write(
settingsDirectory,
generate(id, usernameEnvVar, passwordEnvVar, gpgPassphraseEnvVar),
generate(servers, gpgPassphraseEnvVar, repositorySettings),
overwriteSettings
);
}
// only exported for testing purposes
export function generate(
id: string,
usernameEnvVar: string,
passwordEnvVar: string,
gpgPassphraseEnvVar?: string | undefined
servers: MavenServerCredentials[],
gpgPassphraseEnvVar?: string | undefined,
repositorySettings?: MavenRepositorySettings | undefined
) {
// The maven-gpg-plugin reads the passphrase from the environment variable
// named by the `gpg.passphraseEnvName` property (default MAVEN_GPG_PASSPHRASE).
@@ -115,30 +278,90 @@ export function generate(
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
' xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">',
' <interactiveMode>false</interactiveMode>',
' <servers>',
' <server>',
` <id>${escapeXmlText(id)}</id>`,
` <username>${escapeXmlText(`\${env.${usernameEnvVar}}`)}</username>`,
` <password>${escapeXmlText(`\${env.${passwordEnvVar}}`)}</password>`,
' </server>',
' </servers>'
' <servers>'
];
if (includeGpgPassphraseProfile) {
for (const server of servers) {
lines.push(
' <profiles>',
' <profile>',
` <id>${constants.GPG_PASSPHRASE_PROFILE_ID}</id>`,
' <properties>',
` <gpg.passphraseEnvName>${escapeXmlText(gpgPassphraseEnvVar)}</gpg.passphraseEnvName>`,
' </properties>',
' </profile>',
' </profiles>',
' <activeProfiles>',
` <activeProfile>${constants.GPG_PASSPHRASE_PROFILE_ID}</activeProfile>`,
' </activeProfiles>'
' <server>',
` <id>${escapeXmlText(server.id)}</id>`,
` <username>${escapeXmlText(`\${env.${server.usernameEnvVar}}`)}</username>`,
` <password>${escapeXmlText(`\${env.${server.passwordEnvVar}}`)}</password>`,
' </server>'
);
}
lines.push(' </servers>');
if (repositorySettings || includeGpgPassphraseProfile) {
lines.push(' <profiles>');
if (repositorySettings) {
const centralRepository: MavenRepository = {
id: constants.MAVEN_CENTRAL_REPOSITORY_ID,
url: constants.MAVEN_CENTRAL_REPOSITORY_URL,
snapshotsEnabled: false
};
const customCentralConfigured = repositorySettings.repositories.some(
repository => repository.id === constants.MAVEN_CENTRAL_REPOSITORY_ID
);
const repositories = repositorySettings.includeCentral
? repositorySettings.prioritizeCentral
? [centralRepository, ...repositorySettings.repositories]
: [...repositorySettings.repositories, centralRepository]
: customCentralConfigured
? repositorySettings.repositories
: [
...repositorySettings.repositories,
{...centralRepository, releasesEnabled: false}
];
lines.push(
' <profile>',
` <id>${constants.MAVEN_REPOSITORIES_PROFILE_ID}</id>`,
' <repositories>'
);
for (const repository of repositories) {
lines.push(
' <repository>',
` <id>${escapeXmlText(repository.id)}</id>`,
` <url>${escapeXmlText(repository.url)}</url>`,
...(repository.releasesEnabled === undefined
? []
: [
' <releases>',
` <enabled>${repository.releasesEnabled}</enabled>`,
' </releases>'
]),
' <snapshots>',
` <enabled>${repository.snapshotsEnabled}</enabled>`,
' </snapshots>',
' </repository>'
);
}
lines.push(' </repositories>', ' </profile>');
}
if (includeGpgPassphraseProfile) {
lines.push(
' <profile>',
` <id>${constants.GPG_PASSPHRASE_PROFILE_ID}</id>`,
' <properties>',
` <gpg.passphraseEnvName>${escapeXmlText(gpgPassphraseEnvVar)}</gpg.passphraseEnvName>`,
' </properties>',
' </profile>'
);
}
lines.push(' </profiles>', ' <activeProfiles>');
if (repositorySettings) {
lines.push(
` <activeProfile>${constants.MAVEN_REPOSITORIES_PROFILE_ID}</activeProfile>`
);
}
if (includeGpgPassphraseProfile) {
lines.push(
` <activeProfile>${constants.GPG_PASSPHRASE_PROFILE_ID}</activeProfile>`
);
}
lines.push(' </activeProfiles>');
}
lines.push('</settings>');
return lines.join('\n');
+5
View File
@@ -82,6 +82,7 @@ const supportedPackageManager: PackageManager[] = [
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---gradle
pattern: [
'**/*.gradle*',
'**/gradle.properties',
'**/gradle-wrapper.properties',
'buildSrc/**/Versions.kt',
'buildSrc/**/Dependencies.kt',
@@ -137,6 +138,10 @@ function findPackageManager(id: string): PackageManager {
return packageManager;
}
export function validatePackageManager(id: string): void {
findPackageManager(id);
}
function resolveCachePaths(
packageManager: PackageManager,
cachePaths: string[]
+35 -20
View File
@@ -1,22 +1,26 @@
import * as core from '@actions/core';
import * as gpg from './gpg.js';
import * as constants from './constants.js';
import {getBooleanInput, isJobStatusSuccess} from './util.js';
import {
getBooleanInput,
isJdkCacheEnabled,
isJobStatusSuccess
} from './util.js';
import {fileURLToPath} from 'url';
async function removePrivateKeyFromKeychain() {
if (core.getInput(constants.INPUT_GPG_PRIVATE_KEY, {required: false})) {
core.info('Removing private key from keychain');
try {
const keyFingerprint = core.getState(
constants.STATE_GPG_PRIVATE_KEY_FINGERPRINT
);
await gpg.deleteKey(keyFingerprint);
} catch (error) {
core.setFailed(
`Failed to remove private key due to: ${(error as Error).message}`
);
}
async function removeGpgHome() {
const gpgHome = core.getState(constants.STATE_GPG_HOME);
if (!gpgHome) {
return;
}
core.info('Removing private key from isolated GPG home');
try {
await gpg.removeGpgHome(gpgHome);
} catch (error) {
core.setFailed(
`Failed to remove isolated GPG home due to: ${(error as Error).message}`
);
}
}
@@ -24,10 +28,11 @@ async function removePrivateKeyFromKeychain() {
* Check given input and run a save process for the specified package manager
* @returns Promise that will be resolved when the save process finishes
*/
async function saveCache() {
async function saveCaches() {
const jobStatus = isJobStatusSuccess();
const cache = core.getInput(constants.INPUT_CACHE);
if (!jobStatus || !cache) {
const cacheJdk = isJdkCacheEnabled(cache);
if (!jobStatus || (!cache && !cacheJdk)) {
return;
}
@@ -36,8 +41,18 @@ async function saveCache() {
return;
}
const {save} = await import('./cache.js');
await save(cache);
const saves: Promise<void>[] = [];
if (cache) {
const {save} = await import('./cache.js');
saves.push(save(cache));
}
if (cacheJdk) {
const {saveJdkCaches} = await import('./jdk-cache.js');
const {saveJdkResolutionCaches} = await import('./jdk-resolution-cache.js');
saves.push(saveJdkCaches());
saves.push(saveJdkResolutionCaches());
}
await Promise.all(saves);
}
/**
@@ -58,8 +73,8 @@ async function ignoreError(promise: Promise<void>) {
}
export async function run() {
await removePrivateKeyFromKeychain();
await ignoreError(saveCache());
await removeGpgHome();
await ignoreError(saveCaches());
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
+12 -1
View File
@@ -12,6 +12,12 @@ export const INPUT_SET_DEFAULT = 'set-default';
export const INPUT_PROBLEM_MATCHER = 'problem-matcher';
export const INPUT_VERIFY_SIGNATURE = 'verify-signature';
export const INPUT_VERIFY_SIGNATURE_PUBLIC_KEY = 'verify-signature-public-key';
export const INPUT_MVN_SERVER_CREDENTIALS = 'mvn-server-credentials';
export const INPUT_MVN_REPOSITORIES = 'mvn-repositories';
export const INPUT_MVN_REPOSITORIES_INCLUDE_CENTRAL =
'mvn-repositories-include-central';
export const INPUT_MVN_REPOSITORIES_PRIORITIZE_CENTRAL =
'mvn-repositories-prioritize-central';
export const INPUT_SERVER_ID = 'server-id';
export const INPUT_SERVER_USERNAME_ENV_VAR = 'server-username-env-var';
export const INPUT_SERVER_PASSWORD_ENV_VAR = 'server-password-env-var';
@@ -35,14 +41,19 @@ export const MAVEN_GPG_PASSPHRASE_DEFAULT_ENV = 'MAVEN_GPG_PASSPHRASE';
// Id of the settings.xml profile used to set `gpg.passphraseEnvName`.
export const GPG_PASSPHRASE_PROFILE_ID = 'setup-java-gpg';
export const MAVEN_REPOSITORIES_PROFILE_ID = 'setup-java-repositories';
export const MAVEN_CENTRAL_REPOSITORY_ID = 'central';
export const MAVEN_CENTRAL_REPOSITORY_URL =
'https://repo.maven.apache.org/maven2';
export const INPUT_CACHE = 'cache';
export const INPUT_CACHE_JDK = 'cache-jdk';
export const INPUT_CACHE_DEPENDENCY_PATH = 'cache-dependency-path';
export const INPUT_CACHE_PATH = 'cache-path';
export const INPUT_CACHE_READ_ONLY = 'cache-read-only';
export const INPUT_JOB_STATUS = 'job-status';
export const STATE_GPG_PRIVATE_KEY_FINGERPRINT = 'gpg-private-key-fingerprint';
export const STATE_GPG_HOME = 'gpg-home';
export const M2_DIR = '.m2';
export const MVN_SETTINGS_FILE = 'settings.xml';
+297 -6
View File
@@ -20,7 +20,11 @@ import {MACOS_JAVA_CONTENT_POSTFIX} from '../constants.js';
import {RetryingHttpClient} from '../retrying-http-client.js';
import os from 'os';
import {expectedDigestLength, verifyChecksum} from '../checksum.js';
import {normalizeArchitecture} from './platform-types.js';
import {
getJavaPlatformIdentity,
normalizeArchitecture
} from './platform-types.js';
import type {JdkCache} from '../jdk-cache.js';
export abstract class JavaBase {
protected http: httpm.HttpClient;
@@ -31,6 +35,13 @@ export abstract class JavaBase {
protected latest: boolean;
protected checkLatest: boolean;
protected forceDownload: boolean;
protected cacheJdk: boolean;
/**
* Whether the concrete version of a floating release has been established
* from the checksum-bound resolution cache. Until then the release version is
* only the requested major and says nothing about the bytes behind the URL.
*/
private floatingVersionVerified = false;
protected setDefault: boolean;
protected verifySignature: boolean;
protected verifySignaturePublicKey: string | undefined;
@@ -52,6 +63,7 @@ export abstract class JavaBase {
this.packageType = installerOptions.packageType;
this.checkLatest = installerOptions.checkLatest;
this.forceDownload = installerOptions.forceDownload ?? false;
this.cacheJdk = installerOptions.cacheJdk ?? false;
this.setDefault =
installerOptions.setDefault !== undefined
? installerOptions.setDefault
@@ -170,19 +182,81 @@ export abstract class JavaBase {
}
let foundJava = this.forceDownload ? null : this.findInToolcache();
if (foundJava && !this.checkLatest && !this.latest) {
if (
foundJava &&
!this.checkLatest &&
!this.latest &&
!this.requiresRemoteResolution()
) {
core.info(`Resolved Java ${foundJava.version} from tool-cache`);
} else {
core.info('Trying to resolve the latest version from remote');
try {
const javaRelease = await this.findPackageForDownload(this.version);
let javaRelease = await this.resolveJavaRelease();
core.info(`Resolved latest version as ${javaRelease.version}`);
if (javaRelease.floating) {
// A tool-cache entry has no source identity, and until the
// checksum-bound resolution cache maps the current artifact to a
// concrete version the release version is still just the requested
// major — so nothing already on the runner can be trusted. Once that
// mapping is known, an installation of exactly that version is the
// artifact we would otherwise download.
foundJava =
this.floatingVersionVerified && !this.forceDownload
? this.findConcreteVersionInToolcache(javaRelease.version)
: null;
}
if (!this.forceDownload && foundJava?.version === javaRelease.version) {
core.info(`Resolved Java ${foundJava.version} from tool-cache`);
} else {
core.info('Trying to download...');
foundJava = await this.downloadTool(javaRelease);
core.info(`Java ${foundJava.version} was downloaded`);
let jdkCache =
this.cacheJdk &&
(!javaRelease.floating ||
(this.hasStableReleaseIdentity(javaRelease) &&
semver.valid(javaRelease.version)))
? await this.createJdkCache(javaRelease)
: undefined;
if (!this.forceDownload && jdkCache) {
const {restoreJdk} = await import('../jdk-cache.js');
const restored = await restoreJdk(jdkCache);
if (restored) {
const restoredPath = this.getRestoredJdkPath(javaRelease.version);
if (restoredPath) {
foundJava = {
version: javaRelease.version,
path: restoredPath
};
}
}
}
if (!foundJava || foundJava.version !== javaRelease.version) {
core.info('Trying to download...');
foundJava = await this.downloadTool(javaRelease);
core.info(`Java ${foundJava.version} was downloaded`);
if (javaRelease.floating) {
if (
!semver.valid(foundJava.version) ||
!isVersionSatisfies(this.version, foundJava.version)
) {
throw new Error(
`The downloaded ${this.distribution} artifact reported Java ${foundJava.version}, which does not satisfy '${this.version}'.`
);
}
javaRelease = {...javaRelease, version: foundJava.version};
await this.registerFloatingResolution(javaRelease);
jdkCache =
this.cacheJdk && this.hasStableReleaseIdentity(javaRelease)
? await this.createJdkCache(javaRelease)
: undefined;
}
if (jdkCache) {
// Register after the installation exists so its identity is
// captured; the post-job save refuses to upload a path whose
// installation was replaced afterwards.
const {registerJdk} = await import('../jdk-cache.js');
registerJdk(jdkCache);
}
}
}
} catch (error: any) {
this.logSetupError(error);
@@ -214,6 +288,158 @@ export abstract class JavaBase {
return foundJava;
}
/**
* Resolves the release to install, preferring a cached resolution over the
* distribution's metadata API.
*
* Only Temurin is preinstalled on hosted runners, so for every other
* distribution the tool-cache lookup misses and the vendor API becomes a
* per-job dependency even when the JDK itself is already in the GitHub
* Actions cache. A cached resolution removes that dependency, and because it
* carries the download URL and checksum it also keeps a job working when the
* vendor API is unavailable but the JDK still has to be downloaded.
*/
private async resolveJavaRelease(): Promise<JavaDownloadRelease> {
if (
!this.cacheJdk ||
this.checkLatest ||
this.latest ||
this.forceDownload ||
this.requiresRemoteResolution()
) {
const release = await this.findPackageForDownload(this.version);
return this.restoreFloatingResolution(release);
}
const {restoreJdkResolution, registerJdkResolution} =
await import('../jdk-resolution-cache.js');
const request = {
distribution: this.distribution,
packageType: this.packageType,
platform: getJavaPlatformIdentity(),
architecture: this.architecture,
versionSpec: this.version,
stable: this.stable
};
const restored = await restoreJdkResolution(request);
if (restored?.fresh) {
core.info(
`Resolved ${this.distribution} ${restored.release.version} from the resolution cache`
);
return restored.release;
}
try {
const javaRelease = await this.findPackageForDownload(this.version);
if (!javaRelease.floating) {
registerJdkResolution(request, javaRelease);
}
return this.restoreFloatingResolution(javaRelease);
} catch (error) {
if (!restored) {
throw error;
}
// The cached resolution is older than the current bucket, but falling
// back to it is strictly better than failing the job because the vendor
// metadata API is down.
core.warning(
`Failed to resolve ${this.distribution} ${this.version} from remote (${
error instanceof Error ? error.message : String(error)
}); falling back to the cached resolution for ${restored.release.version}.`
);
return restored.release;
}
}
protected requiresRemoteResolution(): boolean {
return false;
}
private async createJdkCache(
javaRelease: JavaDownloadRelease
): Promise<JdkCache> {
const {getJdkVerificationIdentity} = await import('../jdk-cache.js');
return {
distribution: this.distribution,
packageType: this.packageType,
architecture: this.architecture,
version: javaRelease.version,
source: this.getJdkReleaseIdentity(javaRelease),
verification: getJdkVerificationIdentity(
this.verifySignature,
this.verifySignaturePublicKey
),
path: this.getJdkCachePath(javaRelease.version)
};
}
private async restoreFloatingResolution(
javaRelease: JavaDownloadRelease
): Promise<JavaDownloadRelease> {
if (
!javaRelease.floating ||
!this.hasStableReleaseIdentity(javaRelease) ||
!this.cacheJdk ||
this.forceDownload
) {
return javaRelease;
}
const {restoreJdkResolution} = await import('../jdk-resolution-cache.js');
const restored = await restoreJdkResolution(
this.getFloatingResolutionRequest(javaRelease)
);
if (!restored) {
return javaRelease;
}
if (
!semver.valid(restored.release.version) ||
!isVersionSatisfies(this.version, restored.release.version)
) {
core.debug(
`Ignoring the cached concrete version '${restored.release.version}' for ${this.distribution} ${this.version}.`
);
return javaRelease;
}
core.info(
`Resolved ${this.distribution} ${restored.release.version} for the current floating artifact`
);
this.floatingVersionVerified = true;
return {...javaRelease, version: restored.release.version};
}
private async registerFloatingResolution(
javaRelease: JavaDownloadRelease
): Promise<void> {
if (
!this.hasStableReleaseIdentity(javaRelease) ||
!this.cacheJdk ||
this.forceDownload
) {
return;
}
const {registerJdkResolution} = await import('../jdk-resolution-cache.js');
registerJdkResolution(
this.getFloatingResolutionRequest(javaRelease),
javaRelease
);
}
private getFloatingResolutionRequest(javaRelease: JavaDownloadRelease) {
return {
distribution: this.distribution,
packageType: this.packageType,
platform: getJavaPlatformIdentity(),
architecture: this.architecture,
versionSpec: this.version,
stable: this.stable,
source: this.getJdkReleaseIdentity(javaRelease)
};
}
private logSetupError(error: any): void {
const httpStatusCode =
error instanceof tc.HTTPError
@@ -299,6 +525,71 @@ export abstract class JavaBase {
return version.replace('+', '-');
}
protected getJdkCachePath(version: string): string {
const toolCache = process.env['RUNNER_TOOL_CACHE'];
if (!toolCache) {
return '';
}
return path.join(
toolCache,
this.toolcacheFolderName,
this.getToolcacheVersionName(version)
);
}
protected getRestoredJdkPath(version: string): string | null {
const basePath = this.getJdkCachePath(version);
if (!basePath) {
return null;
}
const architecturePath = path.join(basePath, this.architecture);
return fs.existsSync(architecturePath) &&
fs.existsSync(`${architecturePath}.complete`)
? architecturePath
: null;
}
/**
* Locates an installation of an exact version in the tool cache, unlike
* `findInToolcache()` which returns the newest entry satisfying the requested
* range. Used to reuse a JDK the runner already holds instead of downloading
* the identical artifact again.
*/
private findConcreteVersionInToolcache(
version: string
): JavaInstallerResults | null {
if (!semver.valid(version)) {
return null;
}
const installedPath = this.getRestoredJdkPath(version);
return installedPath ? {version, path: installedPath} : null;
}
private getJdkReleaseIdentity(javaRelease: JavaDownloadRelease): string {
if (javaRelease.checksum) {
return `${javaRelease.checksum.algorithm}:${javaRelease.checksum.value}`;
}
if (javaRelease.fingerprint) {
return javaRelease.fingerprint;
}
try {
const url = new URL(javaRelease.url);
return `${url.origin}${url.pathname}`;
} catch {
return javaRelease.url;
}
}
/**
* Whether the release identity pins the exact bytes behind `url`. A floating
* URL is a constant string, so it only becomes a safe cache identity once a
* checksum or a response validator distinguishes one published build from the
* next.
*/
private hasStableReleaseIdentity(javaRelease: JavaDownloadRelease): boolean {
return Boolean(javaRelease.checksum ?? javaRelease.fingerprint);
}
protected findInToolcache(): JavaInstallerResults | null {
// we can't use tc.find directly because firstly, we need to filter versions by stability flag
// if *-ea is provided, take only ea versions from toolcache, otherwise - only stable versions
+16
View File
@@ -4,6 +4,7 @@ export interface JavaInstallerOptions {
packageType: string;
checkLatest: boolean;
forceDownload?: boolean;
cacheJdk?: boolean;
setDefault?: boolean;
verifySignature?: boolean;
verifySignaturePublicKey?: string;
@@ -27,4 +28,19 @@ export interface JavaDownloadRelease {
url: string;
signatureUrl?: string;
checksum?: ChecksumMetadata;
/**
* Whether `url` points at a location whose contents change over time, such as
* a vendor's `/latest/` path. The URL and its checksum are only consistent
* with each other at the moment they are resolved, so such a release must not
* be reused by a later job.
*/
floating?: boolean;
/**
* Validator identifying the exact bytes a mutable `url` currently serves,
* derived from the response headers of the HEAD request that resolved it.
* Used as the cache identity for a floating release when the vendor
* publishes no checksum, so that a republished artifact produces a different
* identity instead of being masked by the constant URL.
*/
fingerprint?: string;
}
+5 -2
View File
@@ -1,8 +1,8 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
import {
cacheJdkDir,
extractJdkFile,
getDownloadArchiveExtension,
convertVersionToSemver,
@@ -18,6 +18,7 @@ import {
ICorrettoAllAvailableVersions,
ICorrettoAvailableVersions
} from './models.js';
import {isAlpineLinux} from '../platform-types.js';
const CORRETTO_VERSIONS_URL =
'https://corretto.github.io/corretto-downloads/latest_links/indexmap_with_checksum.json';
@@ -46,7 +47,7 @@ export class CorrettoDistribution extends JavaBase {
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
version,
@@ -189,6 +190,8 @@ export class CorrettoDistribution extends JavaBase {
return 'macos';
case 'win32':
return 'windows';
case 'linux':
return isAlpineLinux() ? 'alpine' : 'linux';
default:
return process.platform;
}
@@ -98,6 +98,10 @@ export async function getJavaDistribution(
const {OpenJdkDistribution} = await import('./openjdk/installer.js');
return new OpenJdkDistribution(normalizedInstallerOptions);
}
case JavaDistribution.RedHat: {
const {RedHatDistribution} = await import('./redhat/installer.js');
return new RedHatDistribution(normalizedInstallerOptions);
}
default:
return null;
}
+5 -2
View File
@@ -1,5 +1,4 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import semver from 'semver';
import fs from 'fs';
@@ -7,6 +6,7 @@ import path from 'path';
import {JavaBase} from '../base-installer.js';
import {
cacheJdkDir,
convertVersionToSemver,
extractJdkFile,
getDownloadArchiveExtension,
@@ -15,6 +15,7 @@ import {
renameWinArchive
} from '../../util.js';
import {IDragonwellVersions, IDragonwellAllVersions} from './models.js';
import {isAlpineLinux} from '../platform-types.js';
import {
JavaDownloadRelease,
JavaInstallerOptions,
@@ -121,7 +122,7 @@ export class DragonwellDistribution extends JavaBase {
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
version,
@@ -202,6 +203,8 @@ export class DragonwellDistribution extends JavaBase {
switch (process.platform) {
case 'win32':
return 'windows';
case 'linux':
return isAlpineLinux() ? 'alpine-linux' : 'linux';
default:
return process.platform;
}
+26 -5
View File
@@ -1,5 +1,4 @@
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';
@@ -12,10 +11,13 @@ import {
JavaInstallerResults
} from '../base-models.js';
import {
cacheJdkDir,
convertVersionToSemver,
extractJdkFile,
getArtifactFingerprint,
getDownloadArchiveExtension,
getGitHubHttpHeaders,
getJavaVersionFromReleaseFile,
getLatestMajorVersion,
getNextPageUrlFromLinkHeader,
isVersionSatisfies,
@@ -95,22 +97,33 @@ export class GraalVMDistribution extends JavaBase {
}
const archivePath = path.join(extractedJavaPath, dirContents[0]);
const version = this.getToolcacheVersionName(javaRelease.version);
const installedVersion = javaRelease.floating
? getJavaVersionFromReleaseFile(archivePath)
: javaRelease.version;
const version = this.getToolcacheVersionName(installedVersion);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
version,
this.architecture
);
return {version: javaRelease.version, path: javaPath};
return {version: installedVersion, path: javaPath};
} catch (error) {
core.error(`Failed to download and extract GraalVM: ${error}`);
throw error;
}
}
protected requiresRemoteResolution(): boolean {
return (
this.distribution === 'GraalVM' &&
this.stable &&
!this.version.includes('.')
);
}
protected setJavaDefault(version: string, toolPath: string): void {
super.setJavaDefault(version, toolPath);
core.exportVariable('GRAALVM_HOME', toolPath);
@@ -146,10 +159,18 @@ export class GraalVMDistribution extends JavaBase {
const response = await this.http.head(fileUrl);
this.handleHttpResponse(response, range);
// A major-only range resolves to the vendor's `/latest/` path, whose
// contents change when a new build is published.
const floating = !range.includes('.');
return {
url: fileUrl,
version: range,
checksum: await this.fetchChecksum(`${fileUrl}.sha256`, 'sha256')
checksum: await this.fetchChecksum(`${fileUrl}.sha256`, 'sha256'),
floating,
fingerprint: floating
? getArtifactFingerprint(response.message.headers)
: undefined
};
}
+53 -32
View File
@@ -1,5 +1,4 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
@@ -12,10 +11,22 @@ import {
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models.js';
import {extractJdkFile, isVersionSatisfies} from '../../util.js';
import {
cacheJdkDir,
extractJdkFile,
getGitHubToken,
getNextPageUrlFromLinkHeader,
isVersionSatisfies,
MAX_PAGINATION_PAGES,
validatePaginationUrl
} from '../../util.js';
import {OutgoingHttpHeaders} from 'http';
import {HttpCodes} from '@actions/http-client';
const JETBRAINS_RELEASES_URL =
'https://api.github.com/repos/JetBrains/JetBrainsRuntime/releases?per_page=100';
const GITHUB_API_ORIGIN = 'https://api.github.com';
export class JetBrainsDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('JetBrains', installerOptions);
@@ -79,7 +90,7 @@ export class JetBrainsDistribution extends JavaBase {
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
version,
@@ -97,46 +108,56 @@ export class JetBrainsDistribution extends JavaBase {
console.time('Retrieving available versions for JBR took'); // eslint-disable-line no-console
}
// need to iterate through all pages to retrieve the list of all versions
// GitHub API doesn't provide way to retrieve the count of pages to iterate so infinity loop
let page_index = 1;
const rawVersions: IJetBrainsRawVersion[] = [];
const bearerToken = process.env.GITHUB_TOKEN;
const bearerToken = getGitHubToken();
const requestHeaders: OutgoingHttpHeaders = {
Accept: 'application/vnd.github+json'
};
if (bearerToken) {
requestHeaders.Authorization = `Bearer ${bearerToken}`;
}
let releasesUrl: string | null = JETBRAINS_RELEASES_URL;
let pageCount = 0;
while (true) {
const requestArguments = `per_page=100&page=${page_index}`;
const requestHeaders: OutgoingHttpHeaders = {};
if (core.isDebug()) {
core.debug(`Gathering available versions from '${releasesUrl}'`);
}
if (bearerToken) {
requestHeaders['Authorization'] = `Bearer ${bearerToken}`;
}
const rawUrl = `https://api.github.com/repos/JetBrains/JetBrainsRuntime/releases?${requestArguments}`;
if (core.isDebug() && page_index === 1) {
// url is identical except page_index so print it once for debug
core.debug(`Gathering available versions from '${rawUrl}'`);
}
const paginationPageResult = (
await this.http.getJson<IJetBrainsRawVersion[]>(rawUrl, requestHeaders)
).result;
while (releasesUrl) {
pageCount++;
const response = await this.http.getJson<IJetBrainsRawVersion[]>(
releasesUrl,
requestHeaders
);
const paginationPageResult = response.result;
if (!paginationPageResult || paginationPageResult.length === 0) {
// break infinity loop because we have reached end of pagination
break;
}
const paginationPage: IJetBrainsRawVersion[] =
paginationPageResult.filter(version =>
rawVersions.push(
...paginationPageResult.filter(version =>
this.stable ? !version.prerelease : version.prerelease
)
);
const nextUrl = getNextPageUrlFromLinkHeader(response.headers);
if (nextUrl && !validatePaginationUrl(nextUrl, GITHUB_API_ORIGIN)) {
core.warning(
`Ignoring pagination link with unexpected origin: ${nextUrl}`
);
if (!paginationPage || paginationPage.length === 0) {
// break infinity loop because we have reached end of pagination
break;
releasesUrl = null;
} else {
releasesUrl = nextUrl;
}
rawVersions.push(...paginationPage);
page_index++;
if (pageCount >= MAX_PAGINATION_PAGES) {
if (releasesUrl) {
core.warning(
`Reached pagination safeguard limit (${MAX_PAGINATION_PAGES} pages) while listing JetBrains Runtime releases.`
);
}
break;
}
}
if (this.stable) {
+2 -2
View File
@@ -1,5 +1,4 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import semver from 'semver';
import fs from 'fs';
@@ -13,6 +12,7 @@ import {
JavaInstallerResults
} from '../base-models.js';
import {
cacheJdkDir,
extractJdkFile,
getDownloadArchiveExtension,
isVersionSatisfies,
@@ -48,7 +48,7 @@ export class KonaDistribution extends JavaBase {
const jdkDirectory = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
jdkDirectory,
this.toolcacheFolderName,
version,
+4 -3
View File
@@ -6,6 +6,7 @@ import {
} from '../base-models.js';
import semver from 'semver';
import {
cacheJdkDir,
extractJdkFile,
getDownloadArchiveExtension,
isVersionSatisfies,
@@ -13,7 +14,7 @@ import {
} from '../../util.js';
import * as core from '@actions/core';
import {ArchitectureOptions, NikVersion, OsVersions} from './models.js';
import * as tc from '@actions/tool-cache';
import {isAlpineLinux} from '../platform-types.js';
import fs from 'fs';
import path from 'path';
@@ -44,7 +45,7 @@ export class LibericaNikDistributions extends JavaBase {
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaRelease.version),
@@ -156,7 +157,7 @@ export class LibericaNikDistributions extends JavaBase {
case 'cygwin':
return 'windows';
case 'linux':
return 'linux';
return isAlpineLinux(platform) ? 'linux-musl' : 'linux';
default:
throw new Error(
`Platform '${platform}' is not supported. Supported platforms: ${supportedPlatform}`
+4 -3
View File
@@ -6,6 +6,7 @@ import {
} from '../base-models.js';
import semver from 'semver';
import {
cacheJdkDir,
extractJdkFile,
getDownloadArchiveExtension,
isVersionSatisfies,
@@ -13,7 +14,7 @@ import {
} from '../../util.js';
import * as core from '@actions/core';
import {ArchitectureOptions, LibericaVersion, OsVersions} from './models.js';
import * as tc from '@actions/tool-cache';
import {isAlpineLinux} from '../platform-types.js';
import fs from 'fs';
import path from 'path';
@@ -44,7 +45,7 @@ export class LibericaDistributions extends JavaBase {
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaRelease.version),
@@ -154,7 +155,7 @@ export class LibericaDistributions extends JavaBase {
case 'cygwin':
return 'windows';
case 'linux':
return 'linux';
return isAlpineLinux(platform) ? 'linux-musl' : 'linux';
case 'sunos':
return 'solaris';
default:
+68 -17
View File
@@ -1,4 +1,3 @@
import * as tc from '@actions/tool-cache';
import * as core from '@actions/core';
import fs from 'fs';
@@ -10,8 +9,11 @@ import {
JavaDownloadRelease,
JavaInstallerResults
} from '../base-models.js';
import {extractJdkFile} from '../../util.js';
import {cacheJdkDir, extractJdkFile} from '../../util.js';
import {MACOS_JAVA_CONTENT_POSTFIX} from '../../constants.js';
import {createReadStream} from 'fs';
import {createHash} from 'crypto';
import type {JdkCache} from '../../jdk-cache.js';
export class LocalDistribution extends JavaBase {
constructor(
@@ -27,6 +29,11 @@ export class LocalDistribution extends JavaBase {
"The 'latest' version alias is not supported for the 'jdkfile' distribution. Please specify a concrete version."
);
}
if (this.verifySignature) {
throw new Error(
`Input 'verify-signature' is not supported for distribution '${this.distribution}'.`
);
}
let foundJava = this.forceDownload ? null : this.findInToolcache();
@@ -46,24 +53,60 @@ export class LocalDistribution extends JavaBase {
throw new Error(`JDK file was not found in path '${jdkFilePath}'`);
}
core.info(`Extracting Java from '${jdkFilePath}'`);
let jdkCache: JdkCache | undefined;
if (this.cacheJdk) {
const [{getJdkVerificationIdentity}, source] = await Promise.all([
import('../../jdk-cache.js'),
hashFile(jdkFilePath)
]);
jdkCache = {
distribution: this.distribution,
packageType: this.packageType,
architecture: this.architecture,
version: this.version,
source,
verification: getJdkVerificationIdentity(false),
path: this.getJdkCachePath(this.version)
};
}
if (!this.forceDownload && jdkCache) {
const {restoreJdk} = await import('../../jdk-cache.js');
const restored = await restoreJdk(jdkCache);
const restoredPath = restored
? this.getRestoredJdkPath(this.version)
: undefined;
if (restoredPath) {
foundJava = {
version: this.version,
path: restoredPath
};
}
}
const extractedJavaPath = await extractJdkFile(jdkFilePath);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaVersion = this.version;
if (!foundJava) {
core.info(`Extracting Java from '${jdkFilePath}'`);
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaVersion),
this.architecture
);
const extractedJavaPath = await extractJdkFile(jdkFilePath);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaVersion = this.version;
foundJava = {
version: javaVersion,
path: javaPath
};
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaVersion),
this.architecture
);
foundJava = {
version: javaVersion,
path: javaPath
};
if (jdkCache) {
const {registerJdk} = await import('../../jdk-cache.js');
registerJdk(jdkCache);
}
}
}
// JDK folder may contain postfix "Contents/Home" on macOS
@@ -103,3 +146,11 @@ export class LocalDistribution extends JavaBase {
);
}
}
async function hashFile(file: string): Promise<string> {
const hash = createHash('sha256');
for await (const chunk of createReadStream(file)) {
hash.update(chunk);
}
return hash.digest('hex');
}
+5 -13
View File
@@ -5,9 +5,9 @@ import {
JavaInstallerResults
} from '../base-models.js';
import {
cacheJdkDir,
extractJdkFile,
getDownloadArchiveExtension,
getGitHubHttpHeaders,
renameWinArchive
} from '../../util.js';
import * as gpg from '../../gpg.js';
@@ -64,7 +64,7 @@ export class MicrosoftDistributions extends JavaBase {
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaRelease.version),
@@ -127,19 +127,11 @@ export class MicrosoftDistributions extends JavaBase {
}
private async getAvailableVersions(): Promise<tc.IToolRelease[] | null> {
// TODO get these dynamically!
// We will need Microsoft to add an endpoint where we can query for versions.
const owner = 'actions';
const repository = 'setup-java';
const branch = 'main';
const filePath =
'src/distributions/microsoft/microsoft-openjdk-versions.json';
let releases: tc.IToolRelease[] | null = null;
const fileUrl = `https://api.github.com/repos/${owner}/${repository}/contents/${filePath}?ref=${branch}`;
const headers = getGitHubHttpHeaders();
const fileUrl = `https://aka.ms/download-jdk/microsoft-openjdk-versions.json`;
// Avoid leaking the GitHub token to a non-GitHub host (aka.ms redirects to a CDN).
const headers = {accept: 'application/json'};
let response: TypedResponse<tc.IToolRelease[]> | null = null;
if (core.isDebug()) {
+2 -2
View File
@@ -1,5 +1,4 @@
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';
@@ -11,6 +10,7 @@ import {
JavaInstallerResults
} from '../base-models.js';
import {
cacheJdkDir,
convertVersionToSemver,
extractJdkFile,
isVersionSatisfies,
@@ -74,7 +74,7 @@ export class OpenJdkDistribution extends JavaBase {
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaRelease.version),
+20 -5
View File
@@ -1,5 +1,4 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
@@ -11,8 +10,11 @@ import {
JavaInstallerResults
} from '../base-models.js';
import {
cacheJdkDir,
extractJdkFile,
getArtifactFingerprint,
getDownloadArchiveExtension,
getJavaVersionFromReleaseFile,
getLatestMajorVersion,
renameWinArchive
} from '../../util.js';
@@ -43,16 +45,23 @@ export class OracleDistribution extends JavaBase {
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const installedVersion = javaRelease.floating
? getJavaVersionFromReleaseFile(archivePath)
: javaRelease.version;
const version = this.getToolcacheVersionName(installedVersion);
const javaPath = await tc.cacheDir(
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
version,
this.architecture
);
return {version: javaRelease.version, path: javaPath};
return {version: installedVersion, path: javaPath};
}
protected requiresRemoteResolution(): boolean {
return this.stable && !this.version.includes('.');
}
protected async findPackageForDownload(
@@ -99,6 +108,7 @@ export class OracleDistribution extends JavaBase {
`${ORACLE_DL_BASE}/${major}/latest/jdk-${major}_${platform}-${arch}_bin.${extension}`
);
}
const floatingUrl = isOnlyMajorProvided ? possibleUrls[0] : undefined;
possibleUrls.push(
`${ORACLE_DL_BASE}/${major}/archive/jdk-${range}_${platform}-${arch}_bin.${extension}`
@@ -112,10 +122,15 @@ export class OracleDistribution extends JavaBase {
const response = await this.http.head(url);
if (response.message.statusCode === HttpCodes.OK) {
const floating = url === floatingUrl;
return {
url,
version: range,
checksum: await this.fetchChecksum(`${url}.sha256`, 'sha256')
checksum: await this.fetchChecksum(`${url}.sha256`, 'sha256'),
floating,
fingerprint: floating
? getArtifactFingerprint(response.message.headers)
: undefined
};
}
+4 -2
View File
@@ -17,7 +17,8 @@ export enum JavaDistribution {
GraalVMCommunity = 'graalvm-community',
JetBrains = 'jetbrains',
Kona = 'kona',
OracleOpenJdk = 'oracle-openjdk'
OracleOpenJdk = 'oracle-openjdk',
RedHat = 'redhat'
}
export const JAVA_PACKAGE_CAPABILITIES = {
@@ -50,7 +51,8 @@ export const JAVA_PACKAGE_CAPABILITIES = {
'jre+ft'
],
[JavaDistribution.Kona]: ['jdk'],
[JavaDistribution.OracleOpenJdk]: ['jdk']
[JavaDistribution.OracleOpenJdk]: ['jdk'],
[JavaDistribution.RedHat]: ['jdk', 'jre']
} as const satisfies Record<JavaDistribution, readonly string[]>;
export function validateJavaPackage(
+36
View File
@@ -1,3 +1,4 @@
import fs from 'fs';
import semver from 'semver';
import {JavaDistribution} from './package-types.js';
@@ -144,6 +145,19 @@ export const JAVA_PLATFORM_CAPABILITIES: Record<
macos: X64_ARM64,
windows: ['x64']
}
},
[JavaDistribution.RedHat]: {
platforms: {
linux: [
'x64',
{architecture: 'aarch64', versionRange: '<12'},
{architecture: 'ppc64le', versionRange: '<12'}
],
windows: [
{architecture: 'x64', versionRange: '<22'},
{architecture: 'x86', versionRange: '<11'}
]
}
}
};
@@ -191,6 +205,28 @@ export function normalizePlatform(
return PLATFORM_ALIASES[platform];
}
export function isAlpineLinux(
platform: NodeJS.Platform = process.platform,
alpineReleaseExists?: boolean
): boolean {
return (
platform === 'linux' &&
(alpineReleaseExists ?? fs.existsSync('/etc/alpine-release'))
);
}
export function getJavaPlatformIdentity(
platform: NodeJS.Platform = process.platform,
alpineReleaseExists?: boolean
): string {
if (platform === 'linux') {
return isAlpineLinux(platform, alpineReleaseExists)
? 'linux-musl'
: 'linux-glibc';
}
return normalizePlatform(platform) ?? platform;
}
export function validateJavaPlatform(
distributionName: string,
platform: NodeJS.Platform,
+180
View File
@@ -0,0 +1,180 @@
import * as core from '@actions/core';
import fs from 'fs';
import path from 'path';
import semver from 'semver';
import {
cacheJdkDir,
extractJdkFile,
isVersionSatisfies,
renameWinArchive
} from '../../util.js';
import {JavaBase} from '../base-installer.js';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models.js';
import {
IDiscoPackage,
IDiscoPackageDetailsResponse,
IDiscoPackageListResponse
} from './models.js';
import {isAlpineLinux} from '../platform-types.js';
const DISCO_API_URL = 'https://api.foojay.io/disco/v3.0';
export class RedHatDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('RedHat', installerOptions);
}
protected async findPackageForDownload(
range: string
): Promise<JavaDownloadRelease> {
if (!this.stable) {
throw new Error('Early access versions are not supported');
}
const availablePackages = await this.getAvailablePackages();
const normalizedPackages = availablePackages
.map(item => ({
item,
version: this.normalizeDiscoVersion(item.java_version)
}))
.filter(
(item): item is {item: IDiscoPackage; version: string} =>
item.version !== null
)
.sort((left, right) => -semver.compareBuild(left.version, right.version));
const selectedPackage = normalizedPackages.find(item =>
isVersionSatisfies(range, item.version)
);
if (!selectedPackage) {
throw this.createVersionNotFoundError(
range,
normalizedPackages.map(item => item.version),
`Operating system: ${this.getOperatingSystem()}`
);
}
const detailsUrl = `${DISCO_API_URL}/ids/${selectedPackage.item.id}`;
const response =
await this.http.getJson<IDiscoPackageDetailsResponse>(detailsUrl);
const details = response.result?.result?.[0];
if (!details?.direct_download_uri) {
throw new Error(
`Foojay Disco returned no direct Red Hat download URL for package '${selectedPackage.item.id}'.`
);
}
const checksum = details.checksum?.trim();
if (details.checksum_type?.toLowerCase() !== 'sha256' || !checksum) {
throw new Error(
`Foojay Disco returned no SHA-256 checksum for Red Hat package '${selectedPackage.item.id}'.`
);
}
return {
version: selectedPackage.version,
url: details.direct_download_uri,
checksum: {
algorithm: 'sha256',
value: checksum,
source: detailsUrl
}
};
}
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
core.info('Extracting Java archive...');
const archiveType = this.getArchiveType();
if (archiveType === 'zip') {
javaArchivePath = renameWinArchive(javaArchivePath);
}
const extractedJavaPath = await extractJdkFile(
javaArchivePath,
archiveType
);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
if (!archiveName) {
throw new Error(
`The Red Hat archive for Java ${javaRelease.version} was empty.`
);
}
const archivePath = path.join(extractedJavaPath, archiveName);
const javaPath = await cacheJdkDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaRelease.version),
this.architecture
);
return {version: javaRelease.version, path: javaPath};
}
private async getAvailablePackages(): Promise<IDiscoPackage[]> {
const operatingSystem = this.getOperatingSystem();
const archiveType = this.getArchiveType();
const query = new URLSearchParams({
distro: 'redhat',
release_status: 'ga',
operating_system: operatingSystem,
architecture: this.distributionArchitecture(),
package_type: this.packageType,
archive_type: archiveType,
directly_downloadable: 'true'
});
const url = `${DISCO_API_URL}/packages?${query.toString()}`;
const response = await this.http.getJson<IDiscoPackageListResponse>(url);
const packages = response.result?.result;
if (!Array.isArray(packages)) {
throw new Error(
`Could not fetch Red Hat package metadata from Foojay Disco: ${url}`
);
}
return packages.filter(
item =>
item.distribution === 'redhat' &&
item.release_status === 'ga' &&
item.operating_system === operatingSystem &&
item.architecture === this.distributionArchitecture() &&
item.package_type === this.packageType &&
item.archive_type === archiveType &&
item.directly_downloadable
);
}
private getOperatingSystem(alpine = isAlpineLinux()): string {
if (alpine) {
throw new Error(
"Distribution 'redhat' does not support Alpine Linux because Red Hat portable archives require glibc."
);
}
return process.platform === 'win32' ? 'windows' : 'linux';
}
private getArchiveType(): string {
return process.platform === 'win32' ? 'zip' : 'tar.xz';
}
private normalizeDiscoVersion(version: string): string | null {
let normalizedVersion = version.trim();
if (/^\d+\+\d+$/.test(normalizedVersion)) {
normalizedVersion = normalizedVersion.replace('+', '.0.0+');
} else if (/^\d+$/.test(normalizedVersion)) {
normalizedVersion = `${normalizedVersion}.0.0`;
} else if (/^\d+\.\d+$/.test(normalizedVersion)) {
normalizedVersion = `${normalizedVersion}.0`;
}
return semver.valid(normalizedVersion) ? normalizedVersion : null;
}
}
+28
View File
@@ -0,0 +1,28 @@
export interface IDiscoPackage {
id: string;
archive_type: string;
distribution: string;
java_version: string;
release_status: string;
operating_system: string;
architecture: string;
package_type: string;
directly_downloadable: boolean;
}
export interface IDiscoPackageListResponse {
result: IDiscoPackage[];
message: string;
}
export interface IDiscoPackageDetails {
filename: string;
direct_download_uri: string;
checksum: string;
checksum_type: string;
}
export interface IDiscoPackageDetailsResponse {
result: IDiscoPackageDetails[];
message: string;
}

Some files were not shown because too many files have changed in this diff Show More