Compare commits

..

36 Commits

Author SHA1 Message Date
Julien Dubois 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
Bruno Borges 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
Julien Dubois 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
Julien Dubois 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
Bruno Borges 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
Julien Dubois 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
Julien Dubois 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
Bruno Borges 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
Bruno Borges 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
Bruno Borges 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
Bruno Borges 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
Bruno Borges 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
Bruno Borges 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] 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
Bruno Borges 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 Borges 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 Borges 60b1ab8234 Update setup-java README action from v6 to v5 (#1199) 2026-08-04 17:06:55 -04:00
Bruno Borges 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 Borges 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
dependabot[bot] d72315472c chore(deps): bump actions/upload-artifact from 6 to 7 (#1190)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-03 10:43:11 -04:00
Copilot 536de9e5ba Remove legacy Adopt distributions in v6 (#1185)
* Initial plan

* Remove legacy Adopt distributions

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

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Bruno Borges <brborges@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-07-31 15:48:18 -04:00
Bruno Borges 9a8c300417 Fix macOS e2e workflow assertions (#1184)
Normalize ARM64 runner architecture when checking exported JAVA_HOME variables and skip the unsupported adopt-openj9 macOS arm64 version-file matrix entry.

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

Copilot-Session: e78541cb-82b7-4fc2-8ffc-b1e5799efbce
2026-07-30 15:57:15 -04:00
Bruno Borges 5827477733 Optimize Maven configuration warm path (#1182)
* Optimize Maven configuration warm path

Avoid eager Maven XML initialization on warm JDK runs by using deterministic serializers for new Maven settings/toolchains files, lazy-loading xmlbuilder2 for existing toolchains merges, and deferring Maven configuration modules until after Java setup.

Add targeted tests for XML escaping, lazy xmlbuilder2 loading, concurrent Maven configuration, and a manual benchmark workflow for warm-path validation.

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

Copilot-Session: 4dc58426-5e20-44cb-af16-8da0965fac3b

* Address Maven optimization PR feedback

Make the toolchain XML generator consistently async, remove redundant Maven configuration await handling, and reuse the existing XML test helper.

Configure CodeQL to skip generated dist output so newly split vendored chunks do not report duplicate generated-code alerts.

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

Copilot-Session: 4dc58426-5e20-44cb-af16-8da0965fac3b

* Apply rubber duck review suggestions

Document XML attribute escaping, simplify Maven configuration awaiting, and add a regression test that feeds fast-path toolchains output into the merge path.

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

Copilot-Session: 4dc58426-5e20-44cb-af16-8da0965fac3b

* Delete .github/codeql/codeql-config.yml

* Update codeql-analysis.yml

* Replace xmlbuilder2 in Maven toolchain merge

Use fast-xml-parser for existing toolchains.xml parsing and serialize merged Maven toolchains deterministically. This removes the bundled xmlbuilder2 DOM/XML builder chunk from dist while preserving merge behavior for custom attributes, custom toolchains, partial entries, duplicate filtering, and escaping.

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

Copilot-Session: 4dc58426-5e20-44cb-af16-8da0965fac3b

* Move Maven benchmark out of setup-java

Remove the Maven warm-path benchmark workflow and helper script from setup-java. Benchmark coverage is being moved to actions/setup-java-benchmarks so this action repository only carries the runtime optimization, tests, and generated distribution artifacts.

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

Copilot-Session: 4dc58426-5e20-44cb-af16-8da0965fac3b

---------

Copilot-Session: 4dc58426-5e20-44cb-af16-8da0965fac3b
2026-07-30 15:09:35 -04:00
Bruno Borges 3cc3643700 Optimize Temurin tool-cache fast path with lazy loading (#1179)
* Optimize Temurin tool-cache fast path

- Lazy-load distribution installers so only the selected distro module is initialized
- Defer cache feature/cache module loading until cache input is provided
- Start cache restore early and await it safely alongside Java setup flow
- Update orchestration and lazy-loading tests; regenerate dist artifacts

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc2c0256-c55e-4a35-a584-5bed7e8b11ad

* Address PR review comments

- Lazy-load cache save in cleanup path so no-cache runs avoid cache module init in post action
- Stage dist/setup/package.json in release script for chunked setup bundle completeness

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc2c0256-c55e-4a35-a584-5bed7e8b11ad

* Fix CodeQL comment tag filter finding

Patch is-unsafe's XML comment-close detector during builds so generated bundles recognize both HTML comment end forms and satisfy CodeQL until the dependency publishes a fix.

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

Copilot-Session: 277302b1-aa95-4012-817b-9752cdaee14e

* Rebuild generated dist bundles

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc2c0256-c55e-4a35-a584-5bed7e8b11ad

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc2c0256-c55e-4a35-a584-5bed7e8b11ad
Copilot-Session: 277302b1-aa95-4012-817b-9752cdaee14e
2026-07-29 17:53:33 -04:00
Bruno Borges 6937f5eb31 Centralize OS/architecture capability validation (#1178)
* Centralize platform capability validation

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 10e35b75-928f-4ef7-984e-605895c5d88e

* Address PR review feedback

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 10e35b75-928f-4ef7-984e-605895c5d88e

* Regenerate dist after platform validation updates

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

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 10e35b75-928f-4ef7-984e-605895c5d88e
2026-07-29 15:46:29 -04:00
Bruno Borges 0b56831a10 Add dependency cache path overrides (#1175)
* Add dependency cache path overrides

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

Copilot-Session: dd650d36-9c97-4ca4-9ec8-39b37f99a07c

* Clarify supported dependency cache managers

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

Copilot-Session: dd650d36-9c97-4ca4-9ec8-39b37f99a07c

* Fix custom cache path CI checks

Align the custom cache save and restore key inputs and use the workflow hash to avoid a previously populated cache entry. Rebuild the distribution bundles.

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

Copilot-Session: dd650d36-9c97-4ca4-9ec8-39b37f99a07c

---------

Copilot-Session: dd650d36-9c97-4ca4-9ec8-39b37f99a07c
2026-07-29 14:43:55 -04:00
Bruno Borges 9f43141311 Restore dependency and wrapper caches concurrently (#1174)
* Restore dependency and wrapper caches concurrently

Run primary dependency and wrapper cache restores in parallel while preserving existing outputs and save semantics.

Add unit and E2E coverage for concurrent restore behavior, wrapper cache validation, and additional-cache error handling.

Include a manual benchmark workflow for baseline-vs-candidate restore timing comparisons across OSes.

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

Copilot-Session: d43ec3dd-96c7-4eb3-909e-b8123cd12d3c

* Address PR review comments

Use env variables for cache-hit values in benchmark record steps to avoid expression expansion in run commands, and rename E2E restore step labels for clarity.

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

Copilot-Session: d43ec3dd-96c7-4eb3-909e-b8123cd12d3c

* Stabilize wrapper cache restore checks

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

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: d43ec3dd-96c7-4eb3-909e-b8123cd12d3c
2026-07-29 13:41:24 -04:00
Bruno Borges ec4dbbe20d Test Temurin 25 on hosted runners (#1172)
* Test Temurin 25 on hosted runners

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

Copilot-Session: 9def8ac6-e148-4a8e-bb50-a3ee1948fc52

* Recommend Temurin for hosted runners

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

Copilot-Session: 9def8ac6-e148-4a8e-bb50-a3ee1948fc52

* Clarify hosted Temurin guidance

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

Copilot-Session: 9def8ac6-e148-4a8e-bb50-a3ee1948fc52

* Test downloaded Microsoft JDKs

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

Copilot-Session: 9def8ac6-e148-4a8e-bb50-a3ee1948fc52

---------

Copilot-Session: 9def8ac6-e148-4a8e-bb50-a3ee1948fc52
2026-07-29 10:41:44 -04:00
Bruno Borges 62f345fa33 Add read-only dependency cache mode (#1169)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: b3f6f152-8ac4-4c29-b04a-acac8e100777
2026-07-29 10:20:14 -04:00
Bruno Borges bcd3ba3d32 Reduce change-time Java E2E matrix (#1170)
Run a representative smoke matrix on pull requests and main while reserving the exhaustive compatibility matrix for scheduled, manual, and release-branch runs.

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

Copilot-Session: 235c81b4-58ae-494e-9907-e19c841c6a53
2026-07-29 10:17:23 -04:00
Bruno Borges 27f2c62824 Verify JDK downloads with vendor checksums (#1167)
* Verify JDK downloads with vendor checksums

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

Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

* Handle missing vendor checksum values

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

Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

* Preserve checksum error during cleanup failure

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

Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

* Validate checksum metadata value types

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

Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

* Clarify checksum documentation

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

Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

* Expand vendor checksum verification

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

Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

* Accept SHA-256 or SHA-512 for JetBrains checksum sibling

JetBrains publishes a single, generically-named ".checksum" sibling
whose digest algorithm isn't disclosed by the filename. Older JBR 11
builds (e.g. jbrsdk_nomod-11_0_16-*-b2043.64.tar.gz) publish a SHA-256
digest there, while newer builds publish SHA-512. The JetBrains
installer previously assumed SHA-512 unconditionally, so verification
failed with "Malformed sha512 checksum metadata ... expected a
128-character hexadecimal digest" for those older builds, breaking the
jetbrains 11 e2e job on macOS and Windows.

fetchChecksum now accepts a list of candidate algorithms and infers
the actual algorithm from the returned digest's length, preferring the
strongest match. The JetBrains installer passes ['sha512', 'sha256'];
all other callers are unaffected since they already pass a single,
vendor-disclosed algorithm.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

* Use SapMachine archive checksum files

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

Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: a800a031-600e-4d28-b23e-be309555d38d
2026-07-29 04:43:56 -04:00
Bruno Borges 19c23b379e Harden java-package validation (#1165)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 10b8fe1e-18f4-42cb-8672-11215715a713
2026-07-29 00:50:01 -04:00
Bruno Borges 6e26972896 Add setup orchestration tests (#1163)
Make the setup entrypoint import-safe and cover its validation, installation sequencing, post-install collaborators, caching, and failure handling directly.

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

Copilot-Session: a5ba8975-a9ac-4d2c-b41d-97c99689d1bd
2026-07-29 00:36:12 -04:00
Bruno Borges 5894ef6b27 Consolidate JDK metadata retry handling (#1162)
* Consolidate JDK metadata retries

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

Copilot-Session: a5e2549a-0d89-4c8f-b7f3-411ad21c8a06

* Expand distribution retry coverage

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

Copilot-Session: a5e2549a-0d89-4c8f-b7f3-411ad21c8a06

---------

Copilot-Session: a5e2549a-0d89-4c8f-b7f3-411ad21c8a06
2026-07-29 00:09:37 -04:00
Bruno Borges e1ce3a3428 Fail on mismatched Maven toolchain ID counts (#1161)
* Fail on mismatched Maven toolchain IDs

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

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

* Clarify Maven toolchain ID version counts

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

---------

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

Copilot-Session: c6daa6b5-31f5-46b2-a994-b8320b50a50d
2026-07-28 22:43:39 -04:00
135 changed files with 210570 additions and 167254 deletions
@@ -0,0 +1,209 @@
name: Benchmark cache restore
on:
workflow_dispatch:
inputs:
baseline-ref:
description: Git ref containing the sequential restore implementation
required: true
default: main
type: string
candidate-ref:
description: Git ref containing the concurrent restore implementation (defaults to the dispatched ref)
required: false
type: string
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
warm-caches:
name: Warm ${{ matrix.tool }} ${{ matrix.profile }} caches (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-15-intel, windows-latest, ubuntu-latest]
tool: [maven, gradle]
profile: [small, large]
steps:
- name: Checkout benchmark workflow
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Checkout baseline
uses: actions/checkout@v7
with:
path: baseline
persist-credentials: false
ref: ${{ inputs.baseline-ref }}
- name: Checkout candidate
uses: actions/checkout@v7
with:
path: candidate
persist-credentials: false
ref: ${{ inputs.candidate-ref || github.ref }}
- name: Prepare benchmark inputs
run: bash __tests__/benchmark-cache-restore.sh prepare "${{ matrix.tool }}" "${{ matrix.profile }}"
- name: Prepare cache save
uses: ./candidate
with:
distribution: temurin
java-version: '17'
cache: ${{ matrix.tool }}
cache-dependency-path: benchmark/${{ matrix.tool == 'maven' && 'pom.xml' || 'build.gradle' }}
- name: Populate benchmark caches
run: |
bash __tests__/benchmark-cache-restore.sh reset "${{ matrix.tool }}"
bash __tests__/benchmark-cache-restore.sh populate "${{ matrix.tool }}" "${{ matrix.profile }}"
benchmark:
name: Benchmark ${{ matrix.tool }} ${{ matrix.profile }} (${{ matrix.os }})
needs: warm-caches
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-15-intel, windows-latest, ubuntu-latest]
tool: [maven, gradle]
profile: [small, large]
steps:
- name: Checkout benchmark workflow
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Checkout baseline
uses: actions/checkout@v7
with:
path: baseline
persist-credentials: false
ref: ${{ inputs.baseline-ref }}
- name: Checkout candidate
uses: actions/checkout@v7
with:
path: candidate
persist-credentials: false
ref: ${{ inputs.candidate-ref || github.ref }}
- name: Prepare benchmark inputs
run: bash __tests__/benchmark-cache-restore.sh prepare "${{ matrix.tool }}" "${{ matrix.profile }}"
- name: Reset caches for baseline iteration 1
run: bash __tests__/benchmark-cache-restore.sh reset "${{ matrix.tool }}"
- name: Start baseline iteration 1 timer
run: bash __tests__/benchmark-cache-restore.sh start "${{ matrix.tool }}"
- name: Restore with baseline iteration 1
id: baseline-1
uses: ./baseline
with:
distribution: temurin
java-version: '17'
cache: ${{ matrix.tool }}
cache-dependency-path: benchmark/${{ matrix.tool == 'maven' && 'pom.xml' || 'build.gradle' }}
cache-read-only: true
- name: Record baseline iteration 1
env:
CACHE_HIT: ${{ steps.baseline-1.outputs.cache-hit }}
run: bash __tests__/benchmark-cache-restore.sh record "${{ matrix.tool }}" "${{ matrix.os }}" "${{ matrix.profile }}" baseline 1 "$CACHE_HIT"
- name: Reset caches for candidate iteration 1
run: bash __tests__/benchmark-cache-restore.sh reset "${{ matrix.tool }}"
- name: Start candidate iteration 1 timer
run: bash __tests__/benchmark-cache-restore.sh start "${{ matrix.tool }}"
- name: Restore with candidate iteration 1
id: candidate-1
uses: ./candidate
with:
distribution: temurin
java-version: '17'
cache: ${{ matrix.tool }}
cache-dependency-path: benchmark/${{ matrix.tool == 'maven' && 'pom.xml' || 'build.gradle' }}
cache-read-only: true
- name: Record candidate iteration 1
env:
CACHE_HIT: ${{ steps.candidate-1.outputs.cache-hit }}
run: bash __tests__/benchmark-cache-restore.sh record "${{ matrix.tool }}" "${{ matrix.os }}" "${{ matrix.profile }}" candidate 1 "$CACHE_HIT"
- name: Reset caches for candidate iteration 2
run: bash __tests__/benchmark-cache-restore.sh reset "${{ matrix.tool }}"
- name: Start candidate iteration 2 timer
run: bash __tests__/benchmark-cache-restore.sh start "${{ matrix.tool }}"
- name: Restore with candidate iteration 2
id: candidate-2
uses: ./candidate
with:
distribution: temurin
java-version: '17'
cache: ${{ matrix.tool }}
cache-dependency-path: benchmark/${{ matrix.tool == 'maven' && 'pom.xml' || 'build.gradle' }}
cache-read-only: true
- name: Record candidate iteration 2
env:
CACHE_HIT: ${{ steps.candidate-2.outputs.cache-hit }}
run: bash __tests__/benchmark-cache-restore.sh record "${{ matrix.tool }}" "${{ matrix.os }}" "${{ matrix.profile }}" candidate 2 "$CACHE_HIT"
- name: Reset caches for baseline iteration 2
run: bash __tests__/benchmark-cache-restore.sh reset "${{ matrix.tool }}"
- name: Start baseline iteration 2 timer
run: bash __tests__/benchmark-cache-restore.sh start "${{ matrix.tool }}"
- name: Restore with baseline iteration 2
id: baseline-2
uses: ./baseline
with:
distribution: temurin
java-version: '17'
cache: ${{ matrix.tool }}
cache-dependency-path: benchmark/${{ matrix.tool == 'maven' && 'pom.xml' || 'build.gradle' }}
cache-read-only: true
- name: Record baseline iteration 2
env:
CACHE_HIT: ${{ steps.baseline-2.outputs.cache-hit }}
run: bash __tests__/benchmark-cache-restore.sh record "${{ matrix.tool }}" "${{ matrix.os }}" "${{ matrix.profile }}" baseline 2 "$CACHE_HIT"
- name: Reset caches for baseline iteration 3
run: bash __tests__/benchmark-cache-restore.sh reset "${{ matrix.tool }}"
- name: Start baseline iteration 3 timer
run: bash __tests__/benchmark-cache-restore.sh start "${{ matrix.tool }}"
- name: Restore with baseline iteration 3
id: baseline-3
uses: ./baseline
with:
distribution: temurin
java-version: '17'
cache: ${{ matrix.tool }}
cache-dependency-path: benchmark/${{ matrix.tool == 'maven' && 'pom.xml' || 'build.gradle' }}
cache-read-only: true
- name: Record baseline iteration 3
env:
CACHE_HIT: ${{ steps.baseline-3.outputs.cache-hit }}
run: bash __tests__/benchmark-cache-restore.sh record "${{ matrix.tool }}" "${{ matrix.os }}" "${{ matrix.profile }}" baseline 3 "$CACHE_HIT"
- name: Reset caches for candidate iteration 3
run: bash __tests__/benchmark-cache-restore.sh reset "${{ matrix.tool }}"
- name: Start candidate iteration 3 timer
run: bash __tests__/benchmark-cache-restore.sh start "${{ matrix.tool }}"
- name: Restore with candidate iteration 3
id: candidate-3
uses: ./candidate
with:
distribution: temurin
java-version: '17'
cache: ${{ matrix.tool }}
cache-dependency-path: benchmark/${{ matrix.tool == 'maven' && 'pom.xml' || 'build.gradle' }}
cache-read-only: true
- name: Record candidate iteration 3
env:
CACHE_HIT: ${{ steps.candidate-3.outputs.cache-hit }}
run: bash __tests__/benchmark-cache-restore.sh record "${{ matrix.tool }}" "${{ matrix.os }}" "${{ matrix.profile }}" candidate 3 "$CACHE_HIT"
- name: Summarize benchmark
run: bash __tests__/benchmark-cache-restore.sh summarize "${{ matrix.tool }}" "$GITHUB_STEP_SUMMARY"
- name: Upload raw timings
uses: actions/upload-artifact@v7
with:
name: cache-restore-${{ matrix.os }}-${{ matrix.tool }}-${{ matrix.profile }}
path: .benchmark-results/timings.csv
if-no-files-found: error
+88 -16
View File
@@ -34,7 +34,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '17'
cache: gradle
- name: Create files to cache
@@ -42,7 +42,10 @@ jobs:
# https://github.com/actions/cache/issues/454#issuecomment-840493935
run: |
gradle downloadDependencies --no-daemon -p __tests__/cache/gradle1
mkdir -p "$HOME/.gradle/wrapper/dists/setup-java-e2e"
echo "gradle wrapper cache" > "$HOME/.gradle/wrapper/dists/setup-java-e2e/payload"
bash __tests__/check-dir.sh "$HOME/.gradle/caches"
bash __tests__/check-dir.sh "$HOME/.gradle/wrapper/dists"
gradle-restore:
runs-on: ${{ matrix.os }}
strategy:
@@ -59,11 +62,14 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: gradle
cache-read-only: true
- name: Confirm that ~/.gradle/caches directory has been made
run: bash __tests__/check-dir.sh "$HOME/.gradle/caches"
- name: Confirm that the Gradle Wrapper cache has been restored
run: bash __tests__/check-dir.sh "$HOME/.gradle/wrapper/dists"
maven-save:
runs-on: ${{ matrix.os }}
strategy:
@@ -79,13 +85,16 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: maven
- name: Create files to cache
run: |
mvn verify -f __tests__/cache/maven/pom.xml
mkdir -p "$HOME/.m2/wrapper/dists/setup-java-e2e"
echo "maven wrapper cache" > "$HOME/.m2/wrapper/dists/setup-java-e2e/payload"
bash __tests__/check-dir.sh "$HOME/.m2/repository"
bash __tests__/check-dir.sh "$HOME/.m2/wrapper/dists"
maven-restore:
runs-on: ${{ matrix.os }}
strategy:
@@ -102,11 +111,14 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: maven
cache-read-only: true
- name: Confirm that ~/.m2/repository directory has been made
run: bash __tests__/check-dir.sh "$HOME/.m2/repository"
- name: Confirm that the Maven Wrapper cache has been restored
run: bash __tests__/check-dir.sh "$HOME/.m2/wrapper/dists"
sbt-save:
runs-on: ${{ matrix.os }}
defaults:
@@ -126,7 +138,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: sbt
- name: Setup SBT
@@ -166,9 +178,10 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: sbt
cache-read-only: true
- name: Confirm that ~/Library/Caches/Coursier directory has been made
if: matrix.os == 'macos-15-intel'
@@ -194,7 +207,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '17'
cache: gradle
cache-dependency-path: __tests__/cache/gradle1/*.gradle*
@@ -203,7 +216,10 @@ jobs:
# https://github.com/actions/cache/issues/454#issuecomment-840493935
run: |
gradle downloadDependencies --no-daemon -p __tests__/cache/gradle1
mkdir -p "$HOME/.gradle/wrapper/dists/setup-java-e2e-gradle1"
echo "gradle wrapper cache gradle1" > "$HOME/.gradle/wrapper/dists/setup-java-e2e-gradle1/payload"
bash __tests__/check-dir.sh "$HOME/.gradle/caches"
bash __tests__/check-dir.sh "$HOME/.gradle/wrapper/dists"
gradle1-restore:
runs-on: ${{ matrix.os }}
strategy:
@@ -220,12 +236,14 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: gradle
cache-dependency-path: __tests__/cache/gradle1/*.gradle*
- name: Confirm that ~/.gradle/caches directory has been made
run: bash __tests__/check-dir.sh "$HOME/.gradle/caches"
- name: Confirm that the Gradle Wrapper cache has been restored
run: bash __tests__/check-dir.sh "$HOME/.gradle/wrapper/dists"
gradle2-restore:
runs-on: ${{ matrix.os }}
strategy:
@@ -242,7 +260,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: gradle
cache-dependency-path: __tests__/cache/gradle2/*.gradle*
@@ -263,14 +281,17 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: maven
cache-dependency-path: __tests__/cache/maven/pom.xml
- name: Create files to cache
run: |
mvn verify -f __tests__/cache/maven/pom.xml
mkdir -p "$HOME/.m2/wrapper/dists/setup-java-e2e-maven1"
echo "maven wrapper cache maven1" > "$HOME/.m2/wrapper/dists/setup-java-e2e-maven1/payload"
bash __tests__/check-dir.sh "$HOME/.m2/repository"
bash __tests__/check-dir.sh "$HOME/.m2/wrapper/dists"
maven1-restore:
runs-on: ${{ matrix.os }}
strategy:
@@ -287,12 +308,14 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: maven
cache-dependency-path: __tests__/cache/maven/pom.xml
- name: Confirm that ~/.m2/repository directory has been made
run: bash __tests__/check-dir.sh "$HOME/.m2/repository"
- name: Confirm that the Maven Wrapper cache has been restored
run: bash __tests__/check-dir.sh "$HOME/.m2/wrapper/dists"
maven2-restore:
runs-on: ${{ matrix.os }}
strategy:
@@ -309,10 +332,12 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: maven
cache-dependency-path: __tests__/cache/maven2/pom.xml
cache-dependency-path: |
__tests__/cache/maven2/pom.xml
README.md
- name: Confirm that ~/.m2/repository directory has not been made
run: bash __tests__/check-dir.sh "$HOME/.m2/repository" absent
sbt1-save:
@@ -334,7 +359,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: sbt
cache-dependency-path: __tests__/cache/sbt/*.sbt
@@ -375,7 +400,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: sbt
cache-dependency-path: __tests__/cache/sbt/*.sbt
@@ -409,7 +434,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
cache: sbt
cache-dependency-path: __tests__/cache/sbt2/*.sbt
@@ -423,3 +448,50 @@ jobs:
- name: Confirm that ~/.cache/coursier directory has not been made
if: matrix.os == 'ubuntu-22.04'
run: bash "$GITHUB_WORKSPACE/__tests__/check-dir.sh" "$HOME/.cache/coursier" absent
custom-maven-path-save:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Run setup-java with a custom Maven cache path
uses: ./
with:
distribution: 'temurin'
java-version: '11'
cache: maven
cache-dependency-path: |
__tests__/cache/maven2/pom.xml
.github/workflows/e2e-cache.yml
cache-path: |
${{ runner.temp }}/setup-java-custom-maven-repository
!${{ runner.temp }}/setup-java-custom-maven-repository/**/*.lastUpdated
- name: Populate the custom Maven repository
run: |
mvn -Dmaven.repo.local="$RUNNER_TEMP/setup-java-custom-maven-repository" verify -f __tests__/cache/maven2/pom.xml
touch "$RUNNER_TEMP/setup-java-custom-maven-repository/setup-java-cache-path-marker"
bash __tests__/check-dir.sh "$RUNNER_TEMP/setup-java-custom-maven-repository"
custom-maven-path-restore:
runs-on: ubuntu-latest
needs: custom-maven-path-save
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Run setup-java with a custom Maven cache path
uses: ./
with:
distribution: 'temurin'
java-version: '11'
cache: maven
cache-dependency-path: |
__tests__/cache/maven2/pom.xml
.github/workflows/e2e-cache.yml
cache-path: |
${{ runner.temp }}/setup-java-custom-maven-repository
!${{ runner.temp }}/setup-java-custom-maven-repository/**/*.lastUpdated
cache-read-only: true
- name: Confirm that the custom Maven repository has been restored
run: test -f "$RUNNER_TEMP/setup-java-custom-maven-repository/setup-java-cache-path-marker"
-41
View File
@@ -15,47 +15,6 @@ permissions:
contents: read
jobs:
setup-java-local-file-adopt:
name: Validate installation from local file Adopt
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Download Adopt OpenJDK file
run: |
if ($IsLinux) {
$downloadUrl = "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_linux_hotspot_11.0.10_9.tar.gz"
$localFilename = "java_package.tar.gz"
} elseif ($IsMacOS) {
$downloadUrl = "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_mac_hotspot_11.0.10_9.tar.gz"
$localFilename = "java_package.tar.gz"
} elseif ($IsWindows) {
$downloadUrl = "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_windows_hotspot_11.0.10_9.zip"
$localFilename = "java_package.zip"
}
echo "LocalFilename=$localFilename" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
(New-Object System.Net.WebClient).DownloadFile($downloadUrl, "$env:RUNNER_TEMP/$localFilename")
shell: pwsh
- name: setup-java
uses: ./
id: setup-java
with:
distribution: 'jdkfile'
jdk-file: ${{ runner.temp }}/${{ env.LocalFilename }}
java-version: '11.0.0-ea'
architecture: x64
- name: Verify Java version
env:
JAVA_PATH: ${{ steps.setup-java.outputs.path }}
run: bash __tests__/verify-java.sh "11.0.10" "$JAVA_PATH"
shell: bash
setup-java-local-file-zulu:
name: Validate installation from local file Zulu
runs-on: ${{ matrix.os }}
+4 -4
View File
@@ -35,7 +35,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
server-id: maven
server-username-env-var: MAVEN_USERNAME
@@ -90,7 +90,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
server-id: maven
server-username-env-var: MAVEN_USERNAME
@@ -128,7 +128,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
server-id: maven
server-username-env-var: MAVEN_USERNAME
@@ -161,7 +161,7 @@ jobs:
uses: ./
id: setup-java
with:
distribution: 'adopt'
distribution: 'temurin'
java-version: '11'
server-id: maven
server-username-env-var: MAVEN_USERNAME
+87
View File
@@ -0,0 +1,87 @@
name: Validate Java e2e smoke
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
permissions:
contents: read
jobs:
setup-java:
name: ${{ matrix.distribution }} ${{ matrix.version }} (${{ matrix.java-package }}) - ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: macos-latest
distribution: temurin
version: '11'
java-package: jdk
- os: windows-latest
distribution: temurin
version: '17'
java-package: jdk
- os: ubuntu-latest
distribution: temurin
version: '21'
java-package: jdk
- os: macos-latest
distribution: temurin
version: '25'
java-package: jdk
- os: windows-latest
distribution: temurin
version: '25'
java-package: jdk
- os: ubuntu-latest
distribution: temurin
version: '25'
java-package: jdk
- os: macos-latest
distribution: microsoft
version: '25'
java-package: jdk
- os: windows-latest
distribution: microsoft
version: '25'
java-package: jdk
- os: ubuntu-latest
distribution: microsoft
version: '25'
java-package: jdk
- os: ubuntu-latest
distribution: zulu
version: '17'
java-package: jre
- os: ubuntu-latest
distribution: liberica
version: '21'
java-package: jdk+fx
steps:
- name: Checkout
uses: actions/checkout@v7
with:
persist-credentials: false
- name: setup-java
uses: ./
id: setup-java
with:
java-version: ${{ matrix.version }}
java-package: ${{ matrix.java-package }}
distribution: ${{ matrix.distribution }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Verify Java
env:
JAVA_VERSION: ${{ matrix.version }}
JAVA_PATH: ${{ steps.setup-java.outputs.path }}
run: bash __tests__/verify-java.sh "$JAVA_VERSION" "$JAVA_PATH"
shell: bash
+58 -12
View File
@@ -3,13 +3,9 @@ name: Validate Java e2e
on:
push:
branches:
- main
- releases/*
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
schedule:
- cron: '0 */12 * * *'
workflow_dispatch:
@@ -25,10 +21,9 @@ jobs:
fail-fast: false
matrix:
os: [macos-15-intel, windows-latest, ubuntu-latest]
distribution: [
distribution:
[
'temurin',
'adopt',
'adopt-openj9',
'zulu',
'liberica',
'microsoft',
@@ -39,7 +34,7 @@ jobs:
'jetbrains',
'kona',
'liberica-nik'
] # internally 'adopt-hotspot' is the same as 'adopt'
]
version: ['21', '11', '17']
exclude:
- distribution: microsoft
@@ -83,6 +78,15 @@ jobs:
- distribution: oracle
os: ubuntu-latest
version: 21
- distribution: oracle-openjdk
os: macos-15-intel
version: 21
- distribution: oracle-openjdk
os: windows-latest
version: 21
- distribution: oracle-openjdk
os: ubuntu-latest
version: 21
- distribution: graalvm
os: macos-latest
version: 17.0.12
@@ -113,6 +117,27 @@ jobs:
env:
JAVA_VERSION: ${{ matrix.version }}
JAVA_PATH: ${{ steps.setup-java.outputs.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:
name: Corretto checksum verification - ubuntu-latest
runs-on: ubuntu-latest
steps:
- *checkout_step
- name: setup-java with forced download
uses: ./
id: setup-java
with:
java-version: '21'
distribution: corretto
force-download: true
- name: Verify Java
env:
JAVA_VERSION: '21'
JAVA_PATH: ${{ steps.setup-java.outputs.path }}
run: bash __tests__/verify-java.sh "$JAVA_VERSION" "$JAVA_PATH"
shell: bash
@@ -266,10 +291,11 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Verify Java env variables
run: |
$javaArch = if ($env:RUNNER_ARCH -eq "ARM64") { "AARCH64" } else { $env:RUNNER_ARCH }
$versionsArr = "11","17"
foreach ($version in $versionsArr)
{
$envName = "JAVA_HOME_${version}_${env:RUNNER_ARCH}"
$envName = "JAVA_HOME_${version}_${javaArch}"
$JavaVersionPath = [Environment]::GetEnvironmentVariable($envName)
if (-not (Test-Path "$JavaVersionPath")) {
Write-Host "$envName is not found"
@@ -471,6 +497,25 @@ jobs:
run: bash __tests__/verify-java.sh "$JAVA_VERSION" "$JAVA_PATH"
shell: bash
setup-java-unsupported-platform:
name: Reject unsupported Oracle x86 on Linux
runs-on: ubuntu-latest
steps:
- *checkout_step
- name: Attempt unsupported setup
id: unsupported-setup
continue-on-error: true
uses: ./
with:
distribution: oracle
java-version: '21'
architecture: x86
- name: Verify setup was rejected
if: always()
env:
SETUP_OUTCOME: ${{ steps.unsupported-setup.outcome }}
run: test "$SETUP_OUTCOME" = failure
setup-java-version-both-version-inputs-presents:
name: ${{ matrix.distribution }} version (should be from input) - ${{ matrix.os }}
runs-on: ${{ matrix.os }}
@@ -537,7 +582,7 @@ jobs:
fail-fast: false
matrix:
os: *default_os
distribution: ['adopt', 'adopt-openj9', 'zulu']
distribution: ['temurin', 'zulu']
java-version-file: ['.java-version', '.tool-versions']
steps:
- *checkout_step
@@ -566,7 +611,7 @@ jobs:
fail-fast: false
matrix:
os: *default_os
distribution: ['adopt', 'zulu', 'liberica']
distribution: ['temurin', 'zulu', 'liberica']
java-version-file: ['.java-version', '.tool-versions', '.sdkmanrc']
steps:
- *checkout_step
@@ -640,7 +685,8 @@ jobs:
shell: bash
- name: Verify JAVA_HOME_21 env var is set
run: |
$envName = "JAVA_HOME_21_${env:RUNNER_ARCH}"
$javaArch = if ($env:RUNNER_ARCH -eq "ARM64") { "AARCH64" } else { $env:RUNNER_ARCH }
$envName = "JAVA_HOME_21_${javaArch}"
$JavaVersionPath = [Environment]::GetEnvironmentVariable($envName)
if (-not $JavaVersionPath) {
Write-Host "$envName is not set"
-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: []
+415 -260
View File
@@ -4,347 +4,471 @@
[![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.
## Breaking changes in V5
## What's new
- 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)
### V6 (in development)
For more details, see the full release notes on the [releases page](https://github.com/actions/setup-java/releases/tag/v5.0.0)
- 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`.
### 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: `jdk`, `jre`, `jdk+fx`, `jre+fx`. For Azul Zulu, `jdk+crac` and `jre+crac` are also supported. For Eclipse Temurin 24 and later, `jdk+jmods` includes the separately packaged JMOD files. Default value: `jdk`.
- `architecture`: The target architecture of the package. Possible values: `x86`, `x64`, `armv7`, `aarch64`, `ppc64le`. Default value: Derived from the runner machine.
- `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.
#### 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.
- `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.
### 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
### Read the version from a file
> [!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/) |
| `adopt` or `adopt-hotspot` | [AdoptOpenJDK Hotspot](https://adoptopenjdk.net/) | [`adopt-hotspot` license](https://adoptopenjdk.net/about.html) |
| `adopt-openj9` | [AdoptOpenJDK OpenJ9](https://adoptopenjdk.net/) | [`adopt-openj9` license](https://adoptopenjdk.net/about.html) |
| `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.
> - AdoptOpenJDK got moved to Eclipse Temurin and won't be updated anymore. It is highly recommended to migrate workflows from `adopt` and `adopt-openj9`, to `temurin` and `semeru` respectively, to keep receiving software and security updates. See more details in the [Good-bye AdoptOpenJDK post](https://blog.adoptopenjdk.net/2021/08/goodbye-adoptopenjdk-hello-adoptium/).
> - Oracle OpenJDK builds are created and hosted by Oracle. After a limited number of releases, Oracle archives these builds and no longer provides security updates. To continue receiving security patches, users must move to Oracle JDK or choose a different vendor.
> - For Azul Zulu OpenJDK, architecture `arm64` is mapped to `aarch64` when querying the Azul Metadata API.
> - To comply with the GraalVM Free Terms and Conditions (GFTC) license, it is recommended to use GraalVM JDK 17 version 17.0.12, as this is the only version of GraalVM JDK 17 available under the GFTC license. Additionally, it is encouraged to consider upgrading to GraalVM JDK 21, which offers the latest features and improvements.
> - GraalVM Community is available as `distribution: 'graalvm-community'` for stable JDK 17 and later releases published on GitHub.
**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.
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).
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).
The cache input is optional, and caching is turned off by default.
**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.
#### Caching gradle dependencies
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
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
distribution: temurin
java-version-file: .java-version
- run: java --version
```
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.
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`.
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).
### Use the newest stable Java
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
- uses: actions/setup-java@v5
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
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` |
| `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) |
| `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]
> 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.
> 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.
#### Caching sbt dependencies
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
- uses: actions/setup-java@v5
with:
distribution: 'temurin'
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: maven
- run: mvn verify
```
#### 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.
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-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
java-version: '25'
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` changes what is restored and saved, but not the cache key. Jobs that should share a cache key must use the same OS, architecture, package manager, dependency files, and cache paths.
### Wrapper caches
Maven and Gradle wrapper distributions are restored and saved as additional cache entries, separate from the primary dependency cache. These entries have their own keys in the form `setup-java-<runner-os>-<node-arch>-<wrapper-cache-name>-<file-hash>`.
| Package manager | Wrapper cache name | Cached path | Files used for wrapper-cache key |
| --- | --- | --- | --- |
| Maven | `maven-wrapper` | `~/.m2/wrapper/dists` | `**/.mvn/wrapper/maven-wrapper.properties` |
| Gradle | `gradle-wrapper` | `~/.gradle/wrapper` | `**/gradle-wrapper.properties` |
These wrapper caches are independent from dependency caches, so they remain useful even when dependency files change frequently. The wrapper properties are also part of the Maven and Gradle primary dependency-cache key because wrapper changes can affect how dependencies are resolved, but the wrapper distribution files themselves are stored in the separate wrapper cache entries above.
For advanced Gradle caching features such as build output caching, configuration cache support, encrypted cache storage, cleanup, and fine-grained cache control, consider [`gradle/actions/setup-gradle`](https://github.com/gradle/actions/tree/main/setup-gradle).
### Caching JDK installations
The JDK cache stores the downloaded JDK installation so later runs skip the download. It is enabled implicitly whenever dependency `cache` is set, so most workflows that cache dependencies are already caching the JDK. Set `cache-jdk: true` to enable it without dependency caching, or `cache-jdk: false` to opt out while keeping dependency caching. With neither `cache` nor `cache-jdk` set, nothing is cached.
> [!IMPORTANT]
> Because JDK caching is on by default whenever `cache` is set, review [Caching JDK installations](docs/advanced-usage.md#caching-jdk-installations)
> for the full `cache`/`cache-jdk` matrix, cache identity and storage impact.
### Read-only caches
Set `cache-read-only: true` to restore dependency, wrapper, and JDK caches without saving changes in the post action. This is useful for pull requests, merge queues, short-lived branches, and matrix fan-out jobs that should only consume caches produced elsewhere.
```yaml
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '25'
cache: maven
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
```
For matrix fan-out, seed the cache once and make matrix jobs read-only consumers:
```yaml
jobs:
seed-cache:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '25'
cache: maven
- run: mvn dependency:go-offline dependency:resolve-plugins
build:
needs: seed-cache
runs-on: ubuntu-latest
strategy:
matrix:
goal: [test, verify, package]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: '25'
cache: maven
cache-read-only: true
- run: mvn ${{ matrix.goal }}
```
### Cache segment restore timeout
Cache downloads are split into segments. To reduce the chance of a stuck segment blocking a workflow, set `SEGMENT_DOWNLOAD_TIMEOUT_MINS`:
```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
```
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.
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`.
`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
```
### 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
@@ -355,10 +479,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)
+100 -1
View File
@@ -13,6 +13,7 @@ import * as io from '@actions/io';
import * as fs from 'fs';
import * as path from 'path';
import os from 'os';
import {XMLParser} from 'fast-xml-parser';
// Mock @actions/core before importing source modules that depend on it
jest.unstable_mockModule('@actions/core', () => ({
@@ -40,10 +41,18 @@ 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);
@@ -59,8 +68,17 @@ 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.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);
@@ -143,6 +161,52 @@ describe('auth tests', () => {
);
}, 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';
@@ -271,6 +335,41 @@ describe('auth tests', () => {
);
});
it('escapes settings.xml values while preserving parsed semantics', () => {
const id = `packages&<>"'é`;
const username = `USER&<>"'é`;
const password = `TOKEN&<>"'é`;
const gpgPassphrase = `GPG&<>"'é`;
const xml = auth.generate(id, username, password, gpgPassphrase);
const parsed = parseXmlObject(xml) as any;
expect(parsed.settings.interactiveMode).toBe('false');
expect(xmlElementText(xml, 'id')).toBe(id);
expect(xmlElementText(xml, 'username')).toBe(`\${env.${username}}`);
expect(xmlElementText(xml, 'password')).toBe(`\${env.${password}}`);
expect(xmlElementText(xml, 'gpg.passphraseEnvName')).toBe(gpgPassphrase);
expect(parsed.settings.activeProfiles.activeProfile).toBe('setup-java-gpg');
});
function xmlElementText(xml: string, tagName: string): string {
const match = new RegExp(`<${tagName}>([\\s\\S]*?)</${tagName}>`).exec(xml);
expect(match).not.toBeNull();
return (parseXmlObject(`<value>${match?.[1]}</value>`) as {value: string})
.value;
}
function parseXmlObject(xml: string): unknown {
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@',
parseAttributeValue: false,
parseTagValue: false,
trimValues: true
});
return parser.parse(xml);
}
it('uses deprecated input aliases and warns', () => {
const mockGetInput = core.getInput as jest.MockedFunction<
typeof core.getInput
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
set -euo pipefail
command=${1:?command is required}
tool=${2:?tool is required}
case "$tool" in
maven)
dependency_cache="$HOME/.m2/repository"
wrapper_cache="$HOME/.m2/wrapper/dists"
dependency_file="benchmark/pom.xml"
wrapper_file="benchmark/.mvn/wrapper/maven-wrapper.properties"
;;
gradle)
dependency_cache="$HOME/.gradle/caches"
wrapper_cache="$HOME/.gradle/wrapper"
dependency_file="benchmark/build.gradle"
wrapper_file="benchmark/gradle/wrapper/gradle-wrapper.properties"
;;
*)
echo "Unsupported tool: $tool" >&2
exit 1
;;
esac
case "$command" in
prepare)
profile=${3:?profile is required}
mkdir -p "$(dirname "$dependency_file")" "$(dirname "$wrapper_file")"
printf '// setup-java cache benchmark v1: %s\n' "$profile" > "$dependency_file"
printf '# setup-java cache benchmark v1: %s\n' "$profile" > "$wrapper_file"
;;
reset)
rm -rf "$dependency_cache" "$wrapper_cache"
;;
populate)
profile=${3:?profile is required}
case "$profile" in
small)
dependency_megabytes=8
wrapper_megabytes=2
;;
large)
dependency_megabytes=128
wrapper_megabytes=32
;;
*)
echo "Unsupported profile: $profile" >&2
exit 1
;;
esac
mkdir -p "$dependency_cache/setup-java-benchmark"
mkdir -p "$wrapper_cache/setup-java-benchmark"
dd if=/dev/urandom \
of="$dependency_cache/setup-java-benchmark/payload" \
bs=1048576 count="$dependency_megabytes" 2>/dev/null
dd if=/dev/urandom \
of="$wrapper_cache/setup-java-benchmark/payload" \
bs=1048576 count="$wrapper_megabytes" 2>/dev/null
;;
start)
node -e "require('fs').writeFileSync('.benchmark-start', String(Date.now()))"
;;
record)
os=${3:?os is required}
profile=${4:?profile is required}
implementation=${5:?implementation is required}
iteration=${6:?iteration is required}
cache_hit=${7:?cache-hit output is required}
if [ "$cache_hit" != "true" ]; then
echo "Expected an exact dependency-cache hit for $implementation" >&2
exit 1
fi
test -f "$dependency_cache/setup-java-benchmark/payload"
started=$(cat .benchmark-start)
finished=$(node -e "process.stdout.write(String(Date.now()))")
elapsed=$((finished - started))
mkdir -p .benchmark-results
printf '%s,%s,%s,%s,%s,%s\n' \
"$os" "$tool" "$profile" "$implementation" "$iteration" "$elapsed" \
>> .benchmark-results/timings.csv
;;
summarize)
summary_file=${3:?summary file is required}
results_file=".benchmark-results/timings.csv"
node --input-type=module - "$results_file" "$summary_file" <<'NODE'
import fs from 'node:fs';
const [, , resultsFile, summaryFile] = process.argv;
const rows = fs
.readFileSync(resultsFile, 'utf8')
.trim()
.split('\n')
.map(line => {
const [os, tool, profile, implementation, iteration, elapsed] =
line.split(',');
return {os, tool, profile, implementation, iteration, elapsed: +elapsed};
});
const average = implementation => {
const values = rows
.filter(row => row.implementation === implementation)
.map(row => row.elapsed);
if (values.length === 0) {
throw new Error(`No ${implementation} benchmark results were recorded`);
}
return Math.round(values.reduce((sum, value) => sum + value, 0) / values.length);
};
const baseline = average('baseline');
const candidate = average('candidate');
const change = (((candidate - baseline) / baseline) * 100).toFixed(1);
const {os, tool, profile} = rows[0];
const lines = [
`### ${tool} ${profile} cache restore on ${os}`,
'',
'| Implementation | Iteration | Wall time (ms) |',
'| --- | ---: | ---: |',
...rows.map(
row =>
`| ${row.implementation} | ${row.iteration} | ${row.elapsed} |`
),
`| **baseline average** | | **${baseline}** |`,
`| **candidate average** | | **${candidate}** |`,
'',
`Candidate change from baseline: **${change}%**`,
''
];
fs.appendFileSync(summaryFile, `${lines.join('\n')}\n`);
NODE
;;
*)
echo "Unsupported command: $command" >&2
exit 1
;;
esac
+80
View File
@@ -0,0 +1,80 @@
import {jest, describe, it, expect, afterEach} from '@jest/globals';
jest.unstable_mockModule('@actions/cache', () => ({
isFeatureAvailable: jest.fn()
}));
jest.unstable_mockModule('@actions/core', () => ({
warning: jest.fn(),
debug: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
info: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
const cache = await import('@actions/cache');
const core = await import('@actions/core');
const {isCacheFeatureAvailable} = await import('../src/cache-feature.js');
describe('isCacheFeatureAvailable', () => {
it('is disabled on GHES when cache feature is unavailable', () => {
(cache.isFeatureAvailable as jest.Mock<any>).mockImplementation(
() => false
);
const warningMock = core.warning as jest.Mock;
const message =
'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.';
try {
process.env['GITHUB_SERVER_URL'] = 'http://example.com';
expect(isCacheFeatureAvailable()).toBe(false);
expect(warningMock).toHaveBeenCalledWith(message);
} finally {
delete process.env['GITHUB_SERVER_URL'];
}
});
it('is disabled on dotcom when cache feature is unavailable', () => {
(cache.isFeatureAvailable as jest.Mock<any>).mockImplementation(
() => false
);
const warningMock = core.warning as jest.Mock;
const message =
'The runner was not able to contact the cache service. Caching will be skipped';
try {
process.env['GITHUB_SERVER_URL'] = 'http://github.com';
expect(isCacheFeatureAvailable()).toBe(false);
expect(warningMock).toHaveBeenCalledWith(message);
} finally {
delete process.env['GITHUB_SERVER_URL'];
}
});
it('is enabled when cache feature is available', () => {
(cache.isFeatureAvailable as jest.Mock<any>).mockImplementation(() => true);
expect(isCacheFeatureAvailable()).toBe(true);
});
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
});
});
+229 -4
View File
@@ -224,10 +224,10 @@ describe('dependency cache', () => {
join(workspace, '.mvn', 'wrapper', 'maven-wrapper.properties')
);
await restore('maven', '');
await restore('maven', '', ['/custom/maven/repository']);
// Main dependency cache no longer carries the wrapper dists path.
expect(spyCacheRestore).toHaveBeenCalledWith(
[join(os.homedir(), '.m2', 'repository')],
['/custom/maven/repository'],
expect.any(String)
);
expect(spyCacheRestore).toHaveBeenCalledWith(
@@ -237,6 +237,83 @@ describe('dependency cache', () => {
expect(spyGlobHashFiles).toHaveBeenCalledWith(
'**/.mvn/wrapper/maven-wrapper.properties'
);
expect(spyInfo).toHaveBeenCalledWith(
'maven-wrapper cache is not found'
);
});
it('starts maven dependency and wrapper restores before either completes', async () => {
createDirectory(join(workspace, '.mvn'));
createDirectory(join(workspace, '.mvn', 'wrapper'));
createFile(
join(workspace, '.mvn', 'wrapper', 'maven-wrapper.properties')
);
const dependencyRestore = deferred<string | undefined>();
const wrapperRestore = deferred<string | undefined>();
const bothRestoresStarted = deferred<void>();
let restoreCount = 0;
spyCacheRestore.mockImplementation((paths: string[]) => {
restoreCount++;
if (restoreCount === 2) {
bothRestoresStarted.resolve();
}
return paths.includes(join(os.homedir(), '.m2', 'repository'))
? dependencyRestore.promise
: wrapperRestore.promise;
});
const restorePromise = restore('maven', '');
await bothRestoresStarted.promise;
expect(spyCacheRestore).toHaveBeenCalledTimes(2);
expect(spySaveState).toHaveBeenCalledWith(
'cache-primary-key',
expect.any(String)
);
expect(spySaveState).toHaveBeenCalledWith(
'cache-primary-key-maven-wrapper',
expect.any(String)
);
wrapperRestore.resolve('maven-wrapper-hit');
dependencyRestore.resolve('maven-dependency-hit');
await restorePromise;
expect(spySaveState).toHaveBeenCalledWith(
'cache-matched-key-maven-wrapper',
'maven-wrapper-hit'
);
expect(spySaveState).toHaveBeenCalledWith(
'cache-matched-key',
'maven-dependency-hit'
);
expect(spySetOutput).toHaveBeenCalledWith('cache-hit', false);
});
it('propagates a wrapper restore failure after starting both restores', async () => {
createDirectory(join(workspace, '.mvn'));
createDirectory(join(workspace, '.mvn', 'wrapper'));
createFile(
join(workspace, '.mvn', 'wrapper', 'maven-wrapper.properties')
);
const dependencyRestore = deferred<string | undefined>();
const wrapperRestore = deferred<string | undefined>();
const bothRestoresStarted = deferred<void>();
let restoreCount = 0;
spyCacheRestore.mockImplementation((paths: string[]) => {
restoreCount++;
if (restoreCount === 2) {
bothRestoresStarted.resolve();
}
return paths.includes(join(os.homedir(), '.m2', 'repository'))
? dependencyRestore.promise
: wrapperRestore.promise;
});
const restorePromise = restore('maven', '');
await bothRestoresStarted.promise;
wrapperRestore.reject(new Error('wrapper restore failed'));
dependencyRestore.resolve(undefined);
await expect(restorePromise).rejects.toThrow('wrapper restore failed');
});
it('skips the maven wrapper cache when no wrapper properties exist', async () => {
createFile(join(workspace, 'pom.xml'));
@@ -317,10 +394,10 @@ describe('dependency cache', () => {
it('restores the gradle wrapper distribution cache independently of the main cache', async () => {
createFile(join(workspace, 'build.gradle'));
await restore('gradle', '');
await restore('gradle', '', ['/custom/gradle/caches']);
// Main dependency cache no longer carries the wrapper path.
expect(spyCacheRestore).toHaveBeenCalledWith(
[join(os.homedir(), '.gradle', 'caches')],
['/custom/gradle/caches'],
expect.any(String)
);
// Wrapper distribution is restored on its own, keyed only on the
@@ -333,6 +410,50 @@ describe('dependency cache', () => {
'**/gradle-wrapper.properties'
);
});
it('starts gradle dependency and wrapper restores before either completes', async () => {
createFile(join(workspace, 'build.gradle'));
createFile(join(workspace, 'gradle-wrapper.properties'));
const dependencyRestore = deferred<string | undefined>();
const wrapperRestore = deferred<string | undefined>();
const bothRestoresStarted = deferred<void>();
let restoreCount = 0;
spyCacheRestore.mockImplementation((paths: string[]) => {
restoreCount++;
if (restoreCount === 2) {
bothRestoresStarted.resolve();
}
return paths.includes(join(os.homedir(), '.gradle', 'caches'))
? dependencyRestore.promise
: wrapperRestore.promise;
});
const restorePromise = restore('gradle', '');
await bothRestoresStarted.promise;
expect(spyCacheRestore).toHaveBeenCalledTimes(2);
expect(spySaveState).toHaveBeenCalledWith(
'cache-primary-key',
expect.any(String)
);
expect(spySaveState).toHaveBeenCalledWith(
'cache-primary-key-gradle-wrapper',
expect.any(String)
);
dependencyRestore.resolve('gradle-dependency-hit');
wrapperRestore.resolve('gradle-wrapper-hit');
await restorePromise;
expect(spySaveState).toHaveBeenCalledWith(
'cache-matched-key',
'gradle-dependency-hit'
);
expect(spySaveState).toHaveBeenCalledWith(
'cache-matched-key-gradle-wrapper',
'gradle-wrapper-hit'
);
expect(spySetOutput).toHaveBeenCalledWith('cache-hit', false);
});
it('skips the gradle wrapper cache when no wrapper properties exist', async () => {
createFile(join(workspace, 'build.gradle'));
spyGlobHashFiles.mockImplementation((pattern: string) =>
@@ -455,6 +576,34 @@ describe('dependency cache', () => {
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
});
});
describe('cache-path', () => {
it.each([
['maven', ['/custom/maven/repository']],
['gradle', ['/custom/gradle/caches']],
[
'sbt',
[
'/custom/ivy/cache',
'/custom/coursier/cache',
'!/custom/ivy/cache/*.lock'
]
]
])(
'restores and persists custom paths for %s',
async (packageManager, cachePaths) => {
await restore(packageManager, '', cachePaths);
expect(spyCacheRestore).toHaveBeenCalledWith(
cachePaths,
expect.any(String)
);
expect(spySaveState).toHaveBeenCalledWith(
'cache-paths',
JSON.stringify(cachePaths)
);
}
);
});
});
describe('save', () => {
let spyCacheSave: any;
@@ -504,6 +653,42 @@ describe('dependency cache', () => {
);
});
it.each([
['maven', ['/custom/maven/repository']],
['gradle', ['/custom/gradle/caches']],
[
'sbt',
[
'/custom/ivy/cache',
'/custom/coursier/cache',
'!/custom/ivy/cache/*.lock'
]
]
])(
'saves the persisted custom paths for %s',
async (packageManager, cachePaths) => {
(core.getState as jest.Mock<any>).mockImplementation((name: any) => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-primary-key';
case 'cache-matched-key':
return 'setup-java-cache-matched-key';
case 'cache-paths':
return JSON.stringify(cachePaths);
default:
return '';
}
});
await save(packageManager);
expect(spyCacheSave).toHaveBeenCalledWith(
cachePaths,
'setup-java-cache-primary-key'
);
}
);
describe('for maven', () => {
it('uploads cache even if no pom.xml found', async () => {
createStateForMissingBuildFile();
@@ -609,6 +794,36 @@ describe('dependency cache', () => {
);
expect(spyWarning).not.toHaveBeenCalled();
});
it('continues with primary cache save when additional cache save fails unexpectedly', async () => {
createFile(join(workspace, 'pom.xml'));
(core.getState as jest.Mock<any>).mockImplementation((name: any) => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-primary-key';
case 'cache-matched-key':
return 'setup-java-cache-matched-key';
case 'cache-primary-key-maven-wrapper':
return 'setup-java-maven-wrapper-key';
default:
return '';
}
});
spyCacheSave.mockImplementation((paths: string[], key: string) => {
if (paths[0] === 'wrapper-path') {
return Promise.reject(new Error('wrapper save exploded'));
}
return Promise.resolve(0);
});
await expect(save('maven')).resolves.toBeUndefined();
expect(spyWarning).toHaveBeenCalledWith(
'Failed to save maven-wrapper cache: wrapper save exploded. Continuing with primary cache save.'
);
expect(spyCacheSave).toHaveBeenCalledWith(
[join(os.homedir(), '.m2', 'repository')],
'setup-java-cache-primary-key'
);
});
});
describe('for gradle', () => {
it('uploads cache even if no build.gradle found', async () => {
@@ -817,6 +1032,16 @@ function createFile(path: string) {
fs.writeFileSync(path, '');
}
function deferred<T>() {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((promiseResolve, promiseReject) => {
resolve = promiseResolve;
reject = promiseReject;
});
return {promise, resolve, reject};
}
function createDirectory(path: string) {
core.info(`created a directory at ${path}`);
fs.mkdirSync(path);
@@ -0,0 +1 @@
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
@@ -0,0 +1 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip
+130
View File
@@ -0,0 +1,130 @@
import {afterEach, describe, expect, it, jest} from '@jest/globals';
import {createHash} from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import {calculateChecksum, verifyChecksum} from '../src/checksum.js';
import type {ChecksumMetadata} from '../src/distributions/base-models.js';
const temporaryPaths: string[] = [];
async function temporaryFile(contents: string): Promise<string> {
const directory = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'setup-java-checksum-')
);
const file = path.join(directory, 'archive');
await fs.promises.writeFile(file, contents);
temporaryPaths.push(directory);
return file;
}
afterEach(async () => {
await Promise.all(
temporaryPaths
.splice(0)
.map(item => fs.promises.rm(item, {recursive: true, force: true}))
);
jest.restoreAllMocks();
});
describe('verifyChecksum', () => {
it.each(['sha256', 'sha512'] as const)(
'verifies a matching %s digest',
async algorithm => {
const contents = `jdk archive for ${algorithm}`;
const file = await temporaryFile(contents);
const value = createHash(algorithm).update(contents).digest('hex');
await expect(
verifyChecksum(
file,
{algorithm, value: value.toUpperCase()},
{distribution: 'Test', version: '21.0.1'}
)
).resolves.toBeUndefined();
}
);
it('reports mismatch context and both digests', async () => {
const file = await temporaryFile('corrupt archive');
const expected = 'a'.repeat(64);
const actual = await calculateChecksum(file, 'sha256');
await expect(
verifyChecksum(
file,
{algorithm: 'sha256', value: expected},
{distribution: 'Corretto', version: '21.0.8'}
)
).rejects.toThrow(
`Checksum verification failed for Corretto version 21.0.8: sha256 expected ${expected}, actual ${actual}.`
);
});
it('rejects malformed digest metadata before reading the file', async () => {
await expect(
verifyChecksum(
'/missing/archive',
{algorithm: 'sha512', value: 'not-a-digest'},
{distribution: 'Test', version: '17'}
)
).rejects.toThrow(
'Malformed sha512 checksum metadata: expected a 128-character hexadecimal digest.'
);
});
it.each([undefined, null, 123])(
'reports a malformed digest when the value is %p',
async value => {
const checksum = {
algorithm: 'sha256',
value
} as unknown as ChecksumMetadata;
await expect(
verifyChecksum('/missing/archive', checksum, {
distribution: 'Test',
version: '17'
})
).rejects.toThrow(
'Malformed sha256 checksum metadata: expected a 64-character hexadecimal digest.'
);
}
);
it('rejects unsupported algorithms without leaking source query parameters', async () => {
const checksum = {
algorithm: 'md5',
value: 'a'.repeat(32),
source: 'https://vendor.example/checksum.txt?token=secret-value#private'
} as unknown as ChecksumMetadata;
let message = '';
try {
await verifyChecksum('/missing/archive', checksum, {
distribution: 'Test',
version: '17'
});
} catch (error) {
message = (error as Error).message;
}
expect(message).toContain(
"Unsupported checksum algorithm 'md5' from https://vendor.example/checksum.txt"
);
expect(message).not.toContain('secret-value');
expect(message).not.toContain('token=');
expect(message).not.toContain('#private');
});
it('surfaces file read errors', async () => {
await expect(
verifyChecksum(
'/missing/archive',
{algorithm: 'sha256', value: 'a'.repeat(64)},
{distribution: 'Test', version: '17'}
)
).rejects.toMatchObject({code: 'ENOENT'});
});
});
+267
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'))
@@ -120,6 +185,147 @@ describe('cleanup', () => {
await cleanup();
expect(spyCacheSave).toHaveBeenCalled();
});
it.each(['maven', 'gradle', 'sbt'])(
'does not save the %s cache in read-only mode',
async packageManager => {
createStateForSuccessfulRestoreWithWrapper(packageManager);
(core.getInput as jest.Mock<any>).mockImplementation((name: string) => {
switch (name) {
case 'cache':
return packageManager;
case 'cache-read-only':
return 'true';
default:
return '';
}
});
await cleanup();
expect(spyCacheSave).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.'
);
}
);
it('saves the cache when read-only mode is explicitly disabled', async () => {
spyCacheSave.mockResolvedValue(0);
(core.getInput as jest.Mock<any>).mockImplementation((name: string) => {
switch (name) {
case 'cache':
return 'maven';
case 'cache-read-only':
return 'false';
default:
return '';
}
});
await 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() {
@@ -141,3 +347,64 @@ function createStateForSuccessfulRestore() {
}
});
}
function createStateForSuccessfulRestoreWithWrapper(packageManager: string) {
(core.getState as jest.Mock<any>).mockImplementation((name: any) => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-primary-key';
case 'cache-matched-key':
return 'setup-java-cache-matched-key';
case `cache-primary-key-${packageManager}-wrapper`:
return `setup-java-${packageManager}-wrapper-primary-key`;
default:
return '';
}
});
}
/**
* 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')
};
}
-909
View File
@@ -1,909 +0,0 @@
[
{
"binaries": [
{
"architecture": "x64",
"download_count": 74181,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "09b7e6ab5d5eb4b73813f4caa793a0b616d33794a17988fa6a6b7c972e8f3dd3",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.2%2B12/OpenJDK14U-jdk_x64_mac_hotspot_14.0.2_12.tar.gz.sha256.txt",
"download_count": 23872,
"link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.2%2B12/OpenJDK14U-jdk_x64_mac_hotspot_14.0.2_12.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.2%2B12/OpenJDK14U-jdk_x64_mac_hotspot_14.0.2_12.tar.gz.json",
"name": "OpenJDK14U-jdk_x64_mac_hotspot_14.0.2_12.tar.gz",
"size": 195705010
},
"project": "jdk",
"scm_ref": "jdk-14.0.2+12_adopt",
"updated_at": "2020-07-16T08:55:45Z"
}
],
"download_count": 477080,
"id": "MDc6UmVsZWFzZTI4NjIyMDc4.+ve8KojpqJUpsA==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/tag/jdk-14.0.2%2B12",
"release_name": "jdk-14.0.2+12",
"release_type": "ga",
"timestamp": "2020-07-16T08:54:16Z",
"updated_at": "2020-07-16T08:54:16Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 12,
"major": 14,
"minor": 0,
"openjdk_version": "14.0.2+12",
"security": 2,
"semver": "14.0.2+12"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 58023,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "b11cb192312530bcd84607631203d0c1727e672af12813078e6b525e3cce862d",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.1%2B7/OpenJDK14U-jdk_x64_mac_hotspot_14.0.1_7.tar.gz.sha256.txt",
"download_count": 25276,
"link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.1%2B7/OpenJDK14U-jdk_x64_mac_hotspot_14.0.1_7.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.1%2B7/OpenJDK14U-jdk_x64_mac_hotspot_14.0.1_7.tar.gz.json",
"name": "OpenJDK14U-jdk_x64_mac_hotspot_14.0.1_7.tar.gz",
"size": 195769653
},
"project": "jdk",
"scm_ref": "jdk-14.0.1+7_adopt",
"updated_at": "2020-04-20T12:54:23Z"
}
],
"download_count": 198607,
"id": "MDc6UmVsZWFzZTI1Njc4MzEw.z3NqYG25PFlG+Q==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/tag/jdk-14.0.1%2B7",
"release_name": "jdk-14.0.1+7",
"release_type": "ga",
"timestamp": "2020-04-20T12:52:51Z",
"updated_at": "2020-04-20T12:52:51Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 7,
"major": 14,
"minor": 0,
"openjdk_version": "14.0.1+7",
"security": 1,
"semver": "14.0.1+7.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 30069,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "d358a7ff03905282348c6c80562a4da2e04eb377b60ad2152be4c90f8d580b7f",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.2%2B7/OpenJDK15U-jdk_x64_mac_hotspot_15.0.2_7.tar.gz.sha256.txt",
"download_count": 3718,
"link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.2%2B7/OpenJDK15U-jdk_x64_mac_hotspot_15.0.2_7.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.2%2B7/OpenJDK15U-jdk_x64_mac_hotspot_15.0.2_7.tar.gz.json",
"name": "OpenJDK15U-jdk_x64_mac_hotspot_15.0.2_7.tar.gz",
"size": 195232978
},
"project": "jdk",
"scm_ref": "jdk-15.0.2+7_adopt",
"updated_at": "2021-01-22T17:33:20Z"
}
],
"download_count": 124226,
"id": "MDc6UmVsZWFzZTM2NzgwOTAw.X2+6VqPND3E8CA==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/tag/jdk-15.0.2%2B7",
"release_name": "jdk-15.0.2+7",
"release_type": "ga",
"timestamp": "2021-01-22T17:31:37Z",
"updated_at": "2021-01-22T17:31:37Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 7,
"major": 15,
"minor": 0,
"openjdk_version": "15.0.2+7",
"security": 2,
"semver": "15.0.2+7"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 24542,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "b8c2e2ad31f3d6676ea665d9505b06df15e23741847556612b40e3ee329fc046",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.1%2B9.1/OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz.sha256.txt",
"download_count": 3274,
"link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.1%2B9.1/OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.1%2B9.1/OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz.json",
"name": "OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz",
"size": 195872839
},
"project": "jdk",
"scm_ref": "jdk-15.0.1+9_adopt",
"updated_at": "2020-12-01T16:57:47Z"
}
],
"download_count": 25378,
"id": "MDc6UmVsZWFzZTM0NjQ2MDU4.Yj2XZf+VBGAPtw==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/tag/jdk-15.0.1%2B9.1",
"release_name": "jdk-15.0.1+9.1",
"release_type": "ga",
"timestamp": "2020-12-01T16:57:26Z",
"updated_at": "2020-12-01T16:57:26Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 9,
"major": 15,
"minor": 0,
"openjdk_version": "15.0.1+9",
"security": 1,
"semver": "15.0.1+9.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 21675,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "d32f9429c4992cef7be559a15c542011503d6bc38c89379800cd209a9d7ec539",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.1%2B9/OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz.sha256.txt",
"download_count": 11935,
"link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.1%2B9/OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.1%2B9/OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz.json",
"name": "OpenJDK15U-jdk_x64_mac_hotspot_15.0.1_9.tar.gz",
"size": 195773522
},
"project": "jdk",
"scm_ref": "jdk-15.0.1+9_adopt",
"updated_at": "2020-10-23T20:48:09Z"
}
],
"download_count": 308690,
"id": "MDc6UmVsZWFzZTMyOTk4MTUx.3oazo3YGfHhF3w==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/tag/jdk-15.0.1%2B9",
"release_name": "jdk-15.0.1+9",
"release_type": "ga",
"timestamp": "2020-10-23T20:46:22Z",
"updated_at": "2020-10-23T20:46:22Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 9,
"major": 15,
"minor": 0,
"openjdk_version": "15.0.1+9",
"security": 1,
"semver": "15.0.1+9"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 51254,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "bd1fc774232e2dfee93056a01f5765bd92ffb19d68dd548c233a82bb5c162be4",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15%2B36/OpenJDK15U-jdk_x64_mac_hotspot_15_36.tar.gz.sha256.txt",
"download_count": 5325,
"link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15%2B36/OpenJDK15U-jdk_x64_mac_hotspot_15_36.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15%2B36/OpenJDK15U-jdk_x64_mac_hotspot_15_36.tar.gz.json",
"name": "OpenJDK15U-jdk_x64_mac_hotspot_15_36.tar.gz",
"size": 195853361
},
"project": "jdk",
"scm_ref": "jdk-15+36_adopt",
"updated_at": "2020-09-17T07:43:54Z"
}
],
"download_count": 157313,
"id": "MDc6UmVsZWFzZTMxNDUwMjA0.eYpt0EBEjldfEQ==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/tag/jdk-15%2B36",
"release_name": "jdk-15+36",
"release_type": "ga",
"timestamp": "2020-09-17T07:42:21Z",
"updated_at": "2020-09-17T07:42:21Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 36,
"major": 15,
"minor": 0,
"openjdk_version": "15+36",
"security": 0,
"semver": "15.0.0+36"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 27428,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "aabc3aebb0abf1ba64d9bd5796d0c7eb7239983f6e4c0f015b5b88be5616e4bd",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14%2B36/OpenJDK14U-jdk_x64_mac_hotspot_14_36.tar.gz.sha256.txt",
"download_count": 19544,
"link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14%2B36/OpenJDK14U-jdk_x64_mac_hotspot_14_36.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14%2B36/OpenJDK14U-jdk_x64_mac_hotspot_14_36.tar.gz.json",
"name": "OpenJDK14U-jdk_x64_mac_hotspot_14_36.tar.gz",
"size": 201087797
},
"project": "jdk",
"scm_ref": "jdk-14+36_adopt",
"updated_at": "2020-03-18T12:13:05Z"
}
],
"download_count": 364816,
"id": "MDc6UmVsZWFzZTI0NjMxMDAy.AY7rtvmrnWWlIg==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/tag/jdk-14%2B36",
"release_name": "jdk-14+36",
"release_type": "ga",
"timestamp": "2020-03-18T12:11:08Z",
"updated_at": "2020-03-18T12:11:08Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 36,
"major": 14,
"minor": 0,
"openjdk_version": "14+36",
"security": 0,
"semver": "14.0.0+36.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 63201,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "0ddb24efdf5aab541898d19b7667b149a1a64a8bd039b708fc58ee0284fa7e07",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13.0.2%2B8/OpenJDK13U-jdk_x64_mac_hotspot_13.0.2_8.tar.gz.sha256.txt",
"download_count": 32531,
"link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13.0.2%2B8/OpenJDK13U-jdk_x64_mac_hotspot_13.0.2_8.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13.0.2%2B8/OpenJDK13U-jdk_x64_mac_hotspot_13.0.2_8.tar.gz.json",
"name": "OpenJDK13U-jdk_x64_mac_hotspot_13.0.2_8.tar.gz",
"size": 198206427
},
"project": "jdk",
"scm_ref": "jdk-13.0.2+8_adopt",
"updated_at": "2020-01-20T16:46:24Z"
}
],
"download_count": 349677,
"id": "MDc6UmVsZWFzZTIyOTgxNTM1.gtZYwGfBgkb3Gg==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/tag/jdk-13.0.2%2B8",
"release_name": "jdk-13.0.2+8",
"release_type": "ga",
"timestamp": "2020-01-20T16:42:35Z",
"updated_at": "2020-01-20T16:42:35Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 8,
"major": 13,
"minor": 0,
"openjdk_version": "13.0.2+8",
"security": 2,
"semver": "13.0.2+8.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 41508,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "9c82de98ce9bc2353bcf314d85366c9a2c572db034e10a71aa47e804e13748c1",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13.0.1%2B9/OpenJDK13U-jdk_x64_mac_hotspot_13.0.1_9.tar.gz.sha256.txt",
"download_count": 32262,
"link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13.0.1%2B9/OpenJDK13U-jdk_x64_mac_hotspot_13.0.1_9.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13.0.1%2B9/OpenJDK13U-jdk_x64_mac_hotspot_13.0.1_9.tar.gz.json",
"name": "OpenJDK13U-jdk_x64_mac_hotspot_13.0.1_9.tar.gz",
"size": 198205689
},
"project": "jdk",
"scm_ref": "jdk-13.0.1+9_adopt",
"updated_at": "2019-10-26T14:44:27Z"
}
],
"download_count": 680021,
"id": "MDc6UmVsZWFzZTIwOTk4NDA0.srlG2TmLho/j0w==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/tag/jdk-13.0.1%2B9",
"release_name": "jdk-13.0.1+9",
"release_type": "ga",
"timestamp": "2019-10-26T14:43:52Z",
"updated_at": "2019-10-26T14:43:52Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 9,
"major": 13,
"minor": 0,
"openjdk_version": "13.0.1+9",
"security": 1,
"semver": "13.0.1+9.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 37738,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "f948be96daba250b6695e22cb51372d2ba3060e4d778dd09c89548889783099f",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13%2B33/OpenJDK13U-jdk_x64_mac_hotspot_13_33.tar.gz.sha256.txt",
"download_count": 37738,
"link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13%2B33/OpenJDK13U-jdk_x64_mac_hotspot_13_33.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13%2B33/OpenJDK13U-jdk_x64_mac_hotspot_13_33.tar.gz.json",
"name": "OpenJDK13U-jdk_x64_mac_hotspot_13_33.tar.gz",
"size": 198189530
},
"project": "jdk",
"scm_ref": "jdk-13+33_adopt",
"updated_at": "2019-09-19T10:20:21Z"
}
],
"download_count": 226200,
"id": "MDc6UmVsZWFzZTIwMTA0MTUy.trK7qCbNtlMWFw==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/tag/jdk-13%2B33",
"release_name": "jdk-13+33",
"release_type": "ga",
"timestamp": "2019-09-19T10:19:58Z",
"updated_at": "2019-09-19T10:19:58Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 33,
"major": 13,
"minor": 0,
"openjdk_version": "13+33",
"security": 0,
"semver": "13.0.0+33.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 24493,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "9919eee037554d40c7d2f219bbd654f2bf119e16a2f4d284d8dedaf525ee59e6",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.sha256.txt",
"download_count": 22907,
"link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.json",
"name": "OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"size": 198392994
},
"project": "jdk",
"scm_ref": "jdk-12.0.2+10_adopt",
"updated_at": "2019-07-18T20:27:24Z"
}
],
"download_count": 396318,
"id": "MDc6UmVsZWFzZTE4NzE2Mzk5.S/VUFSgnrVIv8A==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/tag/jdk-12.0.2%2B10",
"release_name": "jdk-12.0.2+10",
"release_type": "ga",
"timestamp": "2019-07-18T20:26:29Z",
"updated_at": "2019-07-18T20:26:29Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 10,
"major": 12,
"minor": 0,
"openjdk_version": "12.0.2+10",
"security": 2,
"semver": "12.0.2+10.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 5539,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "7acd697e816491d31b24d0ae1867fd63060aa738cfa388757946ae312a60b4f2",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10.3/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.sha256.txt",
"download_count": 5539,
"link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10.3/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10.3/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.json",
"name": "OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"size": 198429049
},
"project": "jdk",
"scm_ref": "jdk-12.0.2+10_adopt",
"updated_at": "2019-09-19T17:17:37Z"
}
],
"download_count": 5879,
"id": "MDc6UmVsZWFzZTIwMTE2ODQ3.QGQl8Nj1qkma4Q==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/tag/jdk-12.0.2%2B10.3",
"release_name": "jdk-12.0.2+10.3",
"release_type": "ga",
"timestamp": "2019-09-19T17:17:26Z",
"updated_at": "2019-12-06T15:10:37Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 3,
"build": 10,
"major": 12,
"minor": 0,
"openjdk_version": "12.0.2+10",
"security": 2,
"semver": "12.0.2+10.3"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 22794,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "2c1a46c0fab6d4bdbc443f23c3f6a313c2de47fbbd9c16b5c1133a88f6c1ab8f",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10.2/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.sha256.txt",
"download_count": 637,
"link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10.2/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10.2/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.json",
"name": "OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"size": 198862174
},
"project": "jdk",
"scm_ref": "jdk-12.0.2+10_adopt",
"updated_at": "2019-08-06T10:41:10Z"
}
],
"download_count": 23563,
"id": "MDc6UmVsZWFzZTE5MTAzMTI3.in65dKG+veAxOg==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/tag/jdk-12.0.2%2B10.2",
"release_name": "jdk-12.0.2+10.2",
"release_type": "ga",
"timestamp": "2019-08-06T10:40:44Z",
"updated_at": "2019-08-06T10:40:44Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 2,
"build": 10,
"major": 12,
"minor": 0,
"openjdk_version": "12.0.2+10",
"security": 2,
"semver": "12.0.2+10.2"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 24493,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "9919eee037554d40c7d2f219bbd654f2bf119e16a2f4d284d8dedaf525ee59e6",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.sha256.txt",
"download_count": 22907,
"link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10/OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz.json",
"name": "OpenJDK12U-jdk_x64_mac_hotspot_12.0.2_10.tar.gz",
"size": 198392994
},
"project": "jdk",
"scm_ref": "jdk-12.0.2+9_adopt",
"updated_at": "2019-07-18T20:27:24Z"
}
],
"download_count": 396318,
"id": "MDc6UmVsZWFzZTE4NzE2Mzk5.S/VUFSgnrVIv8A==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/tag/jdk-12.0.2%2B10",
"release_name": "jdk-12.0.2+9",
"release_type": "ga",
"timestamp": "2019-07-18T20:26:29Z",
"updated_at": "2019-07-18T20:26:29Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 10,
"major": 12,
"minor": 0,
"openjdk_version": "12.0.2+9",
"security": 2,
"semver": "12.0.2+9.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 39519,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "dcb2ab681247298eda018df24166ba01674127083fb02892acf087e6181d8c56",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.1%2B12/OpenJDK12U-jdk_x64_mac_hotspot_12.0.1_12.tar.gz.sha256.txt",
"download_count": 33306,
"link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.1%2B12/OpenJDK12U-jdk_x64_mac_hotspot_12.0.1_12.tar.gz",
"name": "OpenJDK12U-jdk_x64_mac_hotspot_12.0.1_12.tar.gz",
"size": 198112975
},
"project": "jdk",
"updated_at": "2019-04-21T15:12:34Z"
}
],
"download_count": 1038669,
"id": "MDc6UmVsZWFzZTE2ODg3NDU3",
"release_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/tag/jdk-12.0.1%2B12",
"release_name": "jdk-12.0.1+12",
"release_type": "ga",
"timestamp": "2019-04-21T15:11:56Z",
"updated_at": "2019-04-21T15:11:56Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 12,
"major": 12,
"minor": 0,
"openjdk_version": "12.0.1+12",
"security": 1,
"semver": "12.0.1+12"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 3136,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "985036459d4ef0867a3fe83b0bf87877d8e66a121c7b9c145bb97bd921aaf3f1",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12%2B33/OpenJDK12U-jdk_x64_mac_hotspot_12_33.tar.gz.sha256.txt",
"download_count": 1905,
"link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12%2B33/OpenJDK12U-jdk_x64_mac_hotspot_12_33.tar.gz",
"name": "OpenJDK12U-jdk_x64_mac_hotspot_12_33.tar.gz",
"size": 198099074
},
"project": "jdk",
"updated_at": "2019-03-22T12:09:13Z"
}
],
"download_count": 757289,
"id": "MDc6UmVsZWFzZTE2MjgyMjM2",
"release_link": "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/tag/jdk-12%2B33",
"release_name": "jdk-12+33",
"release_type": "ga",
"timestamp": "2019-03-22T12:08:43Z",
"updated_at": "2019-03-22T12:08:43Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 33,
"major": 12,
"minor": 0,
"openjdk_version": "12+33",
"security": 0,
"semver": "12.0.0+33"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 75576,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "ee7c98c9d79689aca6e717965747b8bf4eec5413e89d5444cc2bd6dbd59e3811",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_mac_hotspot_11.0.10_9.tar.gz.sha256.txt",
"download_count": 17426,
"link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_mac_hotspot_11.0.10_9.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_mac_hotspot_11.0.10_9.tar.gz.json",
"name": "OpenJDK11U-jdk_x64_mac_hotspot_11.0.10_9.tar.gz",
"size": 186160219
},
"project": "jdk",
"scm_ref": "jdk-11.0.10+9_adopt",
"updated_at": "2021-01-22T14:16:47Z"
}
],
"download_count": 636180,
"id": "MDc6UmVsZWFzZTM2NzcwNDUy.hAVJRiZZTufG+w==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.10%2B9",
"release_name": "jdk-11.0.10+9",
"release_type": "ga",
"timestamp": "2021-01-22T14:15:12Z",
"updated_at": "2021-01-22T14:15:12Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 9,
"major": 11,
"minor": 0,
"openjdk_version": "11.0.10+9",
"security": 10,
"semver": "11.0.10+9"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 108441,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "96bc469f9b02a3b84382a0685b0bd7935e1ad1bd82a0aab9befb5b42a17cbd77",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9.1%2B1/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9.1_1.tar.gz.sha256.txt",
"download_count": 22211,
"link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9.1%2B1/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9.1_1.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9.1%2B1/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9.1_1.tar.gz.json",
"name": "OpenJDK11U-jdk_x64_mac_hotspot_11.0.9.1_1.tar.gz",
"size": 185368626
},
"project": "jdk",
"scm_ref": "jdk-11.0.9.1+1_adopt",
"updated_at": "2020-11-12T14:10:45Z"
}
],
"download_count": 815676,
"id": "MDc6UmVsZWFzZTMzODU4MDE1.94IbKUd3vvhzsA==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.9.1%2B1",
"release_name": "jdk-11.0.9.1+1",
"release_type": "ga",
"timestamp": "2020-11-12T14:08:55Z",
"updated_at": "2020-11-12T14:08:55Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 1,
"major": 11,
"minor": 0,
"openjdk_version": "11.0.9.1+1",
"patch": 1,
"security": 9,
"semver": "11.0.9+101"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 45450,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "7b21961ffb2649e572721a0dfad64169b490e987937b661cb4e13a594c21e764",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9%2B11.1/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz.sha256.txt",
"download_count": 11117,
"link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9%2B11.1/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9%2B11.1/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz.json",
"name": "OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz",
"size": 186006796
},
"project": "jdk",
"scm_ref": "jdk-11.0.9+11_adopt",
"updated_at": "2020-10-25T14:43:54Z"
}
],
"download_count": 423635,
"id": "MDc6UmVsZWFzZTMzMDI4MDcz.dRvNNRwJCgY3Xw==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.9%2B11.1",
"release_name": "jdk-11.0.9+11.1",
"release_type": "ga",
"timestamp": "2020-10-25T13:31:15Z",
"updated_at": "2020-10-25T13:31:15Z",
"vendor": "adoptopenjdk",
"version_data": {
"adopt_build_number": 1,
"build": 11,
"major": 11,
"minor": 0,
"openjdk_version": "11.0.9+11",
"security": 9,
"semver": "11.0.9+11.1"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 2456,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "e84b00d74f08f059829bbf121c8423dc37ff65135968c1fcda5839600be4f542",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9%2B11/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz.sha256.txt",
"download_count": 1046,
"link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9%2B11/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.9%2B11/OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz.json",
"name": "OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.tar.gz",
"size": 185532704
},
"project": "jdk",
"scm_ref": "jdk-11.0.9+11_adopt",
"updated_at": "2020-10-25T13:28:33Z"
}
],
"download_count": 359580,
"id": "MDc6UmVsZWFzZTMyOTk4MzM5.6h9TT9pzYTK2Kg==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.9%2B11",
"release_name": "jdk-11.0.9+11",
"release_type": "ga",
"timestamp": "2020-10-23T20:52:14Z",
"updated_at": "2020-10-23T20:52:14Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 11,
"major": 11,
"minor": 0,
"openjdk_version": "11.0.9+11",
"security": 9,
"semver": "11.0.9+11"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 149393,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "4a8dadd58cdc32c7e59978971d56aec610be7ee0ddf0dc1d137bb8b78456499f",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz.sha256.txt",
"download_count": 40158,
"link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz.json",
"name": "OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz",
"size": 185054456
},
"project": "jdk",
"scm_ref": "jdk-11.0.8+10_adopt",
"updated_at": "2020-07-15T14:30:51Z"
}
],
"download_count": 1968658,
"id": "MDc6UmVsZWFzZTI4NTg5Nzcz.pCNBA7G9E1o7pw==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.8%2B10",
"release_name": "jdk-11.0.8+10",
"release_type": "ga",
"timestamp": "2020-07-15T14:29:27Z",
"updated_at": "2020-07-15T14:29:27Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 10,
"major": 11,
"minor": 0,
"openjdk_version": "11.0.8+10",
"security": 8,
"semver": "11.0.8+10"
}
},
{
"binaries": [],
"download_count": 1968658,
"id": "MDc6UmVsZWFzZTI4NTg5Nzcz.pCNBA7G9E1o7pw==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.8%2B10",
"release_name": "jdk-11.0.8+10",
"release_type": "ga",
"timestamp": "2020-07-15T14:29:27Z",
"updated_at": "2020-07-15T14:29:27Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 10,
"major": 9,
"minor": 0,
"openjdk_version": "9.0.8+10",
"security": 8,
"semver": "9.0.8+10"
}
},
{
"binaries": [
{
"architecture": "x64",
"download_count": 149393,
"heap_size": "normal",
"image_type": "jdk",
"jvm_impl": "hotspot",
"os": "mac",
"package": {
"checksum": "4a8dadd58cdc32c7e59978971d56aec610be7ee0ddf0dc1d137bb8b78456499f",
"checksum_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz.sha256.txt",
"download_count": 40158,
"link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz",
"metadata_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz.json",
"name": "OpenJDK11U-jdk_x64_mac_hotspot_11.0.8_10.tar.gz",
"size": 185054456
},
"project": "jdk",
"scm_ref": "jdk-11.0.8+10_adopt",
"updated_at": "2020-07-15T14:30:51Z"
}
],
"download_count": 1968658,
"id": "MDc6UmVsZWFzZTI4NTg5Nzcz.pCNBA7G9E1o7pw==",
"release_link": "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.8%2B10",
"release_name": "jdk-11.0.8+10",
"release_type": "ga",
"timestamp": "2020-07-15T14:29:27Z",
"updated_at": "2020-07-15T14:29:27Z",
"vendor": "adoptopenjdk",
"version_data": {
"build": 10,
"major": 9,
"minor": 0,
"openjdk_version": "9.0.8+10",
"security": 8,
"semver": "9.0.7+10"
}
}
]
@@ -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"
}
}
}
}
}
}
}
}
}
@@ -1,424 +0,0 @@
import {
jest,
describe,
it,
expect,
beforeEach,
afterEach,
beforeAll,
afterAll
} from '@jest/globals';
import {HttpClient} from '@actions/http-client';
import os from 'os';
import manifestData from '../data/adopt.json' with {type: 'json'};
// Mock @actions/core before importing source modules that depend on it
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((p: string) => p),
toWin32Path: jest.fn((p: string) => p),
toPosixPath: jest.fn((p: string) => p)
}));
// Dynamic imports after mocking
const core = await import('@actions/core');
const {AdoptDistribution, AdoptImplementation} =
await import('../../src/distributions/adopt/installer.js');
const {TemurinDistribution} =
await import('../../src/distributions/temurin/installer.js');
import type {IAdoptAvailableVersions} from '../../src/distributions/adopt/models.js';
import type {AdoptImplementation as AdoptImplementationType} from '../../src/distributions/adopt/installer.js';
import type {JavaInstallerOptions} from '../../src/distributions/base-models.js';
describe('getAvailableVersions', () => {
let spyHttpClient: any;
let spyCoreError: any;
let spyCoreWarning: any;
beforeEach(() => {
spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
spyHttpClient.mockReturnValue({
statusCode: 200,
headers: {},
result: []
});
// Mock core.error to suppress error logs
spyCoreError = core.error as jest.Mock;
spyCoreError.mockImplementation(() => {});
spyCoreWarning = core.warning as jest.Mock;
spyCoreWarning.mockImplementation(() => {});
});
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
jest.restoreAllMocks();
});
it.each([
[
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jdk&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{
version: '11',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot,
'os=mac&architecture=x86&image_type=jdk&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{
version: '11',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
AdoptImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jre&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{
version: '11-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jdk&release_type=ea&jvm_impl=hotspot&page_size=20&page=0'
],
[
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.OpenJ9,
'os=mac&architecture=x64&image_type=jdk&release_type=ga&jvm_impl=openj9&page_size=20&page=0'
],
[
{
version: '11',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.OpenJ9,
'os=mac&architecture=x86&image_type=jdk&release_type=ga&jvm_impl=openj9&page_size=20&page=0'
],
[
{
version: '11',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
AdoptImplementation.OpenJ9,
'os=mac&architecture=x64&image_type=jre&release_type=ga&jvm_impl=openj9&page_size=20&page=0'
],
[
{
version: '11-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.OpenJ9,
'os=mac&architecture=x64&image_type=jdk&release_type=ea&jvm_impl=openj9&page_size=20&page=0'
]
])(
'build correct url for %s',
async (
installerOptions: JavaInstallerOptions,
impl: AdoptImplementationType,
expectedParameters
) => {
const distribution = new AdoptDistribution(installerOptions, impl);
const baseUrl =
'https://api.adoptopenjdk.net/v3/assets/version/%5B1.0,100.0%5D';
const expectedUrl = `${baseUrl}?project=jdk&vendor=adoptopenjdk&heap_size=normal&sort_method=DEFAULT&sort_order=DESC&${expectedParameters}`;
distribution['getPlatformOption'] = () => 'mac';
await distribution['getAvailableVersions']();
expect(spyHttpClient.mock.calls).toHaveLength(1);
expect(spyHttpClient.mock.calls[0][0]).toBe(expectedUrl);
}
);
it('load available versions', async () => {
const nextPageUrl =
'https://api.adoptopenjdk.net/v3/assets/version/%5B1.0,100.0%5D?page=1&page_size=20';
spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
spyHttpClient
.mockReturnValueOnce({
statusCode: 200,
headers: {link: `<${nextPageUrl}>; rel="next"`},
result: manifestData as any
})
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: manifestData as any
});
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions).not.toBeNull();
expect(availableVersions.length).toBe(manifestData.length * 2);
expect(spyHttpClient).toHaveBeenNthCalledWith(2, nextPageUrl);
});
it('stops pagination after 1000 pages as a safeguard', async () => {
const nextPageUrl =
'https://api.adoptopenjdk.net/v3/assets/version/%5B1.0,100.0%5D?page=2&page_size=20';
spyHttpClient.mockReturnValue({
statusCode: 200,
headers: {link: `<${nextPageUrl}>; rel="next"`},
result: [{version_data: {semver: '17.0.1'}, binaries: []}] as any
});
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
await distribution['getAvailableVersions']();
expect(spyHttpClient).toHaveBeenCalledTimes(1000);
expect(spyCoreWarning).toHaveBeenCalledWith(
expect.stringContaining('Reached pagination safeguard limit (1000 pages)')
);
});
it.each([
[AdoptImplementation.Hotspot, 'jdk', 'Java_Adopt_jdk'],
[AdoptImplementation.Hotspot, 'jre', 'Java_Adopt_jre'],
[AdoptImplementation.OpenJ9, 'jdk', 'Java_Adopt-OpenJ9_jdk'],
[AdoptImplementation.OpenJ9, 'jre', 'Java_Adopt-OpenJ9_jre']
])(
'find right toolchain folder',
(impl: AdoptImplementationType, packageType: string, expected: string) => {
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: packageType,
checkLatest: false
},
impl
);
// @ts-ignore - because it is protected
expect(distribution.toolcacheFolderName).toBe(expected);
}
);
it.each([
['amd64', 'x64'],
['arm64', 'aarch64']
])(
'defaults to os.arch(): %s mapped to distro arch: %s',
async (osArch: string, distroArch: string) => {
jest
.spyOn(os, 'arch')
.mockReturnValue(osArch as ReturnType<typeof os.arch>);
const installerOptions: JavaInstallerOptions = {
version: '17',
architecture: '', // to get default value
packageType: 'jdk',
checkLatest: false
};
const expectedParameters = `os=mac&architecture=${distroArch}&image_type=jdk&release_type=ga&jvm_impl=hotspot&page_size=20&page=0`;
const distribution = new AdoptDistribution(
installerOptions,
AdoptImplementation.Hotspot
);
const baseUrl =
'https://api.adoptopenjdk.net/v3/assets/version/%5B1.0,100.0%5D';
const expectedUrl = `${baseUrl}?project=jdk&vendor=adoptopenjdk&heap_size=normal&sort_method=DEFAULT&sort_order=DESC&${expectedParameters}`;
distribution['getPlatformOption'] = () => 'mac';
await distribution['getAvailableVersions']();
expect(spyHttpClient.mock.calls).toHaveLength(1);
expect(spyHttpClient.mock.calls[0][0]).toBe(expectedUrl);
}
);
});
describe('findPackageForDownload', () => {
it('returns Temurin result and does not query Adopt API when Temurin succeeds', async () => {
const temurinRelease = {
version: '11.0.31+11',
url: 'https://example.test/temurin-11.tar.gz'
};
const temurinFindPackageForDownload = jest
.fn<any>()
.mockResolvedValue(temurinRelease);
const temurinDistribution = {
findPackageForDownload: temurinFindPackageForDownload
} as any;
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot,
temurinDistribution
);
const adoptLookupSpy = jest.fn<any>();
distribution['getAvailableVersions'] = adoptLookupSpy;
const resolvedVersion = await distribution['findPackageForDownload']('11');
expect(resolvedVersion).toEqual(temurinRelease);
expect(temurinFindPackageForDownload).toHaveBeenCalledWith('11');
expect(adoptLookupSpy).not.toHaveBeenCalled();
});
it.each([
['9', '9.0.7+10'],
['15', '15.0.2+7'],
['15.0', '15.0.2+7'],
['15.0.2', '15.0.2+7'],
['15.0.1', '15.0.1+9.1'],
['11.x', '11.0.10+9'],
['x', '15.0.2+7'],
['12', '12.0.2+10.3'], // make sure that '12.0.2+10.1', '12.0.2+10.3', '12.0.2+10.2' are sorted correctly
['12.0.2+10.1', '12.0.2+10.1'],
['15.0.1+9', '15.0.1+9'],
['15.0.1+9.1', '15.0.1+9.1']
])('version is resolved correctly %s -> %s', async (input, expected) => {
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
// Mock Temurin to fail so fallback to AdoptOpenJDK is tested
distribution['temurinDistribution']!['findPackageForDownload'] =
async () => {
throw new Error('No matching version found for SemVer');
};
distribution['getAvailableVersions'] = async () => manifestData as any;
const resolvedVersion = await distribution['findPackageForDownload'](input);
expect(resolvedVersion.version).toBe(expected);
});
it('version is found but binaries list is empty', async () => {
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
// Mock Temurin to fail so fallback to AdoptOpenJDK is tested
distribution['temurinDistribution']!['findPackageForDownload'] =
async () => {
throw new Error('No matching version found for SemVer');
};
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(
distribution['findPackageForDownload']('9.0.8')
).rejects.toThrow(/No matching version found for SemVer */);
});
it('version is not found', async () => {
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
// Mock Temurin to fail so fallback to AdoptOpenJDK is tested
distribution['temurinDistribution']!['findPackageForDownload'] =
async () => {
throw new Error('No matching version found for SemVer');
};
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(distribution['findPackageForDownload']('7.x')).rejects.toThrow(
/No matching version found for SemVer */
);
});
it('version list is empty', async () => {
const distribution = new AdoptDistribution(
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
// Mock Temurin to fail so fallback to AdoptOpenJDK is tested
distribution['temurinDistribution']!['findPackageForDownload'] =
async () => {
throw new Error('No matching version found for SemVer');
};
distribution['getAvailableVersions'] = async () => [];
await expect(distribution['findPackageForDownload']('11')).rejects.toThrow(
/No matching version found for SemVer */
);
});
});
File diff suppressed because it is too large Load Diff
@@ -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';
@@ -202,6 +203,12 @@ describe('getAvailableVersions', () => {
await distribution['findPackageForDownload'](version);
expect(availableVersion).not.toBeNull();
expect(availableVersion.url).toBe(expectedLink);
expect(availableVersion.checksum).toEqual({
algorithm: 'sha256',
value: expect.stringMatching(/^[a-f0-9]{64}$/),
source:
'https://corretto.github.io/corretto-downloads/latest_links/indexmap_with_checksum.json'
});
});
it('with latest resolves to the newest available major version', async () => {
@@ -293,6 +300,19 @@ describe('getAvailableVersions', () => {
expect(availableVersion.url).toBe(expectedLink);
}
);
it('keeps the canonical ARM runner value separate from the vendor value', () => {
jest.spyOn(os, 'arch').mockReturnValue('arm');
const distribution = new CorrettoDistribution({
version: '11',
architecture: '',
packageType: 'jdk',
checkLatest: false
});
expect(distribution['architecture']).toBe('armv7');
expect(distribution['distributionArchitecture']()).toBe('arm');
});
});
const mockPlatform = (
@@ -304,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();
});
});
@@ -0,0 +1,23 @@
import {jest, describe, it, expect} from '@jest/globals';
jest.unstable_mockModule('../../src/distributions/zulu/installer.js', () => {
throw new Error(
'Zulu installer module must not be imported on the Temurin fast path'
);
});
const {getJavaDistribution} =
await import('../../src/distributions/distribution-factory.js');
describe('distribution factory lazy loading', () => {
it('does not load non-selected distribution installers for Temurin', async () => {
const distribution = await getJavaDistribution('temurin', {
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
expect(distribution).not.toBeNull();
});
});
@@ -1,16 +1,160 @@
import {getJavaDistribution} from '../../src/distributions/distribution-factory.js';
import {RetryingHttpClient} from '../../src/retrying-http-client.js';
import {
JAVA_PACKAGE_CAPABILITIES,
JavaDistribution
} from '../../src/distributions/package-types.js';
import os from 'os';
import {validateJavaPlatform} from '../../src/distributions/platform-types.js';
import {normalizeArchitecture} from '../../src/distributions/platform-types.js';
const supportedDistributionsOnCurrentPlatform = Object.values(
JavaDistribution
).filter(distributionName => {
try {
validateJavaPlatform(distributionName, process.platform, 'x64', '25');
return distributionName !== JavaDistribution.JdkFile;
} catch {
return false;
}
});
const installerOptions = (packageType: string, version = '25') => ({
version,
architecture: 'x64',
packageType,
checkLatest: false
});
describe('getJavaDistribution', () => {
it("rejects java-package 'jdk+jmods' for non-Temurin distributions", () => {
expect(() =>
getJavaDistribution('zulu', {
it.each(supportedDistributionsOnCurrentPlatform)(
'uses the shared retrying HTTP client for %s',
async distributionName => {
const distribution = await getJavaDistribution(distributionName, {
version: '25',
architecture: 'x64',
packageType: 'jdk+jmods',
packageType: 'jdk',
checkLatest: false
})
).toThrow(
"java-package 'jdk+jmods' is only supported for distribution 'temurin'."
});
expect(distribution).not.toBeNull();
expect(distribution!['http']).toBeInstanceOf(RetryingHttpClient);
}
);
it.each(
Object.entries(JAVA_PACKAGE_CAPABILITIES).flatMap(
([distributionName, packageTypes]) =>
supportedDistributionsOnCurrentPlatform.includes(
distributionName as JavaDistribution
) || distributionName === JavaDistribution.JdkFile
? packageTypes.map(packageType => [distributionName, packageType])
: []
)
)(
'accepts %s with java-package %s',
async (distributionName, packageType) => {
expect(
await getJavaDistribution(
distributionName,
installerOptions(packageType as string)
)
).not.toBeNull();
}
);
it.each(Object.entries(JAVA_PACKAGE_CAPABILITIES))(
'rejects unsupported java-package values for %s',
async (distributionName, packageTypes) => {
await expect(
getJavaDistribution(distributionName, installerOptions('jdk+typo'))
).rejects.toThrow(
`Java package 'jdk+typo' is not supported for distribution '${distributionName}'. Supported package types: ${packageTypes.join(', ')}.`
);
}
);
it("rejects java-package 'jdk+jmods' for non-Temurin distributions", async () => {
await expect(
getJavaDistribution('zulu', installerOptions('jdk+jmods'))
).rejects.toThrow(
"Java package 'jdk+jmods' is not supported for distribution 'zulu'. Supported package types: jdk, jre, jdk+fx, jre+fx, jdk+crac, jre+crac."
);
});
it.each(['8', '23.x', '23.0.1.1', '<24'])(
"rejects Temurin java-package 'jdk+jmods' for version %s",
async version => {
await expect(
getJavaDistribution(
JavaDistribution.Temurin,
installerOptions('jdk+jmods', version)
)
).rejects.toThrow(
`Java package 'jdk+jmods' is not supported for distribution 'temurin'. Supported package types: jdk, jre, jdk+jmods. Package 'jdk+jmods' requires Java 24 or later; requested version '${version}'.`
);
}
);
it.each(['24', '24.0.1.1', '25-ea', '>=21', 'latest'])(
"accepts Temurin java-package 'jdk+jmods' for version %s",
async version => {
expect(
await getJavaDistribution(
JavaDistribution.Temurin,
installerOptions('jdk+jmods', version)
)
).not.toBeNull();
}
);
it('preserves unsupported distribution handling', async () => {
expect(
await getJavaDistribution(
'not-a-distribution',
installerOptions('not-a-package')
)
).toBeNull();
});
it.each(['adopt', 'adopt-hotspot', 'adopt-openj9'])(
'does not support legacy Adopt distribution %s',
async distributionName => {
expect(
await getJavaDistribution(distributionName, installerOptions('jdk'))
).toBeNull();
}
);
it.each([
['amd64', 'x64'],
['ia32', 'x86'],
['arm64', 'aarch64']
])('passes normalized architecture %s as %s', async (input, expected) => {
const normalized = await getJavaDistribution(JavaDistribution.JdkFile, {
...installerOptions('jdk'),
architecture: input
});
expect(normalized!['architecture']).toBe(expected);
});
it('uses the runner architecture when the input is empty', async () => {
const distribution = await getJavaDistribution(JavaDistribution.Temurin, {
...installerOptions('jdk'),
architecture: ''
});
const expected = normalizeArchitecture(os.arch());
expect(distribution!['architecture']).toBe(expected);
});
it('rejects an unsupported combination before creating an HTTP client', async () => {
await expect(
getJavaDistribution(JavaDistribution.Oracle, {
...installerOptions('jdk'),
architecture: 'x86'
})
).rejects.toThrow(/does not support operating system/);
});
});
@@ -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'};
@@ -259,6 +260,10 @@ describe('getAvailableVersions', () => {
await distribution['findPackageForDownload'](jdkVersion);
expect(availableVersion).not.toBeNull();
expect(availableVersion.url).toBe(expectedLink);
expect(availableVersion.checksum).toEqual({
algorithm: 'sha256',
value: expect.stringMatching(/^[a-f0-9]{64}$/)
});
}
);
@@ -303,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'})
}));
@@ -129,6 +130,14 @@ describe('GraalVMDistribution', () => {
(distribution as any).http = mockHttpClient;
(communityDistribution as any).http = mockHttpClient;
// Default checksum sibling response for `${url}.sha256` requests made by
// GraalVM (Oracle) and GraalVM EA. Individual tests override this when
// they need to assert the exact URL/digest contract.
mockHttpClient.get.mockResolvedValue({
message: {statusCode: 200},
readBody: jest.fn().mockResolvedValue('a'.repeat(64))
});
(util.getDownloadArchiveExtension as jest.Mock<any>).mockReturnValue(
'tar.gz'
);
@@ -355,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', () => {
@@ -407,9 +440,17 @@ describe('GraalVMDistribution', () => {
expect(result).toEqual({
url: 'https://download.oracle.com/graalvm/17/archive/graalvm-jdk-17.0.5_linux-x64_bin.tar.gz',
version: '17.0.5'
version: '17.0.5',
checksum: {
algorithm: 'sha256',
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`);
});
it('should construct correct URL for major version (latest)', async () => {
@@ -422,10 +463,46 @@ describe('GraalVMDistribution', () => {
expect(result).toEqual({
url: 'https://download.oracle.com/graalvm/21/latest/graalvm-jdk-21_linux-x64_bin.tar.gz',
version: '21'
version: '21',
checksum: {
algorithm: 'sha256',
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,
@@ -465,7 +542,14 @@ describe('GraalVMDistribution', () => {
expect(result).toEqual({
url: 'https://download.oracle.com/graalvm/25/latest/graalvm-jdk-25_linux-x64_bin.tar.gz',
version: '25'
version: '25',
checksum: {
algorithm: 'sha256',
value: 'a'.repeat(64),
source:
'https://download.oracle.com/graalvm/25/latest/graalvm-jdk-25_linux-x64_bin.tar.gz.sha256'
},
floating: true
});
});
@@ -637,13 +721,20 @@ describe('GraalVMDistribution', () => {
expect(result).toEqual({
url: 'https://example.com/download/graalvm-jdk-23_linux-x64_bin.tar.gz',
version: '23-ea-20240716'
version: '23-ea-20240716',
checksum: {
algorithm: 'sha256',
value: 'a'.repeat(64),
source:
'https://example.com/download/graalvm-jdk-23_linux-x64_bin.tar.gz.sha256'
}
});
expect(mockHttpClient.getJson).toHaveBeenCalledWith(
'https://api.github.com/repos/graalvm/oracle-graalvm-ea-builds/contents/versions/23-ea.json?ref=main',
{Accept: 'application/json'}
);
expect(mockHttpClient.get).toHaveBeenCalledWith(`${result.url}.sha256`);
});
it('should throw error when no latest EA version found', async () => {
@@ -876,8 +967,15 @@ describe('GraalVMDistribution', () => {
expect(fetchEASpy).toHaveBeenCalledWith('23-ea');
expect(result).toEqual({
url: 'https://example.com/download/graalvm-jdk-23_linux-x64_bin.tar.gz',
version: '23-ea-20240716'
version: '23-ea-20240716',
checksum: {
algorithm: 'sha256',
value: 'a'.repeat(64),
source:
'https://example.com/download/graalvm-jdk-23_linux-x64_bin.tar.gz.sha256'
}
});
expect(mockHttpClient.get).toHaveBeenCalledWith(`${result.url}.sha256`);
// Verify debug logging
expect(core.debug).toHaveBeenCalledWith('Searching for EA build: 23-ea');
@@ -976,7 +1074,13 @@ describe('GraalVMDistribution', () => {
expect(result).toEqual({
url: 'https://example.com/download/graalvm-jdk-23_linux-aarch64_bin.tar.gz',
version: '23-ea-20240716'
version: '23-ea-20240716',
checksum: {
algorithm: 'sha256',
value: 'a'.repeat(64),
source:
'https://example.com/download/graalvm-jdk-23_linux-aarch64_bin.tar.gz.sha256'
}
});
});
@@ -1151,6 +1255,80 @@ describe('GraalVMDistribution', () => {
url: 'https://github.com/graalvm/graalvm-ce-builds/releases/download/jdk-21.0.2/graalvm-community-jdk-21.0.2_linux-x64_bin.tar.gz',
version: '21.0.2'
});
// The asset had no `digest` field, so no checksum should be attached,
// and the checksum sibling-URL fetch path (used by Oracle GraalVM)
// must not be consulted for GraalVM Community.
expect(result.checksum).toBeUndefined();
expect(mockHttpClient.get).not.toHaveBeenCalled();
});
it('strips the `sha256:` prefix from a GitHub release asset digest', async () => {
const digest = 'd'.repeat(64);
mockHttpClient.getJson.mockResolvedValue({
result: [
{
draft: false,
prerelease: false,
assets: [
{
name: 'graalvm-community-jdk-21.0.2_linux-x64_bin.tar.gz',
browser_download_url:
'https://github.com/graalvm/graalvm-ce-builds/releases/download/jdk-21.0.2/graalvm-community-jdk-21.0.2_linux-x64_bin.tar.gz',
digest: `sha256:${digest}`
}
]
}
],
statusCode: 200,
headers: {}
});
const result = await (
communityDistribution as any
).findPackageForDownload('21.0.2');
expect(result.checksum).toEqual({
algorithm: 'sha256',
value: digest,
source:
'https://api.github.com/repos/graalvm/graalvm-ce-builds/releases?per_page=100'
});
// The digest came from the release listing itself, so no additional
// HTTP request should be made to resolve the checksum.
expect(mockHttpClient.get).not.toHaveBeenCalled();
});
it('safely skips a missing or malformed release asset digest', async () => {
mockHttpClient.getJson.mockResolvedValue({
result: [
{
draft: false,
prerelease: false,
assets: [
{
name: 'graalvm-community-jdk-21.0.2_linux-x64_bin.tar.gz',
browser_download_url:
'https://github.com/graalvm/graalvm-ce-builds/releases/download/jdk-21.0.2/graalvm-community-jdk-21.0.2_linux-x64_bin.tar.gz',
digest: 'md5:not-a-sha256-digest'
}
]
}
],
statusCode: 200,
headers: {}
});
const result = await (
communityDistribution as any
).findPackageForDownload('21.0.2');
expect(result.checksum).toBeUndefined();
expect(mockHttpClient.get).not.toHaveBeenCalled();
expect(core.debug).toHaveBeenCalledWith(
expect.stringContaining(
'No authoritative sha256 digest is available for graalvm-community-jdk-21.0.2_linux-x64_bin.tar.gz'
)
);
});
it('should resolve the latest GraalVM Community release for a major version', async () => {
@@ -1282,8 +1460,11 @@ describe('distribution factory', () => {
checkLatest: false
};
it('should map graalvm-community to the community installer', () => {
const community = getJavaDistribution('graalvm-community', defaultOptions);
it('should map graalvm-community to the community installer', async () => {
const community = await getJavaDistribution(
'graalvm-community',
defaultOptions
);
expect(community).toBeInstanceOf(GraalVMCommunityDistribution);
});
@@ -9,7 +9,9 @@ import {
afterAll
} from '@jest/globals';
import https from 'https';
import {HttpClient} from '@actions/http-client';
import {HttpClient, HttpClientResponse} from '@actions/http-client';
import type {IncomingMessage} from 'http';
import {Readable} from 'stream';
import manifestData from '../data/jetbrains.json' with {type: 'json'};
import os from 'os';
@@ -44,6 +46,36 @@ jest.unstable_mockModule('@actions/core', () => ({
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,
body = '',
headers: IncomingMessage['headers'] = {}
): HttpClientResponse {
const message = Readable.from([Buffer.from(body)]) as IncomingMessage;
message.statusCode = statusCode;
message.headers = headers;
return new HttpClientResponse(message);
}
describe('getAvailableVersions', () => {
let spyHttpClient: any;
@@ -95,9 +127,198 @@ describe('getAvailableVersions', () => {
os.platform() === 'win32' ? manifestData.length : manifestData.length + 2;
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('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);
const requestRaw = jest
.spyOn(HttpClient.prototype, 'requestRaw')
.mockResolvedValueOnce(response(429, '', {'retry-after': '2'}))
.mockResolvedValueOnce(response(200, '[]'))
.mockResolvedValueOnce(response(200))
.mockResolvedValueOnce(response(200));
const distribution = new JetBrainsDistribution({
version: '17',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['http'] = new RetryingHttpClient('test', {
sleep,
random: () => 0
});
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions).toHaveLength(2);
expect(requestRaw).toHaveBeenCalledTimes(4);
expect(requestRaw.mock.calls[0][0].options.path).toBe(
requestRaw.mock.calls[1][0].options.path
);
expect(requestRaw.mock.calls[0][0].options.path).toContain(
'/repos/JetBrains/JetBrainsRuntime/releases'
);
expect(sleep).toHaveBeenCalledWith(2000);
expect(core.info).toHaveBeenCalledWith(
'Request attempt 1 of 4 failed (HTTP 429); retrying in 2000 ms'
);
});
});
describe('findPackageForDownload', () => {
let spyHttpClientGet: any;
const JETBRAINS_CHECKSUM = 'c'.repeat(128);
beforeEach(() => {
// Every resolved release fetches `${url}.checksum` (sha512, GNU
// `<hex> <filename>` format); stub it so tests never reach the real
// network, except the dedicated 'version %s can be downloaded' test
// below which intentionally exercises real HTTPS HEAD requests.
spyHttpClientGet = jest
.spyOn(HttpClient.prototype, 'get')
.mockResolvedValue({
message: {statusCode: 200},
readBody: async () => `${JETBRAINS_CHECKSUM} jbrsdk.tar.gz\n`
} as any);
});
afterEach(() => {
jest.restoreAllMocks();
});
it.each([
['17', '17.0.11+1207.24'],
['11.0', '11.0.16+2043.64'],
@@ -181,4 +402,72 @@ describe('findPackageForDownload', () => {
/No matching version found for SemVer */
);
});
it('fetches the authoritative sha512 checksum only for the resolved version', async () => {
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
const result = await distribution['findPackageForDownload']('21');
expect(result.checksum).toEqual({
algorithm: 'sha512',
value: JETBRAINS_CHECKSUM,
source: `${result.url}.checksum`
});
// Only the single resolved/winning version's checksum is requested,
// not one per candidate considered during version resolution.
expect(spyHttpClientGet).toHaveBeenCalledWith(`${result.url}.checksum`);
expect(spyHttpClientGet).toHaveBeenCalledTimes(1);
});
it('parses only the first whitespace-delimited token from the GNU checksum payload', async () => {
spyHttpClientGet.mockResolvedValue({
message: {statusCode: 200},
readBody: async () => `${JETBRAINS_CHECKSUM} jbrsdk-21.tar.gz\n`
} as any);
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
const result = await distribution['findPackageForDownload']('21');
expect(result.checksum?.value).toBe(JETBRAINS_CHECKSUM);
});
it('falls back to a sha256 checksum for older JBR builds that only publish one', async () => {
// Older JBR 11 builds (e.g. jbrsdk_nomod-11_0_16-*-b2043.64.tar.gz) publish
// a SHA-256 digest at the generic `.checksum` sibling instead of SHA-512.
const sha256Checksum = 'a'.repeat(64);
spyHttpClientGet.mockResolvedValue({
message: {statusCode: 200},
readBody: async () =>
`${sha256Checksum} jbrsdk_nomod-11_0_16-osx-x64-b2043.64.tar.gz\n`
} as any);
const distribution = new JetBrainsDistribution({
version: '21',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
const result = await distribution['findPackageForDownload']('21');
expect(result.checksum).toEqual({
algorithm: 'sha256',
value: sha256Checksum,
source: `${result.url}.checksum`
});
});
});
@@ -216,6 +216,15 @@ describe('Check findPackageForDownload', () => {
await distribution['findPackageForDownload'](version);
expect(availableRelease).not.toBeNull();
expect(availableRelease.url).toBe(expectedUrl);
if (availableRelease.checksum) {
expect(availableRelease.checksum).toEqual({
algorithm: 'sha256',
value: expect.stringMatching(/^[a-f0-9]{64}$/),
source: 'https://tencent.github.io/konajdk/releases/kona-v1.json'
});
} else {
expect(version).toBe('8.0.20');
}
}
);
});
@@ -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()
}));
@@ -103,9 +103,12 @@ const util = await import('../../src/util.js');
describe('findPackageForDownload', () => {
let distribution: InstanceType<typeof MicrosoftDistributions>;
let spyGetManifestFromRepo: any;
let spyHttpClientGet: any;
let spyDebug: any;
let spyCoreError: any;
const MICROSOFT_CHECKSUM = 'b'.repeat(64);
beforeEach(() => {
mockOsArch.mockReturnValue('x64');
mockOsPlatform.mockReturnValue(process.platform);
@@ -124,6 +127,15 @@ describe('findPackageForDownload', () => {
headers: {}
});
// Every resolved release fetches `${download_url}.sha256sum.txt`; stub
// it with a GNU-style `<hex> <filename>` payload so tests never reach
// the real network.
spyHttpClientGet = jest.spyOn(HttpClient.prototype, 'get');
spyHttpClientGet.mockResolvedValue({
message: {statusCode: 200},
readBody: async () => `${MICROSOFT_CHECKSUM} microsoft-jdk.tar.gz\n`
});
spyDebug = core.debug as jest.Mock;
spyDebug.mockImplementation(() => {});
@@ -311,6 +323,34 @@ describe('findPackageForDownload', () => {
'https://example.test/jdk.tar.gz.custom.sig'
);
});
it('fetches the authoritative sha256 checksum from the GNU-style sibling file', async () => {
mockOsPlatform.mockReturnValue(process.platform);
const result = await distribution['findPackageForDownload']('17.0.7');
expect(result.checksum).toEqual({
algorithm: 'sha256',
value: MICROSOFT_CHECKSUM,
source: `${result.url}.sha256sum.txt`
});
expect(spyHttpClientGet).toHaveBeenCalledWith(
`${result.url}.sha256sum.txt`
);
expect(spyHttpClientGet).toHaveBeenCalledTimes(1);
});
it('parses only the first whitespace-delimited token from the GNU checksum payload', async () => {
spyHttpClientGet.mockResolvedValue({
message: {statusCode: 200},
readBody: async () =>
`${MICROSOFT_CHECKSUM} microsoft-jdk-17.0.7-linux-x64.tar.gz\n`
});
const result = await distribution['findPackageForDownload']('17.0.7');
expect(result.checksum?.value).toBe(MICROSOFT_CHECKSUM);
});
});
describe('downloadTool', () => {
@@ -50,6 +50,14 @@ const archivePage = `
<th>9.0.4 (build 9.0.4+11)</th>
<a href="https://download.java.net/java/GA/jdk9/9.0.4/binaries/openjdk-9.0.4_linux-x64_bin.tar.gz">tar.gz</a>
`;
const GA_CHECKSUM = 'c'.repeat(64);
const EA_CHECKSUM = 'd'.repeat(64);
const checksumPages: Record<string, string> = {
'https://download.java.net/java/GA/jdk26.0.2/hash/10/GPL/openjdk-26.0.2_linux-x64_bin.tar.gz.sha256':
GA_CHECKSUM,
'https://download.java.net/java/early_access/jdk27/32/GPL/openjdk-27-ea+32_linux-x64_bin.tar.gz.sha256':
EA_CHECKSUM
};
function createDistribution(
version = '26',
@@ -82,8 +90,16 @@ describe('OpenJdkDistribution', () => {
'https://jdk.java.net/27/': earlyAccessPage,
'https://jdk.java.net/archive/': archivePage
};
if (url in pages) {
return {
message: {statusCode: 200},
readBody: async () => pages[url]
} as Awaited<ReturnType<HttpClient['get']>>;
}
// Any other GET is a `${archiveUrl}.sha256` checksum sibling request.
return {
readBody: async () => pages[url] ?? ''
message: {statusCode: 200},
readBody: async () => checksumPages[url] ?? 'e'.repeat(64)
} as Awaited<ReturnType<HttpClient['get']>>;
});
});
@@ -97,8 +113,15 @@ describe('OpenJdkDistribution', () => {
expect(result).toEqual({
version: '26.0.2+10',
url: 'https://download.java.net/java/GA/jdk26.0.2/hash/10/GPL/openjdk-26.0.2_linux-x64_bin.tar.gz'
url: 'https://download.java.net/java/GA/jdk26.0.2/hash/10/GPL/openjdk-26.0.2_linux-x64_bin.tar.gz',
checksum: {
algorithm: 'sha256',
value: GA_CHECKSUM,
source:
'https://download.java.net/java/GA/jdk26.0.2/hash/10/GPL/openjdk-26.0.2_linux-x64_bin.tar.gz.sha256'
}
});
expect(getSpy).toHaveBeenCalledWith(`${result.url}.sha256`);
});
it('resolves an archived GA release', async () => {
@@ -144,9 +167,16 @@ describe('OpenJdkDistribution', () => {
expect(result).toEqual({
version: '27.0.0+32',
url: 'https://download.java.net/java/early_access/jdk27/32/GPL/openjdk-27-ea+32_linux-x64_bin.tar.gz'
url: 'https://download.java.net/java/early_access/jdk27/32/GPL/openjdk-27-ea+32_linux-x64_bin.tar.gz',
checksum: {
algorithm: 'sha256',
value: EA_CHECKSUM,
source:
'https://download.java.net/java/early_access/jdk27/32/GPL/openjdk-27-ea+32_linux-x64_bin.tar.gz.sha256'
}
});
expect(getSpy).not.toHaveBeenCalledWith('https://jdk.java.net/archive/');
expect(getSpy).toHaveBeenCalledWith(`${result.url}.sha256`);
});
it('reports available versions when no release matches', async () => {
@@ -203,8 +233,8 @@ describe('OpenJdkDistribution', () => {
expect(windowsRelease[0].url.endsWith('.tar.gz')).toBe(true);
});
it('is registered in the distribution factory', () => {
const distribution = getJavaDistribution('oracle-openjdk', {
it('is registered in the distribution factory', async () => {
const distribution = await getJavaDistribution('oracle-openjdk', {
version: '26',
architecture: 'x64',
packageType: 'jdk',
@@ -47,8 +47,11 @@ describe('findPackageForDownload', () => {
let distribution: InstanceType<typeof OracleDistribution>;
let spyDebug: any;
let spyHttpClient: any;
let spyHttpClientGet: any;
let spyCoreError: any;
const ORACLE_CHECKSUM = 'f'.repeat(64);
beforeEach(() => {
distribution = new OracleDistribution({
version: '',
@@ -63,6 +66,14 @@ describe('findPackageForDownload', () => {
// Mock core.error to suppress error logs
spyCoreError = core.error as jest.Mock;
spyCoreError.mockImplementation(() => {});
// Every resolved release fetches its `${url}.sha256` sibling checksum;
// stub it so tests never reach the real network.
spyHttpClientGet = jest.spyOn(HttpClient.prototype, 'get');
spyHttpClientGet.mockResolvedValue({
message: {statusCode: 200},
readBody: async () => ORACLE_CHECKSUM
});
});
it.each([
@@ -131,6 +142,58 @@ 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}});
const result = await distribution['findPackageForDownload']('21');
jest.restoreAllMocks();
expect(result.checksum).toEqual({
algorithm: 'sha256',
value: ORACLE_CHECKSUM,
source: `${result.url}.sha256`
});
expect(spyHttpClientGet).toHaveBeenCalledWith(`${result.url}.sha256`);
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([
@@ -196,6 +259,10 @@ describe('findPackageForDownload with latest', () => {
it('resolves the newest major version from the Adoptium API', async () => {
spyHttpClientHead = jest.spyOn(HttpClient.prototype, 'head');
spyHttpClientHead.mockResolvedValue({message: {statusCode: 200}});
jest.spyOn(HttpClient.prototype, 'get').mockResolvedValue({
message: {statusCode: 200},
readBody: async () => 'f'.repeat(64)
} as any);
const distribution = new OracleDistribution({
version: 'latest',
@@ -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', () => ({
@@ -52,8 +53,10 @@ const utils = await import('../../src/util.js');
describe('getAvailableVersions', () => {
let spyHttpClient: any;
let spyHttpGet: any;
let spyUtilGetDownloadArchiveExtension: any;
let spyCoreError: any;
const archiveChecksum = 'f'.repeat(64);
beforeEach(() => {
spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
@@ -62,6 +65,11 @@ describe('getAvailableVersions', () => {
headers: {},
result: manifestData
});
spyHttpGet = jest.spyOn(HttpClient.prototype, 'get');
spyHttpGet.mockResolvedValue({
message: {statusCode: 200},
readBody: async () => `${archiveChecksum} archive`
});
spyUtilGetDownloadArchiveExtension =
utils.getDownloadArchiveExtension as jest.Mock<any>;
@@ -125,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 (
@@ -149,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', () => {
@@ -282,9 +329,52 @@ describe('getAvailableVersions', () => {
await distribution['findPackageForDownload'](normalizedVersion);
expect(availableVersion).not.toBeNull();
expect(availableVersion.url).toBe(expectedLink);
expect(availableVersion.checksum).toEqual({
algorithm: 'sha256',
value: archiveChecksum,
source: expectedLink.replace(/\.(?:tar\.gz|zip)$/, '.sha256.txt')
});
}
);
it('uses the checksum published beside the selected EA archive', async () => {
const distribution = new SapMachineDistribution({
version: '21-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, 'linux');
const release = await distribution['findPackageForDownload']('21');
expect(spyHttpGet).toHaveBeenCalledWith(
release.url.replace(/\.(?:tar\.gz|zip)$/, '.sha256.txt')
);
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'],
@@ -208,6 +208,14 @@ describe('findPackageForDownload', () => {
distribution['getAvailableVersions'] = async () => manifestData as any;
const resolvedVersion = await distribution['findPackageForDownload'](input);
expect(resolvedVersion.version).toBe(expected);
const vendorPackage = (manifestData as any[]).find(
item => item.version_data.semver === expected
).binaries[0].package;
expect(resolvedVersion.checksum).toEqual({
algorithm: 'sha256',
value: vendorPackage.checksum,
source: vendorPackage.checksum_link
});
});
it('version is found but binaries list is empty', async () => {
@@ -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()
}));
@@ -291,6 +291,7 @@ describe('getAvailableVersions', () => {
it.each([
['amd64', 'x64'],
['arm', 'arm'],
['arm64', 'aarch64']
])(
'defaults to os.arch(): %s mapped to distro arch: %s',
@@ -347,6 +348,14 @@ describe('findPackageForDownload', () => {
const resolvedVersion = await distribution['findPackageForDownload'](input);
expect(resolvedVersion.version).toBe(expected);
expect(resolvedVersion.signatureUrl).toBeDefined();
const vendorPackage = (manifestData as any[]).find(
item => item.version_data.semver === expected
).binaries[0].package;
expect(resolvedVersion.checksum).toEqual({
algorithm: 'sha256',
value: vendorPackage.checksum,
source: vendorPackage.checksum_link
});
});
it('version "latest" is normalized to the newest available version', async () => {
@@ -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';
@@ -241,6 +242,26 @@ describe('getArchitectureOptions', () => {
});
describe('findPackageForDownload', () => {
let spyPackageDetails: any;
const ZULU_CHECKSUM = 'a'.repeat(64);
beforeEach(() => {
// The resolved winning package fetches sha256_hash from the Azul
// package-details endpoint; stub it so tests never reach the real
// network.
spyPackageDetails = jest.spyOn(HttpClient.prototype, 'getJson');
spyPackageDetails.mockResolvedValue({
statusCode: 200,
headers: {},
result: {sha256_hash: ZULU_CHECKSUM}
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it.each([
['8', '8.0.282+8'],
['11.x', '11.0.10+9'],
@@ -279,6 +300,38 @@ describe('findPackageForDownload', () => {
expect(result.url).toBe(
'https://cdn.azul.com/zulu/bin/zulu11.35.15-ca-jdk11.0.5-macosx_x64.tar.gz'
);
expect(result.checksum).toEqual({
algorithm: 'sha256',
value: ZULU_CHECKSUM,
source: 'https://api.azul.com/metadata/v1/zulu/packages/test-uuid-10933'
});
// Only the winning package's UUID triggers a details request.
expect(spyPackageDetails).toHaveBeenCalledWith(
'https://api.azul.com/metadata/v1/zulu/packages/test-uuid-10933'
);
expect(spyPackageDetails).toHaveBeenCalledTimes(1);
});
it('skips checksum verification when sha256_hash is missing or malformed', async () => {
spyPackageDetails.mockResolvedValue({
statusCode: 200,
headers: {},
result: {sha256_hash: 'not-a-valid-digest'}
});
const distribution = new ZuluDistribution({
version: '',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData;
const result = await distribution['findPackageForDownload']('11.0.5');
expect(result.checksum).toBeUndefined();
expect(core.debug).toHaveBeenCalledWith(
expect.stringContaining('No authoritative sha256 checksum')
);
});
it('should throw an error', async () => {
@@ -294,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();
});
});
@@ -245,6 +245,26 @@ describe('getArchitectureOptions', () => {
});
describe('findPackageForDownload', () => {
let spyPackageDetails: any;
const ZULU_CHECKSUM = 'a'.repeat(64);
beforeEach(() => {
// The resolved winning package fetches sha256_hash from the Azul
// package-details endpoint; stub it so tests never reach the real
// network.
spyPackageDetails = jest.spyOn(HttpClient.prototype, 'getJson');
spyPackageDetails.mockResolvedValue({
statusCode: 200,
headers: {},
result: {sha256_hash: ZULU_CHECKSUM}
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it.each([
['8', '8.0.282+8'],
['11.x', '11.0.10+9'],
@@ -283,6 +303,38 @@ describe('findPackageForDownload', () => {
expect(result.url).toBe(
'https://cdn.azul.com/zulu/bin/zulu21.32.17-ca-jdk21.0.2-linux_aarch64.tar.gz'
);
expect(result.checksum).toEqual({
algorithm: 'sha256',
value: ZULU_CHECKSUM,
source: 'https://api.azul.com/metadata/v1/zulu/packages/test-uuid-12447'
});
// Only the winning package's UUID triggers a details request.
expect(spyPackageDetails).toHaveBeenCalledWith(
'https://api.azul.com/metadata/v1/zulu/packages/test-uuid-12447'
);
expect(spyPackageDetails).toHaveBeenCalledTimes(1);
});
it('skips checksum verification when sha256_hash is missing or malformed', async () => {
spyPackageDetails.mockResolvedValue({
statusCode: 200,
headers: {},
result: {}
});
const distribution = new ZuluDistribution({
version: '',
architecture: 'arm64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData;
const result = await distribution['findPackageForDownload']('21.0.2');
expect(result.checksum).toBeUndefined();
expect(core.debug).toHaveBeenCalledWith(
expect.stringContaining('No authoritative sha256 checksum')
);
});
it('should throw an error', async () => {
@@ -242,6 +242,26 @@ describe('getArchitectureOptions', () => {
});
describe('findPackageForDownload', () => {
let spyPackageDetails: any;
const ZULU_CHECKSUM = 'a'.repeat(64);
beforeEach(() => {
// The resolved winning package fetches sha256_hash from the Azul
// package-details endpoint; stub it so tests never reach the real
// network.
spyPackageDetails = jest.spyOn(HttpClient.prototype, 'getJson');
spyPackageDetails.mockResolvedValue({
statusCode: 200,
headers: {},
result: {sha256_hash: ZULU_CHECKSUM}
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it.each([
['8', '8.0.282+8'],
['11.x', '11.0.10+9'],
@@ -280,6 +300,38 @@ describe('findPackageForDownload', () => {
expect(result.url).toBe(
'https://cdn.azul.com/zulu/bin/zulu17.48.15-ca-jdk17.0.10-windows_aarch64.zip'
);
expect(result.checksum).toEqual({
algorithm: 'sha256',
value: ZULU_CHECKSUM,
source: 'https://api.azul.com/metadata/v1/zulu/packages/test-uuid-12446'
});
// Only the winning package's UUID triggers a details request.
expect(spyPackageDetails).toHaveBeenCalledWith(
'https://api.azul.com/metadata/v1/zulu/packages/test-uuid-12446'
);
expect(spyPackageDetails).toHaveBeenCalledTimes(1);
});
it('skips checksum verification when sha256_hash is missing or malformed', async () => {
spyPackageDetails.mockResolvedValue({
statusCode: 200,
headers: {},
result: {sha256_hash: '123'}
});
const distribution = new ZuluDistribution({
version: '',
architecture: 'arm64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData;
const result = await distribution['findPackageForDownload']('17.0.10');
expect(result.checksum).toBeUndefined();
expect(core.debug).toHaveBeenCalledWith(
expect.stringContaining('No authoritative sha256 checksum')
);
});
it('should throw an error', async () => {
+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})
);
});
});
});
+82
View File
@@ -0,0 +1,82 @@
import fs from 'fs';
import path from 'path';
import {
JAVA_PACKAGE_CAPABILITIES,
JavaDistribution
} from '../src/distributions/package-types.js';
const repositoryRoot = process.cwd();
const readRepositoryFile = (filePath: string) =>
fs.readFileSync(path.join(repositoryRoot, filePath), 'utf8');
const allPackageTypes = [
...new Set(Object.values(JAVA_PACKAGE_CAPABILITIES).flat())
];
describe('java-package published contract', () => {
it.each(['action.yml', 'README.md'])(
'documents every supported package type in %s',
filePath => {
const content = readRepositoryFile(filePath);
const contractLine =
filePath === 'action.yml'
? content.match(/ {2}java-package:\n(?: {4}.+\n)+/)?.[0]
: content
.split('\n')
.find(line => line.includes('| `java-package` |'));
expect(contractLine).toBeDefined();
for (const packageType of allPackageTypes) {
expect(contractLine).toContain(`\`${packageType}\``);
}
}
);
it.each(Object.entries(JAVA_PACKAGE_CAPABILITIES))(
'keeps the advanced compatibility table aligned for %s',
(distributionName, packageTypes) => {
const advancedUsage = readRepositoryFile('docs/advanced-usage.md');
const compatibilityTable = advancedUsage.slice(
advancedUsage.indexOf('### Package compatibility')
);
const compatibilityRow = compatibilityTable
.split('\n')
.find(
line =>
line.startsWith('|') && line.includes(`\`${distributionName}\``)
);
expect(compatibilityRow).toBeDefined();
for (const packageType of packageTypes) {
expect(compatibilityRow).toContain(`\`${packageType}\``);
}
}
);
it('only exercises supported distribution/package combinations in E2E', () => {
const workflow = readRepositoryFile('.github/workflows/e2e-versions.yml');
const defaultMatrix = workflow.match(
/distribution:\s*\n\s*\[([^\]]+)\]\s*\n\s*java-package:\s*\['([^']+)'\]/
);
expect(defaultMatrix).not.toBeNull();
const defaultDistributions = [
...defaultMatrix![1].matchAll(/'([^']+)'/g)
].map(match => match[1]);
const defaultPackage = defaultMatrix![2];
for (const distributionName of defaultDistributions) {
expect(supportedPackagesFor(distributionName)).toContain(defaultPackage);
}
const includedPackages = workflow.matchAll(
/- distribution: '([^']+)'\s*\n\s*java-package: ([^\s]+)/g
);
for (const match of includedPackages) {
const [, distributionName, packageType] = match;
expect(supportedPackagesFor(distributionName)).toContain(packageType);
}
});
});
function supportedPackagesFor(distributionName: string): readonly string[] {
return JAVA_PACKAGE_CAPABILITIES[distributionName as JavaDistribution] ?? [];
}
+158
View File
@@ -0,0 +1,158 @@
import fs from 'fs';
import path from 'path';
import {
getJavaPlatformIdentity,
isAlpineLinux,
JAVA_PLATFORM_CAPABILITIES,
normalizeArchitecture,
validateJavaPlatform
} from '../src/distributions/platform-types.js';
import {JavaDistribution} from '../src/distributions/package-types.js';
describe('Java platform capabilities', () => {
it('declares a capability for every distribution', () => {
expect(Object.keys(JAVA_PLATFORM_CAPABILITIES).sort()).toEqual(
Object.values(JavaDistribution).sort()
);
});
it.each([
['x64', 'x64'],
['amd64', 'x64'],
['x86', 'x86'],
['ia32', 'x86'],
['arm', 'armv7'],
['aarch64', 'aarch64'],
['arm64', 'aarch64'],
['ppc64le', 'ppc64le'],
['s390x', 's390x']
])('normalizes architecture %s to %s', (input, expected) => {
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'
);
});
it('rejects OS-specific restrictions with a consistent diagnostic', () => {
expect(() =>
validateJavaPlatform('oracle', 'win32', 'arm64', '21')
).toThrow(
"Distribution 'oracle' does not support operating system 'windows' with architecture 'aarch64' for Java version '21'. Supported combinations: linux (x64, aarch64); macos (x64, aarch64); windows (x64)."
);
});
it('rejects version-dependent architecture restrictions', () => {
expect(() =>
validateJavaPlatform('corretto', 'linux', 'x86', '17')
).toThrow(/x86 \(<12\)/);
expect(() =>
validateJavaPlatform('corretto', 'linux', 'x86', '17.0.2.8.1')
).toThrow(/x86 \(<12\)/);
expect(validateJavaPlatform('corretto', 'linux', 'x86', '11')).toBe('x86');
});
it.each(['corretto', 'kona'])(
'rejects Windows aarch64 for %s',
distributionName => {
expect(() =>
validateJavaPlatform(distributionName, 'win32', 'arm64', '21')
).toThrow(/does not support operating system 'windows'/);
}
);
it('allows local archives on any platform and architecture', () => {
expect(validateJavaPlatform('jdkfile', 'aix', 'mips64', '21')).toBe(
'mips64'
);
});
it('keeps the documented architecture contract aligned', () => {
const repositoryRoot = process.cwd();
const readRepositoryFile = (filePath: string) =>
fs.readFileSync(path.join(repositoryRoot, filePath), 'utf8');
for (const filePath of ['action.yml', 'README.md']) {
const content = readRepositoryFile(filePath);
for (const architecture of [
'x86',
'x64',
'armv7',
'aarch64',
'ppc64le',
'ppc64',
's390x'
]) {
expect(content).toContain(architecture);
}
}
});
it.each(Object.entries(JAVA_PLATFORM_CAPABILITIES))(
'keeps the advanced compatibility table aligned for %s',
(distributionName, capability) => {
const advancedUsage = fs.readFileSync(
path.join(process.cwd(), 'docs/advanced-usage.md'),
'utf8'
);
const compatibilityTable = advancedUsage.slice(
advancedUsage.indexOf('## Platform and architecture compatibility')
);
const compatibilityRow = compatibilityTable
.split('\n')
.find(
line =>
line.startsWith('|') && line.includes(`\`${distributionName}\``)
);
expect(compatibilityRow).toBeDefined();
if (!('platforms' in capability)) {
expect(compatibilityRow).toContain('Any');
return;
}
const architectures = new Set(
Object.values(capability.platforms)
.flat()
.map(item => (typeof item === 'string' ? item : item.architecture))
);
for (const architecture of architectures) {
expect(compatibilityRow).toContain(`\`${architecture}\``);
}
}
);
});
+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();
});
});
});
+56
View File
@@ -0,0 +1,56 @@
import {describe, expect, it, jest} from '@jest/globals';
const mockXmlBuilderFactory = jest.fn();
const mockParse = jest.fn(() => ({
toolchains: {
toolchain: [
{
type: 'foo',
provides: {id: 'custom'},
configuration: {fooHome: '/opt/foo'}
}
]
}
}));
jest.unstable_mockModule('fast-xml-parser', () => {
mockXmlBuilderFactory();
return {
XMLParser: jest.fn().mockImplementation(() => ({
parse: mockParse
}))
};
});
const toolchains = await import('../src/toolchains.js');
describe('Maven XML loading', () => {
it('does not load fast-xml-parser for new toolchains.xml generation', async () => {
const xml = await toolchains.generateToolchainDefinition(
'',
'21',
'temurin',
'temurin_21',
'/opt/java/21'
);
expect(xml).toContain('<id>temurin_21</id>');
expect(mockXmlBuilderFactory).not.toHaveBeenCalled();
expect(mockParse).not.toHaveBeenCalled();
});
it('loads fast-xml-parser for existing toolchains.xml merge generation', async () => {
await expect(
toolchains.generateToolchainDefinition(
'<toolchains><toolchain><type>foo</type></toolchain></toolchains>',
'21',
'temurin',
'temurin_21',
'/opt/java/21'
)
).resolves.toContain('<id>temurin_21</id>');
expect(mockXmlBuilderFactory).toHaveBeenCalledTimes(1);
expect(mockParse).toHaveBeenCalledTimes(1);
});
});
+251
View File
@@ -0,0 +1,251 @@
import {jest, describe, it, expect, beforeEach, afterEach} from '@jest/globals';
import type {IncomingMessage} from 'http';
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn()
}));
const core = await import('@actions/core');
const httpm = await import('@actions/http-client');
const {RetryingHttpClient, isRetryableNetworkError, parseRetryAfter} =
await import('../src/retrying-http-client.js');
function response(
statusCode: number,
retryAfter?: string
): httpm.HttpClientResponse {
return {
message: {
statusCode,
headers: retryAfter ? {'retry-after': retryAfter} : {}
} as IncomingMessage,
readBody: jest.fn(async () => '')
} as unknown as httpm.HttpClientResponse;
}
describe('RetryingHttpClient', () => {
let request: ReturnType<typeof jest.spyOn>;
let sleep: jest.Mock<(delayMs: number) => Promise<void>>;
beforeEach(() => {
request = jest.spyOn(httpm.HttpClient.prototype, 'request');
sleep = jest.fn(async () => undefined);
});
afterEach(() => {
jest.restoreAllMocks();
jest.clearAllMocks();
});
it('uses exponential backoff with jitter for retryable responses', async () => {
request
.mockResolvedValueOnce(response(503))
.mockResolvedValueOnce(response(502))
.mockResolvedValueOnce(response(200));
const client = new RetryingHttpClient('test', {
sleep,
random: () => 0,
baseDelayMs: 1000,
maxDelayMs: 10000
});
await expect(client.get('https://example.com')).resolves.toBeDefined();
expect(request).toHaveBeenCalledTimes(3);
expect(sleep).toHaveBeenNthCalledWith(1, 500);
expect(sleep).toHaveBeenNthCalledWith(2, 1000);
expect(core.info).toHaveBeenNthCalledWith(
1,
'Request attempt 1 of 4 failed (HTTP 503); retrying in 500 ms'
);
expect(core.info).toHaveBeenNthCalledWith(
2,
'Request attempt 2 of 4 failed (HTTP 502); retrying in 1000 ms'
);
});
it('honors Retry-After delta-seconds over the client delay', async () => {
request
.mockResolvedValueOnce(response(429, '3'))
.mockResolvedValueOnce(response(200));
const client = new RetryingHttpClient('test', {
sleep,
random: () => 0
});
await client.get('https://example.com');
expect(sleep).toHaveBeenCalledWith(3000);
});
it('honors Retry-After HTTP dates over the client delay', async () => {
const now = Date.parse('2026-07-29T00:00:00Z');
request
.mockResolvedValueOnce(response(503, new Date(now + 5000).toUTCString()))
.mockResolvedValueOnce(response(200));
const client = new RetryingHttpClient('test', {
sleep,
random: () => 0,
now: () => now
});
await client.get('https://example.com');
expect(sleep).toHaveBeenCalledWith(5000);
});
it('caps Retry-After at the configured maximum delay', async () => {
request
.mockResolvedValueOnce(response(429, '60'))
.mockResolvedValueOnce(response(200));
const client = new RetryingHttpClient('test', {
sleep,
random: () => 0,
maxDelayMs: 10000
});
await client.get('https://example.com');
expect(sleep).toHaveBeenCalledWith(10000);
});
it.each([429, 502, 503, 504, 522])(
'retries HTTP %s responses',
async statusCode => {
request
.mockResolvedValueOnce(response(statusCode))
.mockResolvedValueOnce(response(200));
const client = new RetryingHttpClient('test', {
sleep,
random: () => 0
});
await client.get('https://example.com');
expect(request).toHaveBeenCalledTimes(2);
}
);
it.each(['ETIMEDOUT', 'ECONNRESET', 'ENOTFOUND', 'ECONNREFUSED'])(
'retries network errors with code %s',
async code => {
request
.mockRejectedValueOnce(Object.assign(new Error(code), {code}))
.mockResolvedValueOnce(response(200));
const client = new RetryingHttpClient('test', {
sleep,
random: () => 0
});
await client.get('https://example.com');
expect(request).toHaveBeenCalledTimes(2);
}
);
it('retries retryable aggregate network errors', async () => {
const aggregateError = Object.assign(new Error('connection failed'), {
errors: [Object.assign(new Error('timed out'), {code: 'ETIMEDOUT'})]
});
request
.mockRejectedValueOnce(aggregateError)
.mockResolvedValueOnce(response(200));
const client = new RetryingHttpClient('test', {
sleep,
random: () => 0
});
await client.get('https://example.com');
expect(request).toHaveBeenCalledTimes(2);
expect(sleep).toHaveBeenCalledWith(500);
});
it('does not retry non-retryable responses or network errors', async () => {
request.mockResolvedValueOnce(response(500));
const client = new RetryingHttpClient('test', {sleep});
await expect(client.get('https://example.com')).resolves.toBeDefined();
expect(request).toHaveBeenCalledTimes(1);
expect(sleep).not.toHaveBeenCalled();
request.mockRejectedValueOnce(
Object.assign(new Error('certificate failed'), {code: 'CERT_HAS_EXPIRED'})
);
await expect(client.get('https://example.com')).rejects.toThrow(
'certificate failed'
);
expect(request).toHaveBeenCalledTimes(2);
expect(sleep).not.toHaveBeenCalled();
});
it('stops after the configured total attempt count', async () => {
request
.mockResolvedValueOnce(response(503))
.mockResolvedValueOnce(response(503));
const client = new RetryingHttpClient('test', {
maxAttempts: 2,
sleep,
random: () => 0
});
const finalResponse = await client.get('https://example.com');
expect(finalResponse.message.statusCode).toBe(503);
expect(request).toHaveBeenCalledTimes(2);
expect(sleep).toHaveBeenCalledTimes(1);
});
it('propagates the final network error after exhausting attempts', async () => {
const finalError = Object.assign(new Error('still unavailable'), {
code: 'ECONNREFUSED'
});
request
.mockRejectedValueOnce(
Object.assign(new Error('unavailable'), {code: 'ECONNREFUSED'})
)
.mockRejectedValueOnce(finalError);
const client = new RetryingHttpClient('test', {
maxAttempts: 2,
sleep,
random: () => 0
});
await expect(client.get('https://example.com')).rejects.toBe(finalError);
expect(request).toHaveBeenCalledTimes(2);
expect(sleep).toHaveBeenCalledTimes(1);
});
it('does not retry write requests', async () => {
request.mockResolvedValueOnce(response(503));
const client = new RetryingHttpClient('test', {sleep});
await client.post('https://example.com', '{}');
expect(request).toHaveBeenCalledTimes(1);
expect(sleep).not.toHaveBeenCalled();
});
});
describe('retry classification', () => {
it('parses valid Retry-After values and ignores invalid or past values', () => {
const now = Date.parse('2026-07-29T00:00:00Z');
expect(parseRetryAfter('7', now)).toBe(7000);
expect(parseRetryAfter(new Date(now + 3000).toUTCString(), now)).toBe(3000);
expect(parseRetryAfter(new Date(now - 3000).toUTCString(), now)).toBe(
undefined
);
expect(parseRetryAfter('not-a-date', now)).toBe(undefined);
});
it('recognizes direct and nested retryable network error codes', () => {
expect(isRetryableNetworkError({code: 'ECONNRESET'})).toBe(true);
expect(
isRetryableNetworkError({errors: [{code: 'ENOTFOUND'}, {code: 'OTHER'}]})
).toBe(true);
expect(isRetryableNetworkError({code: 'CERT_HAS_EXPIRED'})).toBe(false);
expect(isRetryableNetworkError(new Error('unknown'))).toBe(false);
});
});
+120
View File
@@ -0,0 +1,120 @@
import {jest, describe, it, expect, beforeEach} from '@jest/globals';
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((value: string) => value),
toWin32Path: jest.fn((value: string) => value),
toPosixPath: jest.fn((value: string) => value)
}));
jest.unstable_mockModule('fs', () => ({
default: {
readFileSync: jest.fn()
}
}));
jest.unstable_mockModule('../src/util.js', () => ({
getBooleanInput: jest.fn(),
getVersionFromFileContent: jest.fn(),
isJdkCacheEnabled: jest.fn()
}));
jest.unstable_mockModule('../src/toolchains.js', () => ({
validateToolchainIds: jest.fn(),
configureToolchains: jest.fn()
}));
jest.unstable_mockModule(
'../src/distributions/distribution-factory.js',
() => ({
getJavaDistribution: jest.fn()
})
);
jest.unstable_mockModule('../src/auth.js', () => ({
configureAuthentication: jest.fn()
}));
jest.unstable_mockModule('../src/maven-args.js', () => ({
configureMavenArgs: jest.fn()
}));
jest.unstable_mockModule('../src/problem-matcher.js', () => ({
configureProblemMatcher: jest.fn()
}));
// These modules should never be imported when `cache` input is empty.
jest.unstable_mockModule('../src/cache-feature.js', () => {
throw new Error('cache-feature module should not be loaded');
});
jest.unstable_mockModule('../src/cache.js', () => {
throw new Error('cache module should not be loaded');
});
const core = await import('@actions/core');
const util = await import('../src/util.js');
const toolchains = await import('../src/toolchains.js');
const factory = await import('../src/distributions/distribution-factory.js');
const {run} = await import('../src/setup-java.js');
describe('setup-java conditional module loading', () => {
const inputs = new Map<string, string>();
const multilineInputs = new Map<string, string[]>();
const booleanInputs = new Map<string, boolean>();
beforeEach(() => {
jest.resetAllMocks();
inputs.clear();
multilineInputs.clear();
booleanInputs.clear();
(core.getInput as jest.Mock).mockImplementation((name: unknown) => {
return inputs.get(name as string) ?? '';
});
(core.getMultilineInput as jest.Mock).mockImplementation(
(name: unknown) => {
return multilineInputs.get(name as string) ?? [];
}
);
(util.getBooleanInput as jest.Mock).mockImplementation(
(name: unknown, defaultValue: unknown) => {
return booleanInputs.get(name as string) ?? defaultValue;
}
);
(util.isJdkCacheEnabled as jest.Mock).mockReturnValue(false);
(toolchains.configureToolchains as jest.Mock).mockResolvedValue(undefined);
});
it('does not import cache modules when cache input is not provided', async () => {
inputs.set('distribution', 'temurin');
multilineInputs.set('java-version', ['21']);
(factory.getJavaDistribution as jest.Mock).mockResolvedValue({
setupJava: jest.fn(async () => ({
version: '21.0.4+7',
path: '/opt/java/21'
}))
});
await run();
expect(core.setFailed).not.toHaveBeenCalled();
});
});
+609
View File
@@ -0,0 +1,609 @@
import {jest, describe, it, expect, beforeEach} from '@jest/globals';
jest.unstable_mockModule('@actions/core', () => ({
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
notice: jest.fn(),
setFailed: jest.fn(),
setOutput: jest.fn(),
getInput: jest.fn(),
getBooleanInput: jest.fn(),
getMultilineInput: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(),
setSecret: jest.fn(),
isDebug: jest.fn(() => false),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn((_name: string, fn: () => Promise<unknown>) => fn()),
toPlatformPath: jest.fn((value: string) => value),
toWin32Path: jest.fn((value: string) => value),
toPosixPath: jest.fn((value: string) => value)
}));
jest.unstable_mockModule('fs', () => ({
default: {
readFileSync: jest.fn()
}
}));
jest.unstable_mockModule('../src/util.js', () => ({
getBooleanInput: jest.fn(),
getVersionFromFileContent: jest.fn(),
isJdkCacheEnabled: jest.fn()
}));
jest.unstable_mockModule('../src/toolchains.js', () => ({
validateToolchainIds: jest.fn(),
configureToolchains: jest.fn()
}));
jest.unstable_mockModule('../src/toolchain-ids.js', () => ({
validateToolchainIds: jest.fn()
}));
jest.unstable_mockModule('../src/cache.js', () => ({
restore: jest.fn()
}));
jest.unstable_mockModule('../src/cache-feature.js', () => ({
isCacheFeatureAvailable: jest.fn()
}));
jest.unstable_mockModule(
'../src/distributions/distribution-factory.js',
() => ({
getJavaDistribution: jest.fn()
})
);
jest.unstable_mockModule('../src/auth.js', () => ({
configureAuthentication: jest.fn()
}));
jest.unstable_mockModule('../src/maven-args.js', () => ({
configureMavenArgs: jest.fn()
}));
jest.unstable_mockModule('../src/problem-matcher.js', () => ({
configureProblemMatcher: jest.fn()
}));
const core = await import('@actions/core');
const fs = (await import('fs')).default;
const util = await import('../src/util.js');
const toolchains = await import('../src/toolchains.js');
const toolchainIds = await import('../src/toolchain-ids.js');
const cache = await import('../src/cache.js');
const cacheFeature = await import('../src/cache-feature.js');
const factory = await import('../src/distributions/distribution-factory.js');
const auth = await import('../src/auth.js');
const mavenArgs = await import('../src/maven-args.js');
const problemMatcher = await import('../src/problem-matcher.js');
const {run} = await import('../src/setup-java.js');
const inputCallsOnImport = (core.getInput as jest.Mock).mock.calls.length;
const multilineInputCallsOnImport = (core.getMultilineInput as jest.Mock).mock
.calls.length;
describe('setup action orchestration', () => {
const inputs = new Map<string, string>();
const multilineInputs = new Map<string, string[]>();
const booleanInputs = new Map<string, boolean>();
beforeEach(() => {
jest.resetAllMocks();
inputs.clear();
multilineInputs.clear();
booleanInputs.clear();
(core.getInput as jest.Mock).mockImplementation((name: unknown) => {
return inputs.get(name as string) ?? '';
});
(core.getMultilineInput as jest.Mock).mockImplementation(
(name: unknown) => {
return multilineInputs.get(name as string) ?? [];
}
);
(util.getBooleanInput as jest.Mock).mockImplementation(
(name: unknown, defaultValue: unknown) => {
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
);
(toolchains.configureToolchains as jest.Mock).mockResolvedValue(undefined);
(auth.configureAuthentication as jest.Mock).mockResolvedValue(undefined);
(cache.restore as jest.Mock).mockResolvedValue(undefined);
});
it('does not execute the action when imported', () => {
expect(inputCallsOnImport).toBe(0);
expect(multilineInputCallsOnImport).toBe(0);
});
it('requires java-version or java-version-file', async () => {
await run();
expect(core.setFailed).toHaveBeenCalledWith(
'java-version or java-version-file input expected'
);
expect(factory.getJavaDistribution).not.toHaveBeenCalled();
expect(problemMatcher.configureProblemMatcher).not.toHaveBeenCalled();
});
it('requires distribution when java-version is provided', async () => {
multilineInputs.set('java-version', ['21']);
await run();
expect(core.setFailed).toHaveBeenCalledWith(
'distribution input is required'
);
expect(factory.getJavaDistribution).not.toHaveBeenCalled();
});
it('requires distribution when it cannot be inferred from the version file', async () => {
inputs.set('java-version-file', '.java-version');
(fs.readFileSync as jest.Mock).mockReturnValue(Buffer.from('21'));
(util.getVersionFromFileContent as jest.Mock).mockReturnValue({
version: '21'
});
await run();
expect(core.setFailed).toHaveBeenCalledWith(
'distribution input is required when not specified in the version file'
);
expect(factory.getJavaDistribution).not.toHaveBeenCalled();
});
it('fails when the version file has no supported version', async () => {
inputs.set('java-version-file', '.java-version');
inputs.set('distribution', 'temurin');
(fs.readFileSync as jest.Mock).mockReturnValue(Buffer.from('invalid'));
(util.getVersionFromFileContent as jest.Mock).mockReturnValue(undefined);
await run();
expect(core.setFailed).toHaveBeenCalledWith(
'No supported version was found in file .java-version'
);
expect(factory.getJavaDistribution).not.toHaveBeenCalled();
});
it('uses the distribution inferred from a version file', async () => {
inputs.set('java-version-file', '.sdkmanrc');
inputs.set('architecture', 'x64');
inputs.set('java-package', 'jdk');
inputs.set('distribution', 'zulu');
inputs.set('jdk-file', '/tmp/java.tar.gz');
multilineInputs.set('mvn-toolchain-id', ['file-jdk']);
booleanInputs.set('check-latest', true);
booleanInputs.set('force-download', true);
booleanInputs.set('set-default', false);
booleanInputs.set('verify-signature', true);
inputs.set('verify-signature-public-key', 'public-key');
(fs.readFileSync as jest.Mock).mockReturnValue(
Buffer.from('java=21.0.5-tem')
);
(util.getVersionFromFileContent as jest.Mock).mockReturnValue({
version: '21.0.5',
distribution: 'temurin'
});
const setupJava = jest.fn(async () => ({
version: '21.0.5+11',
path: '/opt/java/21'
}));
(factory.getJavaDistribution as jest.Mock).mockReturnValue({setupJava});
await run();
expect(util.getVersionFromFileContent).toHaveBeenCalledWith(
'java=21.0.5-tem',
'zulu',
'.sdkmanrc'
);
expect(factory.getJavaDistribution).toHaveBeenCalledWith(
'temurin',
{
version: '21.0.5',
architecture: 'x64',
packageType: 'jdk',
checkLatest: true,
forceDownload: true,
cacheJdk: false,
setDefault: false,
verifySignature: true,
verifySignaturePublicKey: 'public-key'
},
'/tmp/java.tar.gz'
);
expect(toolchainIds.validateToolchainIds).toHaveBeenCalledWith(
[],
'.sdkmanrc',
['file-jdk']
);
expect(toolchains.configureToolchains).toHaveBeenCalledWith(
'21.0.5',
'temurin',
'/opt/java/21',
'file-jdk'
);
expect(core.setFailed).not.toHaveBeenCalled();
});
it('installs multiple JDKs in order with matching toolchain IDs', async () => {
inputs.set('distribution', 'temurin');
inputs.set('architecture', 'x64');
inputs.set('java-package', 'jdk');
multilineInputs.set('java-version', ['17', '21']);
multilineInputs.set('mvn-toolchain-id', ['java-17', 'java-21']);
const setupJava17 = jest.fn(async () => ({
version: '17.0.12+7',
path: '/opt/java/17'
}));
const setupJava21 = jest.fn(async () => ({
version: '21.0.4+7',
path: '/opt/java/21'
}));
(factory.getJavaDistribution as jest.Mock)
.mockReturnValueOnce({setupJava: setupJava17})
.mockReturnValueOnce({setupJava: setupJava21});
await run();
expect(factory.getJavaDistribution).toHaveBeenNthCalledWith(
1,
'temurin',
expect.objectContaining({version: '17'}),
''
);
expect(factory.getJavaDistribution).toHaveBeenNthCalledWith(
2,
'temurin',
expect.objectContaining({version: '21'}),
''
);
expect(toolchains.configureToolchains).toHaveBeenNthCalledWith(
1,
'17',
'temurin',
'/opt/java/17',
'java-17'
);
expect(toolchains.configureToolchains).toHaveBeenNthCalledWith(
2,
'21',
'temurin',
'/opt/java/21',
'java-21'
);
expect(setupJava17.mock.invocationCallOrder[0]).toBeLessThan(
setupJava21.mock.invocationCallOrder[0]
);
});
it('uses the resolved version for the latest Maven toolchain', async () => {
inputs.set('distribution', 'temurin');
multilineInputs.set('java-version', ['latest']);
const setupJava = jest.fn(async () => ({
version: '24.0.2+12',
path: '/opt/java/24'
}));
(factory.getJavaDistribution as jest.Mock).mockReturnValue({setupJava});
await run();
expect(toolchains.configureToolchains).toHaveBeenCalledWith(
'24.0.2+12',
'temurin',
'/opt/java/24',
undefined
);
});
it('starts cache restoration before post-install steps and awaits it before finishing', async () => {
inputs.set('distribution', 'temurin');
inputs.set('cache', 'maven');
inputs.set('cache-dependency-path', '**/pom.xml');
multilineInputs.set('java-version', ['21']);
multilineInputs.set('cache-path', [
'/custom/maven/repository',
'!/custom/maven/repository/excluded'
]);
const cacheRestore = deferred<void>();
let resolveSetupJava: (() => void) | undefined;
const setupJava = jest.fn(
() =>
new Promise<{version: string; path: string}>(resolve => {
resolveSetupJava = () =>
resolve({
version: '21.0.4+7',
path: '/opt/java/21'
});
})
);
(cache.restore as jest.Mock).mockReturnValue(cacheRestore.promise);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({setupJava});
const runPromise = run();
try {
await tick();
expect(cacheFeature.isCacheFeatureAvailable).toHaveBeenCalled();
expect(cache.restore).toHaveBeenCalledWith('maven', '**/pom.xml', [
'/custom/maven/repository',
'!/custom/maven/repository/excluded'
]);
expect(toolchains.configureToolchains).not.toHaveBeenCalled();
resolveSetupJava?.();
await tick();
expect(problemMatcher.configureProblemMatcher).toHaveBeenCalledWith(
expect.stringMatching(/\.github[/\\]java\.json$/)
);
expect(
(problemMatcher.configureProblemMatcher as jest.Mock).mock
.invocationCallOrder[0]
).toBeLessThan(
(auth.configureAuthentication as jest.Mock).mock.invocationCallOrder[0]
);
expect(
(problemMatcher.configureProblemMatcher as jest.Mock).mock
.invocationCallOrder[0]
).toBeLessThan(
(toolchains.configureToolchains as jest.Mock).mock
.invocationCallOrder[0]
);
expect(
(auth.configureAuthentication as jest.Mock).mock.invocationCallOrder[0]
).toBeLessThan(
(mavenArgs.configureMavenArgs as jest.Mock).mock.invocationCallOrder[0]
);
expect(
(toolchains.configureToolchains as jest.Mock).mock
.invocationCallOrder[0]
).toBeLessThan(
(mavenArgs.configureMavenArgs as jest.Mock).mock.invocationCallOrder[0]
);
let completed = false;
runPromise.then(() => {
completed = true;
});
await tick();
expect(completed).toBe(false);
} finally {
resolveSetupJava?.();
cacheRestore.resolve();
await runPromise;
}
expect(core.setFailed).not.toHaveBeenCalled();
});
it('overlaps independent Maven settings and toolchains configuration', async () => {
inputs.set('distribution', 'temurin');
multilineInputs.set('java-version', ['21']);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({
setupJava: jest.fn(async () => ({
version: '21.0.4+7',
path: '/opt/java/21'
}))
});
const authentication = deferred<void>();
const toolchainConfiguration = deferred<void>();
(auth.configureAuthentication as jest.Mock).mockReturnValue(
authentication.promise
);
(toolchains.configureToolchains as jest.Mock).mockReturnValue(
toolchainConfiguration.promise
);
const runPromise = run();
try {
await tick();
await tick();
expect(auth.configureAuthentication).toHaveBeenCalled();
expect(toolchains.configureToolchains).toHaveBeenCalledWith(
'21',
'temurin',
'/opt/java/21',
undefined
);
expect(mavenArgs.configureMavenArgs).not.toHaveBeenCalled();
authentication.resolve();
await tick();
expect(mavenArgs.configureMavenArgs).not.toHaveBeenCalled();
toolchainConfiguration.resolve();
await runPromise;
} finally {
authentication.resolve();
toolchainConfiguration.resolve();
await runPromise;
}
expect(mavenArgs.configureMavenArgs).toHaveBeenCalled();
expect(core.setFailed).not.toHaveBeenCalled();
});
it('skips cache restoration when the cache feature is unavailable', async () => {
inputs.set('distribution', 'temurin');
inputs.set('cache', 'maven');
multilineInputs.set('java-version', ['21']);
(cacheFeature.isCacheFeatureAvailable as jest.Mock).mockReturnValue(false);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({
setupJava: jest.fn(async () => ({
version: '21.0.4+7',
path: '/opt/java/21'
}))
});
await run();
expect(cache.restore).not.toHaveBeenCalled();
});
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',
path: '/opt/java/21'
}))
});
await run();
expect(cacheFeature.isCacheFeatureAvailable).not.toHaveBeenCalled();
expect(cache.restore).not.toHaveBeenCalled();
expect(factory.getJavaDistribution).toHaveBeenCalledWith(
'temurin',
expect.objectContaining({cacheJdk: false}),
''
);
});
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']);
(factory.getJavaDistribution as jest.Mock).mockReturnValue(null);
await run();
expect(core.setFailed).toHaveBeenCalledWith(
'No supported distribution was found for input unsupported'
);
expect(toolchains.configureToolchains).not.toHaveBeenCalled();
expect(problemMatcher.configureProblemMatcher).not.toHaveBeenCalled();
});
it('reports collaborator failures and stops post-install configuration', async () => {
inputs.set('distribution', 'temurin');
multilineInputs.set('java-version', ['21']);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({
setupJava: jest.fn(async () => {
throw new Error('download failed');
})
});
await run();
expect(core.setFailed).toHaveBeenCalledWith('download failed');
expect(toolchains.configureToolchains).not.toHaveBeenCalled();
expect(problemMatcher.configureProblemMatcher).not.toHaveBeenCalled();
expect(auth.configureAuthentication).not.toHaveBeenCalled();
expect(mavenArgs.configureMavenArgs).not.toHaveBeenCalled();
expect(cache.restore).not.toHaveBeenCalled();
});
it('reports post-install failures and skips later collaborators', async () => {
inputs.set('distribution', 'temurin');
inputs.set('cache', 'maven');
multilineInputs.set('java-version', ['21']);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({
setupJava: jest.fn(async () => ({
version: '21.0.4+7',
path: '/opt/java/21'
}))
});
(auth.configureAuthentication as jest.Mock).mockRejectedValue(
new Error('authentication failed')
);
await run();
expect(problemMatcher.configureProblemMatcher).toHaveBeenCalled();
expect(core.setFailed).toHaveBeenCalledWith('authentication failed');
expect(mavenArgs.configureMavenArgs).not.toHaveBeenCalled();
expect(cache.restore).toHaveBeenCalled();
});
it('keeps Java setup errors deterministic when cache restore also fails', async () => {
inputs.set('distribution', 'temurin');
inputs.set('cache', 'maven');
multilineInputs.set('java-version', ['21']);
(factory.getJavaDistribution as jest.Mock).mockReturnValue({
setupJava: jest.fn(async () => {
throw new Error('download failed');
})
});
(cache.restore as jest.Mock).mockRejectedValue(
new Error('cache restore failed')
);
await run();
expect(core.setFailed).toHaveBeenCalledWith('download failed');
});
});
function deferred<T>() {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return {promise, resolve, reject};
}
async function tick() {
await new Promise(resolve => setTimeout(resolve, 0));
}
+201 -24
View File
@@ -13,6 +13,7 @@ import * as fs from 'fs';
import os from 'os';
import * as path from 'path';
import * as io from '@actions/io';
import {XMLParser} from 'fast-xml-parser';
// Mock @actions/core before importing source modules that depend on it
jest.unstable_mockModule('@actions/core', () => ({
@@ -95,7 +96,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(altHome)).toBe(true);
expect(fs.existsSync(altToolchainsFile)).toBe(true);
expect(fs.readFileSync(altToolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
@@ -140,7 +141,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
@@ -149,7 +150,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
@@ -221,7 +222,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -230,7 +231,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -306,7 +307,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -315,7 +316,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -383,7 +384,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -392,7 +393,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -453,7 +454,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -462,7 +463,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -545,7 +546,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -554,7 +555,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -604,7 +605,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -613,7 +614,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -662,7 +663,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -671,7 +672,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -745,7 +746,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -754,7 +755,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -824,7 +825,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -833,7 +834,7 @@ describe('toolchains tests', () => {
)
);
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
@@ -888,7 +889,7 @@ describe('toolchains tests', () => {
expect(updated).toContain(`<jdkHome>${jdkInfo.jdkHome}</jdkHome>`);
}, 100000);
it('generates valid toolchains.xml with minimal configuration', () => {
it('generates valid toolchains.xml with minimal configuration', async () => {
const jdkInfo = {
version: 'JAVA_VERSION',
vendor: 'JAVA_VENDOR',
@@ -914,7 +915,7 @@ describe('toolchains tests', () => {
</toolchains>`;
expect(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
@@ -924,6 +925,29 @@ describe('toolchains tests', () => {
).toEqual(expectedToolchains);
}, 100000);
it('escapes new toolchains.xml values while preserving parsed semantics', () => {
const jdkInfo = {
version: `21&<>"'é`,
vendor: `Temurin&<>"'é`,
id: `temurin&<>"'é`,
jdkHome: `/opt/java&<>"'é`
};
const xml = toolchains.generateNewToolchainDefinition(
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
);
const parsed = parseXmlObject(xml) as any;
expect(parsed.toolchains.toolchain[0].type).toBe('jdk');
expect(xmlElementText(xml, 'version')).toBe(jdkInfo.version);
expect(xmlElementText(xml, 'vendor')).toBe(jdkInfo.vendor);
expect(xmlElementText(xml, 'id')).toBe(jdkInfo.id);
expect(xmlElementText(xml, 'jdkHome')).toBe(jdkInfo.jdkHome);
});
it('creates toolchains.xml with correct id when none is supplied', async () => {
const version = '17';
const distributionName = 'temurin';
@@ -946,7 +970,7 @@ describe('toolchains tests', () => {
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
await toolchains.generateToolchainDefinition(
'',
version,
distributionName,
@@ -956,6 +980,75 @@ describe('toolchains tests', () => {
);
}, 100000);
it('merges a second JDK into a toolchains.xml produced by the new-file fast path', async () => {
const firstJdk = {
version: '17',
vendor: 'temurin',
id: 'temurin_17',
jdkHome: '/opt/java/17'
};
const secondJdk = {
version: '21',
vendor: 'temurin',
id: 'temurin_21',
jdkHome: '/opt/java/21'
};
const firstToolchains = await toolchains.generateToolchainDefinition(
'',
firstJdk.version,
firstJdk.vendor,
firstJdk.id,
firstJdk.jdkHome
);
const mergedToolchains = await toolchains.generateToolchainDefinition(
firstToolchains,
secondJdk.version,
secondJdk.vendor,
secondJdk.id,
secondJdk.jdkHome
);
for (const jdk of [firstJdk, secondJdk]) {
expect(mergedToolchains).toContain(`<id>${jdk.id}</id>`);
expect(mergedToolchains).toContain(`<jdkHome>${jdk.jdkHome}</jdkHome>`);
}
expect((mergedToolchains.match(/<toolchain>/g) || []).length).toBe(2);
});
it('preserves custom attributes and elements when merging existing toolchains.xml', async () => {
const originalFile = `<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.0.0" customRoot="A &amp; B">
<toolchain customAttr="custom &amp; value">
<type>foo</type>
<provides customProvides="yes">
<custom attr="custom &quot; attr">baz &amp; qux</custom>
</provides>
<configuration>
<fooHome>/usr/local/bin/foo</fooHome>
</configuration>
</toolchain>
</toolchains>`;
const mergedToolchains = await toolchains.generateToolchainDefinition(
originalFile,
'21&<>"\'',
'Temurin&<>"\'',
'temurin_21&<>"\'',
'/opt/java/21&<>"\''
);
const parsed = parseXmlObject(mergedToolchains) as any;
const merged = parsed.toolchains.toolchain;
expect(parsed.toolchains['@customRoot']).toBe('A & B');
expect(merged).toHaveLength(2);
expect(merged[0].provides.id).toBe('temurin_21&<>"\'');
expect(merged[0].configuration.jdkHome).toBe('/opt/java/21&<>"\'');
expect(merged[1]['@customAttr']).toBe('custom & value');
expect(merged[1].provides['@customProvides']).toBe('yes');
expect(merged[1].provides.custom['#text']).toBe('baz & qux');
expect(merged[1].provides.custom['@attr']).toBe('custom " attr');
});
it('preserves toolchains from previous executions across multiple setup-java runs', async () => {
// Regression test for https://github.com/actions/setup-java/issues/1099
// Running setup-java several times in the same job (e.g. multiple steps / multiple
@@ -1007,3 +1100,87 @@ describe('toolchains tests', () => {
expect((contents.match(/<toolchain>/g) || []).length).toBe(runs.length);
}, 100000);
});
describe('validateToolchainIds', () => {
it.each([
{
name: 'uses generated IDs when no custom IDs are supplied',
versions: ['17', '21'],
versionFile: '',
toolchainIds: []
},
{
name: 'accepts one custom ID for a single Java version',
versions: ['21'],
versionFile: '',
toolchainIds: ['custom-21']
},
{
name: 'accepts one custom ID per Java version',
versions: ['17', '21'],
versionFile: '',
toolchainIds: ['custom-17', 'custom-21']
},
{
name: 'accepts one custom ID with java-version-file',
versions: [],
versionFile: '.java-version',
toolchainIds: ['custom-file-version']
}
])('$name', ({versions, versionFile, toolchainIds}) => {
expect(() =>
toolchains.validateToolchainIds(versions, versionFile, toolchainIds)
).not.toThrow();
});
it.each([
{
name: 'rejects fewer IDs than Java versions',
versions: ['17', '21'],
versionFile: '',
toolchainIds: ['custom-17'],
expectedMessage:
'The number of Maven toolchain IDs (1) must match the number of Java versions (2)'
},
{
name: 'rejects extra IDs for a single Java version',
versions: ['21'],
versionFile: '',
toolchainIds: ['custom-21', 'custom-extra'],
expectedMessage:
'The number of Maven toolchain IDs (2) must match the number of Java versions (1)'
},
{
name: 'rejects extra IDs with java-version-file',
versions: [],
versionFile: '.java-version',
toolchainIds: ['custom-file-version', 'custom-extra'],
expectedMessage:
'The number of Maven toolchain IDs (2) must match the number of Java versions (1)'
}
])('$name', ({versions, versionFile, toolchainIds, expectedMessage}) => {
expect(() =>
toolchains.validateToolchainIds(versions, versionFile, toolchainIds)
).toThrow(expectedMessage);
});
});
function xmlElementText(xml: string, tagName: string): string {
const match = new RegExp(`<${tagName}>([\\s\\S]*?)</${tagName}>`).exec(xml);
expect(match).not.toBeNull();
return (parseXmlObject(`<value>${match?.[1]}</value>`) as {value: string})
.value;
}
function parseXmlObject(xml: string): unknown {
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@',
textNodeName: '#text',
parseAttributeValue: false,
parseTagValue: false,
trimValues: true,
isArray: tagName => tagName === 'toolchain'
});
return parser.parse(xml);
}
+508
View File
@@ -0,0 +1,508 @@
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('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);
});
});
+97 -54
View File
@@ -13,13 +13,6 @@ import * as path from 'path';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Mock @actions/cache
jest.unstable_mockModule('@actions/cache', () => ({
isFeatureAvailable: jest.fn(),
saveCache: jest.fn(),
restoreCache: jest.fn()
}));
// Mock @actions/core
jest.unstable_mockModule('@actions/core', () => ({
getInput: jest.fn(),
@@ -46,7 +39,6 @@ jest.unstable_mockModule('@actions/core', () => ({
toPosixPath: jest.fn((p: string) => p)
}));
const cache = await import('@actions/cache');
const core = await import('@actions/core');
const {
@@ -54,12 +46,107 @@ const {
getNextPageUrlFromLinkHeader,
getVersionFromFileContent,
isVersionSatisfies,
isCacheFeatureAvailable,
isGhes,
validatePaginationUrl,
getLatestMajorVersion
getLatestMajorVersion,
getBooleanInput,
isJdkCacheEnabled
} = await import('../src/util.js');
describe('getBooleanInput', () => {
let inputs: Record<string, string>;
beforeEach(() => {
inputs = {};
(core.getInput as jest.Mock).mockImplementation(
(name: string) => inputs[name] ?? ''
);
});
afterEach(() => {
jest.resetAllMocks();
});
it.each([
['true', true],
['TRUE', true],
['TrUe', true],
[' true ', true],
['false', false],
['FALSE', false],
['FaLsE', false],
[' false ', false]
])('parses %j as %s', (value: string, expected: boolean) => {
inputs['boolean-input'] = value;
expect(getBooleanInput('boolean-input')).toBe(expected);
});
it.each([
[undefined, false],
[false, false],
[true, true]
])(
'uses the configured default %s when the input is omitted',
(defaultValue: boolean | undefined, expected: boolean) => {
expect(getBooleanInput('boolean-input', defaultValue)).toBe(expected);
}
);
it('uses the configured default for a whitespace-only input', () => {
inputs['boolean-input'] = ' ';
expect(getBooleanInput('boolean-input', true)).toBe(true);
});
it.each([
'check-latest',
'force-download',
'set-default',
'verify-signature',
'overwrite-settings',
'show-download-progress',
'problem-matcher'
])('rejects an invalid value for %s', inputName => {
inputs[inputName] = 'ture';
expect(() => getBooleanInput(inputName)).toThrow(
`Invalid value 'ture' for boolean input '${inputName}'. Expected 'true' or 'false'.`
);
});
});
describe('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],
@@ -88,50 +175,6 @@ describe('isVersionSatisfies', () => {
);
});
describe('isCacheFeatureAvailable', () => {
it('isCacheFeatureAvailable disabled on GHES', () => {
(cache.isFeatureAvailable as jest.Mock<any>).mockImplementation(
() => false
);
const infoMock = core.warning as jest.Mock;
const message =
'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.';
try {
process.env['GITHUB_SERVER_URL'] = 'http://example.com';
expect(isCacheFeatureAvailable()).toBeFalsy();
expect(infoMock).toHaveBeenCalledWith(message);
} finally {
delete process.env['GITHUB_SERVER_URL'];
}
});
it('isCacheFeatureAvailable disabled on dotcom', () => {
(cache.isFeatureAvailable as jest.Mock<any>).mockImplementation(
() => false
);
const infoMock = core.warning as jest.Mock;
const message =
'The runner was not able to contact the cache service. Caching will be skipped';
try {
process.env['GITHUB_SERVER_URL'] = 'http://github.com';
expect(isCacheFeatureAvailable()).toBe(false);
expect(infoMock).toHaveBeenCalledWith(message);
} finally {
delete process.env['GITHUB_SERVER_URL'];
}
});
it('isCacheFeatureAvailable is enabled', () => {
(cache.isFeatureAvailable as jest.Mock<any>).mockImplementation(() => true);
expect(isCacheFeatureAvailable()).toBe(true);
});
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
});
});
describe('convertVersionToSemver', () => {
it.each([
['12', '12'],
+17
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,21 @@ if [ -z "$GREP_RESULT" ]; then
exit 1
fi
if [ -n "$SETUP_JAVA_VERSION" ]; then
OUTPUT_JAVA_VERSION=$(echo "$SETUP_JAVA_VERSION" | cut -d'+' -f1)
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"
+14 -4
View File
@@ -13,11 +13,11 @@ inputs:
description: 'Java distribution. See the list of supported distributions in README file. This input is required except when java-version-file points to .sdkmanrc with a recognized distribution suffix (e.g., java=21.0.5-tem).'
required: false
java-package:
description: 'The package type (jdk, jre, jdk+fx, jre+fx, jdk+crac, jre+crac, jdk+jmods)'
description: 'The package type (`jdk`, `jre`, `jdk+fx`, `jre+fx`, `jdk+crac`, `jre+crac`, `jdk+jmods`, `jdk+jcef`, `jre+jcef`, `jdk+ft`, or `jre+ft`). Supported values vary by distribution.'
required: false
default: 'jdk'
architecture:
description: "The architecture of the package (defaults to the action runner's architecture)"
description: "The architecture of the package (`x86`, `x64`, `armv7`, `aarch64`, `ppc64le`, `ppc64`, or `s390x`). Aliases `ia32`, `amd64`, `arm`, and `arm64` are normalized to `x86`, `x64`, `armv7`, and `aarch64`. Supported values vary by distribution and operating system. Defaults to the action runner's architecture."
required: false
jdk-file:
description: 'Path to where the compressed JDK is located'
@@ -72,7 +72,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,9 +84,19 @@ 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
cache-path:
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 caches without saving cache changes in the post action.'
required: false
default: false
job-status:
description: 'Workaround to pass job status to post job step. This variable is not intended for manual setting'
required: false
@@ -96,7 +106,7 @@ inputs:
required: false
default: ${{ github.server_url == 'https://github.com' && github.token || '' }}
mvn-toolchain-id:
description: 'Name of Maven Toolchain ID if the default name of "${distribution}_${java-version}" is not wanted. See examples of supported syntax in Advanced Usage file'
description: 'Name of Maven Toolchain ID if the default name of "${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);
}
/***/ })
};
+356
View File
@@ -0,0 +1,356 @@
export const id = 377;
export const ids = [377];
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 export 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__(5767);
/* 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-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 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: ');
}
/***/ })
};
+62560
View File
File diff suppressed because it is too large Load Diff
+2690 -64844
View File
File diff suppressed because it is too large Load Diff
+164
View File
@@ -0,0 +1,164 @@
export const id = 126;
export const ids = [126];
export const modules = {
/***/ 4126:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CorrettoDistribution: () => (/* binding */ CorrettoDistribution)
/* 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 _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);
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_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Corretto', installerOptions);
}
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 extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .renameWinArchive */ .n2)(javaArchivePath);
}
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 (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(version) {
if (!this.stable) {
throw new Error('Early access versions are not supported');
}
const availableVersions = await this.getAvailableVersions();
// The `latest` alias is normalized to the SemVer wildcard, but Corretto
// matches on an exact major version, so resolve it to the newest available
// major from Corretto's own list.
if (this.latest) {
const majors = availableVersions
.map(item => parseInt(item.version, 10))
.filter(major => Number.isFinite(major) && major > 0);
if (majors.length === 0) {
throw new Error('Could not determine the latest available Corretto major version from remote metadata');
}
version = Math.max(...majors).toString();
}
if (version.includes('.')) {
throw new Error('Only major versions are supported');
}
const matchingVersions = availableVersions
.filter(item => item.version == version)
.map(item => {
return {
version: (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .convertVersionToSemver */ .ZY)(item.correttoVersion),
url: item.downloadLink,
checksum: {
algorithm: 'sha256',
value: item.checksum_sha256,
source: CORRETTO_VERSIONS_URL
}
};
});
const resolvedVersion = matchingVersions.length > 0 ? matchingVersions[0] : null;
if (!resolvedVersion) {
const availableVersionStrings = availableVersions.map(item => item.version);
throw this.createVersionNotFoundError(version, availableVersionStrings);
}
return resolvedVersion;
}
async getAvailableVersions() {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
const imageType = this.packageType;
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
console.time('Retrieving available versions for Corretto took'); // eslint-disable-line no-console
}
const fetchCurrentVersions = await this.http.getJson(CORRETTO_VERSIONS_URL);
const fetchedCurrentVersions = fetchCurrentVersions.result;
if (!fetchedCurrentVersions) {
throw Error(`Could not fetch latest corretto versions from ${CORRETTO_VERSIONS_URL}`);
}
const eligibleVersions = fetchedCurrentVersions?.[platform]?.[arch]?.[imageType];
const availableVersions = this.getAvailableVersionsForPlatform(eligibleVersions);
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .startGroup */ .Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for Corretto took'); // eslint-disable-line no-console
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Available versions: [${availableVersions.length}]`);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(availableVersions
.map(item => `${item.version}: ${item.correttoVersion}`)
.join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .endGroup */ .N4();
}
return availableVersions;
}
getAvailableVersionsForPlatform(eligibleVersions) {
const availableVersions = [];
for (const version in eligibleVersions) {
const availableVersion = eligibleVersions[version];
for (const fileType in availableVersion) {
const skipNonExtractableBinaries = fileType != (0,_util_js__WEBPACK_IMPORTED_MODULE_3__/* .getDownloadArchiveExtension */ .ag)();
if (skipNonExtractableBinaries) {
continue;
}
const availableVersionDetails = availableVersion[fileType];
const correttoVersion = this.getCorrettoVersion(availableVersionDetails.resource);
availableVersions.push({
checksum: availableVersionDetails.checksum,
checksum_sha256: availableVersionDetails.checksum_sha256,
fileType,
resource: availableVersionDetails.resource,
downloadLink: `https://corretto.aws${availableVersionDetails.resource}`,
version: version,
correttoVersion
});
}
}
return availableVersions;
}
getPlatformOption() {
// Corretto has its own platform names so we need to map them
switch (process.platform) {
case 'darwin':
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;
}
}
distributionArchitecture() {
const architecture = super.distributionArchitecture();
return architecture === 'armv7' ? 'arm' : architecture;
}
getCorrettoVersion(resource) {
const regex = /(\d+.+)\//;
const match = regex.exec(resource);
if (match === null) {
throw Error(`Could not parse corretto version from ${resource}`);
}
return match[1];
}
}
/***/ })
};
+155
View File
@@ -0,0 +1,155 @@
export const id = 151;
export const ids = [151];
export const modules = {
/***/ 8151:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ KonaDistribution: () => (/* binding */ KonaDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* 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);
const KONA_RELEASES_URL = 'https://tencent.github.io/konajdk/releases/kona-v1.json';
class KonaDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Kona', installerOptions);
}
async downloadTool(javaRelease) {
_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_5__/* .getDownloadArchiveExtension */ .ag)();
const archivePath = process.platform === 'win32'
? (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .renameWinArchive */ .n2)(javaArchivePath)
: javaArchivePath;
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 (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .cacheJdkDir */ .Vj)(jdkDirectory, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(version) {
if (!this.stable) {
throw new Error('Kona provides stable releases only');
}
if (this.packageType !== 'jdk') {
throw new Error('Kona provides jdk only');
}
const availableReleases = await this.getAvailableReleases();
const releases = availableReleases
.filter(item => {
return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(version, item.version);
})
.map(item => {
return {
version: item.version,
url: item.downloadUrl,
checksum: item.checksum
? {
algorithm: 'sha256',
value: item.checksum,
source: KONA_RELEASES_URL
}
: undefined
};
})
.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()}".`);
}
return releases[0];
}
async getAvailableReleases() {
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
console.time('Retrieving available releases for Kona took'); // eslint-disable-line no-console
}
const releaseInfo = await this.fetchReleaseInfo();
if (!releaseInfo) {
throw new Error(`Couldn't fetch Kona release information`);
}
const availableReleases = this.chooseReleases(this.getOs(), this.getArch(), releaseInfo);
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .startGroup */ .Oh('Print information about available releases');
console.timeEnd('Retrieving available releases for Kona took'); // eslint-disable-line no-console
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(availableReleases.map(item => item.version).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .endGroup */ .N4();
}
return availableReleases;
}
async fetchReleaseInfo() {
try {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Fetching Kona release info from URL: ${KONA_RELEASES_URL}`);
return (await this.http.getJson(KONA_RELEASES_URL))
.result;
}
catch (err) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Fetching Kona release info from the URL: ${KONA_RELEASES_URL} failed with the error: ${err.message}`);
return null;
}
}
chooseReleases(os, arch, releaseInfo) {
const releases = [];
for (const majorVersion in releaseInfo) {
const versions = releaseInfo[majorVersion];
for (const version of versions) {
if (!version.latest) {
continue;
}
for (const file of version.files) {
if (file.os === os && file.arch === arch) {
releases.push({
version: version.version,
jdkVersion: version.jdkVersion,
os: os,
arch: arch,
downloadUrl: version.baseUrl + file.filename,
checksum: file.checksum
});
break;
}
}
}
}
return releases;
}
getOs() {
switch (process.platform) {
case 'darwin':
return 'macos';
case 'win32':
return 'windows';
default:
return process.platform;
}
}
getArch() {
switch (this.architecture) {
case 'arm64':
return 'aarch64';
case 'x64':
return 'x86_64';
default:
return this.architecture;
}
}
}
/***/ })
};
+63
View File
@@ -0,0 +1,63 @@
export const id = 172;
export const ids = [172];
export const modules = {
/***/ 8172:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ configureMavenArgs: () => (/* binding */ configureMavenArgs)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4527);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7242);
/**
* Configures the MAVEN_ARGS environment variable so that Maven suppresses
* artifact transfer/download progress output by default, producing cleaner
* CI logs.
*
* Behavior:
* - When `show-download-progress` is `false` (the default), `-ntp`
* (`--no-transfer-progress`) is appended to any existing MAVEN_ARGS value.
* - When `show-download-progress` is `true`, MAVEN_ARGS is left untouched so
* the user's own configuration (and Maven's default progress output) is
* preserved.
*
* The change is idempotent: if MAVEN_ARGS already disables transfer progress
* (via `-ntp` or `--no-transfer-progress`) nothing is added. Any pre-existing
* MAVEN_ARGS value is preserved.
*
* MAVEN_ARGS is honored by Maven 3.9.0+ and the Maven Wrapper; older Maven
* versions ignore it, so this is a no-op there. It has no effect on non-Maven
* builds such as Gradle or sbt.
*/
function configureMavenArgs() {
const showDownloadProgress = (0,_util_js__WEBPACK_IMPORTED_MODULE_1__/* .getBooleanInput */ .Vt)(_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .INPUT_SHOW_DOWNLOAD_PROGRESS */ .wX, false);
if (showDownloadProgress) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`${_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .INPUT_SHOW_DOWNLOAD_PROGRESS */ .wX} is true; leaving ${_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_ARGS_ENV */ .qm} unchanged`);
return;
}
const existingArgs = (process.env[_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_ARGS_ENV */ .qm] ?? '').trim();
const alreadyDisabled = existingArgs
.split(/\s+/)
.some(arg => arg === _constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_NO_TRANSFER_PROGRESS_FLAG */ .ti ||
arg === _constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_NO_TRANSFER_PROGRESS_LONG_FLAG */ .kN);
if (alreadyDisabled) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`${_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_ARGS_ENV */ .qm} already disables transfer progress; leaving it unchanged`);
return;
}
const updatedArgs = existingArgs
? `${existingArgs} ${_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_NO_TRANSFER_PROGRESS_FLAG */ .ti}`
: _constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_NO_TRANSFER_PROGRESS_FLAG */ .ti;
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .exportVariable */ .dN(_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_ARGS_ENV */ .qm, updatedArgs);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Configured ${_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_ARGS_ENV */ .qm} to include ${_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .MAVEN_NO_TRANSFER_PROGRESS_FLAG */ .ti} to suppress Maven transfer progress logs. ` +
`Set '${_constants_js__WEBPACK_IMPORTED_MODULE_2__/* .INPUT_SHOW_DOWNLOAD_PROGRESS */ .wX}: true' to keep the download progress output.`);
}
/***/ })
};
+131
View File
@@ -0,0 +1,131 @@
export const id = 182;
export const ids = [182];
export const modules = {
/***/ 1182:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ OracleDistribution: () => (/* binding */ OracleDistribution)
/* 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 _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);
const ORACLE_DL_BASE = 'https://download.oracle.com/java';
class OracleDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_3__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Oracle', installerOptions);
}
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 extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .renameWinArchive */ .n2)(javaArchivePath);
}
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();
if (arch !== 'x64' && arch !== 'aarch64') {
throw new Error(`Unsupported architecture: ${this.architecture}`);
}
if (!this.stable) {
throw new Error('Early access versions are not supported');
}
if (this.packageType !== 'jdk') {
throw new Error('Oracle JDK provides only the `jdk` package type');
}
const platform = this.getPlatform();
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_4__/* .getLatestMajorVersion */ .ri)(this.http);
range = latestMajor.toString();
}
const isOnlyMajorProvided = !range.includes('.');
const major = isOnlyMajorProvided ? range : range.split('.')[0];
const possibleUrls = [];
/**
* NOTE
* If only major version was provided we will check it under /latest first
* in order to retrieve the latest possible version if possible,
* otherwise we will fall back to /archive where we are guaranteed to
* find any version if it exists
*/
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_5__/* .HttpCodes */ .Hv.OK) {
const floating = url === floatingUrl;
return {
url,
version: range,
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_5__/* .HttpCodes */ .Hv.NotFound) {
throw new Error(`Http request for Oracle JDK failed with status code: ${response.message.statusCode}`);
}
}
if (this.latest) {
const error = this.createVersionNotFoundError(range);
error.message += `\nThe latest Java major version (${range}) is not yet available for the Oracle JDK distribution. Please specify a concrete version instead of 'latest'.`;
throw error;
}
throw this.createVersionNotFoundError(range);
}
getPlatform(platform = process.platform) {
switch (platform) {
case 'darwin':
return 'macos';
case 'win32':
return 'windows';
case 'linux':
return 'linux';
default:
throw new Error(`Platform '${platform}' is not supported. Supported platforms: 'linux', 'macos', 'windows'`);
}
}
}
/***/ })
};
+137
View File
@@ -0,0 +1,137 @@
export const id = 19;
export const ids = [19];
export const modules = {
/***/ 1019:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LocalDistribution: () => (/* binding */ LocalDistribution)
/* 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 _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__);
class LocalDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_3__/* .JavaBase */ .O {
jdkFile;
constructor(installerOptions, jdkFile) {
super('jdkfile', installerOptions);
this.jdkFile = jdkFile;
}
async setupJava() {
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_0__/* .info */ .pq(`Resolved Java ${foundJava.version} from tool-cache`);
}
else {
_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_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}'`);
}
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_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_0__/* .info */ .pq(`Setting Java ${foundJava.version} as the default`);
this.setJavaDefault(foundJava.version, foundJava.path);
}
else {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .info */ .pq(`Installing Java ${foundJava.version} (not setting as default)`);
this.setJavaEnvironment(foundJava.version, foundJava.path);
}
return foundJava;
}
async findPackageForDownload(version // eslint-disable-line @typescript-eslint/no-unused-vars
) {
throw new Error('This method should not be implemented in local file provider');
}
async downloadTool(javaRelease // eslint-disable-line @typescript-eslint/no-unused-vars
) {
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');
}
/***/ })
};
+308
View File
@@ -0,0 +1,308 @@
export const id = 220;
export const ids = [220];
export const modules = {
/***/ 3220:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
MicrosoftDistributions: () => (/* binding */ MicrosoftDistributions)
});
// UNUSED EXPORTS: MICROSOFT_PUBLIC_KEY
// EXTERNAL MODULE: ./src/distributions/base-installer.ts + 2 modules
var base_installer = __webpack_require__(6242);
// EXTERNAL MODULE: ./src/util.ts
var util = __webpack_require__(4527);
// EXTERNAL MODULE: ./src/gpg.ts
var gpg = __webpack_require__(8343);
;// CONCATENATED MODULE: ./src/distributions/microsoft/microsoft-key.ts
// Microsoft Build of OpenJDK GPG signing key
// Retrieved from: https://download.visualstudio.microsoft.com/download/pr/b90071e2-e0cf-4411-98be-dbeb09d67bf0/8622862bcd54206e158c5abca0582c9b/464279_464280_aoc_20210208.asc
const MICROSOFT_PUBLIC_KEY = `-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: BSN Pgp v1.1.0.0
mQENBGAhlWcBCADCQjj6huLTenvZSLej35e9YKEHm4lix2uvPOONexMaU8V2v7KL
RGdoXF7jwHci7efnPZ+9zpS2+g3rhvv8M7yWy9E/1psEtGzvmp1IL/qIabMEQqi+
UlhPGh7MQ/BkXAlic8Dyl3XYqr0EXS11iCiTr6Zkxs9Ee4V54gxL4gogRn4wk9sl
/nrjgDzMsUwla0pynoQQvYpqCdiAr3gKKllT1skCDqgVOMMyZxsx9HjZxg/3AJz6
r5i512L2R+3Hkv+XmxT+mnGBCFcny0DM7PjNXEmIK3ZSkro1tQML90zx3Fyh5esx
fpVvuIXGFV75o35VVCBZoiD3hcfOnIJsPQ9nABEBAAG0OE1pY3Jvc29mdCBKYXZh
IEVuZ2luZWVyaW5nIDxqYXZhcGxhdGluZnJhQG1pY3Jvc29mdC5jb20+iQE4BBMB
CAAiBQJgIZVnAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRA1Ux0xWyHB
icwTCACJO2FGNocNvdUtAb+eDKuGwt0chAJdCES2ZtgBScwrwDyWpxpRznoXWBHL
MJeLyxJoKsCG3vVlY4uh48psCzVm3OKvi7MCPT955t8W6TzfSBxTpjR8zRgJkjPJ
EGhHTlusUfz7TtM5etJF0qscSJH1grcNsgtee97mk4QyEzT8Di83NQmYxKcBrliq
yK/SWWt8VkTyYAEO6L5PoB4L9r8ka27uQs+jgCw+/Z0JMtNmmhyNGY3+a1YtPeoy
JdQaI9LphfKGbVaz6SK2aol7vj+c2TG3TLUYdOYGMH1OZlri2GTkCVjwna2GC7p4
Fa133tP85xzJEq1XeXm8WeLFo2wV
=rHCS
-----END PGP PUBLIC KEY BLOCK-----`;
// 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_);
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(6928);
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_);
;// CONCATENATED MODULE: ./src/distributions/microsoft/installer.ts
class MicrosoftDistributions extends base_installer/* JavaBase */.O {
constructor(installerOptions) {
super('Microsoft', installerOptions);
}
async downloadTool(javaRelease) {
core/* info */.pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
if (this.verifySignature) {
if (!javaRelease.signatureUrl) {
throw new Error(`Input 'verify-signature' is enabled, but no signature URL was found for Microsoft Build of OpenJDK version ${javaRelease.version}.`);
}
core/* info */.pq(`Verifying Java package signature...`);
try {
await gpg/* verifyPackageSignature */.Yi(javaArchivePath, javaRelease.signatureUrl, this.verifySignaturePublicKey ?? MICROSOFT_PUBLIC_KEY);
}
catch (error) {
throw new Error(`Failed to verify signature for Microsoft Build of OpenJDK version ${javaRelease.version}. Signature URL: ${javaRelease.signatureUrl}. Error: ${error.message}`, { cause: error });
}
}
core/* info */.pq(`Extracting Java archive...`);
const extension = (0,util/* getDownloadArchiveExtension */.ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,util/* renameWinArchive */.n2)(javaArchivePath);
}
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 (0,util/* cacheJdkDir */.Vj)(archivePath, this.toolcacheFolderName, this.getToolcacheVersionName(javaRelease.version), this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async findPackageForDownload(range) {
const arch = this.distributionArchitecture();
if (arch !== 'x64' && arch !== 'aarch64') {
throw new Error(`Unsupported architecture: ${this.architecture}`);
}
if (!this.stable) {
throw new Error('Early access versions are not supported');
}
if (this.packageType !== 'jdk') {
throw new Error('Microsoft Build of OpenJDK provides only the `jdk` package type');
}
const manifest = await this.getAvailableVersions();
if (!manifest) {
throw new Error('Could not load manifest for Microsoft Build of OpenJDK');
}
const foundRelease = await tool_cache/* findFromManifest */.DC(range, true, manifest, arch);
if (!foundRelease) {
const availableVersionStrings = manifest.map(item => item.version);
throw this.createVersionNotFoundError(range, availableVersionStrings);
}
const file = foundRelease.files[0];
const signatureUrl = file.signature_url ?? `${file.download_url}.sig`;
return {
url: file.download_url,
signatureUrl,
version: foundRelease.version,
checksum: await this.fetchChecksum(`${file.download_url}.sha256sum.txt`, 'sha256')
};
}
supportsSignatureVerification() {
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_)();
let response = null;
if (core/* isDebug */._o()) {
console.time('Retrieving available versions for Microsoft took'); // eslint-disable-line no-console
}
try {
response = await this.http.getJson(fileUrl, headers);
if (!response.result) {
return null;
}
}
catch (err) {
core/* debug */.Yz(`Http request for microsoft-openjdk-versions.json failed with status code: ${response?.statusCode}. Error: ${err}`);
return null;
}
if (response.result) {
releases = response.result;
}
if (core/* isDebug */._o() && releases) {
core/* startGroup */.Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for Microsoft took'); // eslint-disable-line no-console
core/* debug */.Yz(`Available versions: [${releases.length}]`);
core/* debug */.Yz(releases.map(item => item.version).join(', '));
core/* endGroup */.N4();
}
return releases;
}
}
/***/ }),
/***/ 8343:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Fh: () => (/* binding */ importKey),
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature),
/* harmony export */ mS: () => (/* binding */ removeGpgHome),
/* harmony export */ nY: () => (/* binding */ toGpgPath)
/* harmony export */ });
/* 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 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 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
// (exit code 2), so all paths passed to GPG must be in POSIX format on Windows.
function toGpgPath(p) {
if (process.platform !== 'win32')
return p;
return p
.replace(/\\/g, '/')
.replace(/^([A-Za-z]):\//, (_, drive) => `/${drive.toLowerCase()}/`);
}
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 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_5__/* .downloadTool */ .bq(signatureUrl);
let gpgHome;
try {
gpgHome = createGpgHome(VERIFY_GPG_HOME_PREFIX);
}
catch (error) {
try {
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
}
catch {
// ignore cleanup failures
}
throw new Error(`Failed to create temporary GPG home directory for signature verification: ${error.message}`, { cause: error });
}
try {
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_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(publicKeyFile)
], options);
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--verify',
toGpgPath(signaturePath),
toGpgPath(archivePath)
], options);
}
finally {
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(gpgHome);
}
}
/***/ })
};
+788
View File
@@ -0,0 +1,788 @@
export const id = 242;
export const ids = [242];
export const modules = {
/***/ 6242:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
O: () => (/* binding */ JavaBase)
});
// EXTERNAL MODULE: ./node_modules/@actions/tool-cache/lib/tool-cache.js + 2 modules
var tool_cache = __webpack_require__(9805);
// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js + 7 modules
var core = __webpack_require__(3838);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(9896);
// EXTERNAL MODULE: ./node_modules/semver/index.js
var semver = __webpack_require__(2088);
var semver_default = /*#__PURE__*/__webpack_require__.n(semver);
// 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/http-client/lib/index.js + 1 modules
var lib = __webpack_require__(4942);
// EXTERNAL MODULE: ./src/util.ts
var util = __webpack_require__(4527);
// EXTERNAL MODULE: ./src/constants.ts
var constants = __webpack_require__(7242);
;// CONCATENATED MODULE: ./src/retrying-http-client.ts
const RETRYABLE_HTTP_STATUS_CODES = new Set([429, 502, 503, 504, 522]);
const RETRYABLE_NETWORK_ERROR_CODES = new Set([
'ETIMEDOUT',
'ECONNRESET',
'ENOTFOUND',
'ECONNREFUSED'
]);
const RETRYABLE_HTTP_VERBS = new Set(['OPTIONS', 'GET', 'DELETE', 'HEAD']);
class RetryingHttpClient extends lib/* HttpClient */.Qq {
maxAttempts;
baseDelayMs;
maxDelayMs;
sleep;
random;
now;
constructor(userAgent, retryOptions = {}) {
super(userAgent, undefined, { allowRetries: false });
this.maxAttempts = retryOptions.maxAttempts ?? 4;
this.baseDelayMs = retryOptions.baseDelayMs ?? 1000;
this.maxDelayMs = retryOptions.maxDelayMs ?? 10000;
this.sleep =
retryOptions.sleep ??
(delayMs => new Promise(resolve => setTimeout(resolve, delayMs)));
this.random = retryOptions.random ?? Math.random;
this.now = retryOptions.now ?? Date.now;
if (this.maxAttempts < 1) {
throw new Error('maxAttempts must be at least 1');
}
if (this.baseDelayMs < 0 || this.maxDelayMs < this.baseDelayMs) {
throw new Error('baseDelayMs must be non-negative and no greater than maxDelayMs');
}
}
async request(verb, requestUrl, data, headers) {
if (!RETRYABLE_HTTP_VERBS.has(verb)) {
return super.request(verb, requestUrl, data, headers);
}
for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
try {
const response = await super.request(verb, requestUrl, data, headers);
const statusCode = response.message.statusCode;
if (!statusCode ||
!RETRYABLE_HTTP_STATUS_CODES.has(statusCode) ||
attempt === this.maxAttempts) {
return response;
}
const delayMs = this.getDelayMs(attempt, response.message.headers['retry-after']);
await response.readBody();
this.logRetry(attempt, delayMs, `HTTP ${statusCode}`);
await this.sleep(delayMs);
}
catch (error) {
if (!isRetryableNetworkError(error) || attempt === this.maxAttempts) {
throw error;
}
const delayMs = this.getDelayMs(attempt);
this.logRetry(attempt, delayMs, getErrorMessage(error));
await this.sleep(delayMs);
}
}
throw new Error('HTTP retry attempts exhausted unexpectedly');
}
getDelayMs(failedAttempt, retryAfter) {
const exponentialDelay = Math.min(this.maxDelayMs, this.baseDelayMs * 2 ** (failedAttempt - 1));
const jitteredDelay = Math.floor(exponentialDelay / 2 + this.random() * (exponentialDelay / 2));
const retryAfterDelay = parseRetryAfter(retryAfter, this.now());
return Math.min(this.maxDelayMs, Math.max(jitteredDelay, retryAfterDelay ?? 0));
}
logRetry(failedAttempt, delayMs, reason) {
core/* info */.pq(`Request attempt ${failedAttempt} of ${this.maxAttempts} failed (${reason}); retrying in ${delayMs} ms`);
}
}
function parseRetryAfter(value, nowMs) {
const retryAfter = Array.isArray(value) ? value[0] : value;
if (!retryAfter) {
return undefined;
}
if (/^\d+$/.test(retryAfter.trim())) {
return Number(retryAfter) * 1000;
}
const retryAt = Date.parse(retryAfter);
if (Number.isNaN(retryAt) || retryAt <= nowMs) {
return undefined;
}
return retryAt - nowMs;
}
function isRetryableNetworkError(error) {
if (!isErrorRecord(error)) {
return false;
}
if (typeof error.code === 'string' &&
RETRYABLE_NETWORK_ERROR_CODES.has(error.code)) {
return true;
}
return (Array.isArray(error.errors) &&
error.errors.some(nestedError => isRetryableNetworkError(nestedError)));
}
function isErrorRecord(error) {
return typeof error === 'object' && error !== null;
}
function getErrorMessage(error) {
return error instanceof Error ? error.message : 'network error';
}
// EXTERNAL MODULE: external "os"
var external_os_ = __webpack_require__(857);
var external_os_default = /*#__PURE__*/__webpack_require__.n(external_os_);
// EXTERNAL MODULE: external "crypto"
var external_crypto_ = __webpack_require__(6982);
// EXTERNAL MODULE: external "stream/promises"
var promises_ = __webpack_require__(9786);
;// CONCATENATED MODULE: ./src/checksum.ts
function sanitizedSource(source) {
if (!source) {
return '';
}
try {
const url = new URL(source);
return ` from ${url.origin}${url.pathname}`;
}
catch {
return ' from an invalid checksum source';
}
}
// Length, in hex characters, of a digest produced by each supported algorithm.
// Exported so callers (e.g. fetchChecksum) can infer which algorithm a vendor
// actually used when it doesn't disclose it via the checksum URL/filename.
function expectedDigestLength(algorithm) {
return algorithm === 'sha256' ? 64 : algorithm === 'sha512' ? 128 : 0;
}
function normalizeExpectedDigest(checksum) {
const algorithm = checksum.algorithm;
const digest = typeof checksum.value === 'string'
? checksum.value.trim().toLowerCase()
: '';
const expectedLength = expectedDigestLength(algorithm);
if (expectedLength === 0) {
throw new Error(`Unsupported checksum algorithm '${String(algorithm)}'${sanitizedSource(checksum.source)}. Supported algorithms are sha256 and sha512.`);
}
if (!new RegExp(`^[a-f0-9]{${expectedLength}}$`).test(digest)) {
throw new Error(`Malformed ${algorithm} checksum metadata${sanitizedSource(checksum.source)}: expected a ${expectedLength}-character hexadecimal digest.`);
}
return digest;
}
async function calculateChecksum(filePath, algorithm) {
const hash = (0,external_crypto_.createHash)(algorithm);
await (0,promises_.pipeline)((0,external_fs_.createReadStream)(filePath), hash);
return hash.digest('hex');
}
async function verifyChecksum(filePath, checksum, context) {
const expected = normalizeExpectedDigest(checksum);
const actual = await calculateChecksum(filePath, checksum.algorithm);
const matches = (0,external_crypto_.timingSafeEqual)(Buffer.from(expected, 'hex'), Buffer.from(actual, 'hex'));
if (!matches) {
throw new Error(`Checksum verification failed for ${context.distribution} version ${context.version}: ${checksum.algorithm} expected ${expected}, actual ${actual}.`);
}
}
// EXTERNAL MODULE: ./src/distributions/platform-types.ts
var platform_types = __webpack_require__(7444);
;// CONCATENATED MODULE: ./src/distributions/base-installer.ts
class JavaBase {
distribution;
http;
version;
architecture;
packageType;
stable;
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;
constructor(distribution, installerOptions) {
this.distribution = distribution;
this.http = new RetryingHttpClient('actions/setup-java');
({
version: this.version,
stable: this.stable,
latest: this.latest
} = this.normalizeVersion(installerOptions.version));
this.architecture = (0,platform_types/* normalizeArchitecture */.dV)(installerOptions.architecture || external_os_default().arch());
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
: true;
this.verifySignature = installerOptions.verifySignature ?? false;
this.verifySignaturePublicKey = installerOptions.verifySignaturePublicKey;
}
async downloadAndVerify(javaRelease) {
const archivePath = await tool_cache/* downloadTool */.bq(javaRelease.url);
const checksum = javaRelease.checksum;
if (!checksum || !checksum.value?.trim()) {
core/* debug */.Yz(`No authoritative checksum is available for ${this.distribution} version ${javaRelease.version}; skipping checksum verification.`);
return archivePath;
}
try {
await verifyChecksum(archivePath, checksum, {
distribution: this.distribution,
version: javaRelease.version
});
core/* debug */.Yz(`Verified ${checksum.algorithm} checksum for ${this.distribution} version ${javaRelease.version}.`);
return archivePath;
}
catch (error) {
let cleanupError;
let cleanupFailed = false;
try {
await external_fs_.promises.rm(archivePath, { force: true });
}
catch (caughtCleanupError) {
cleanupError = caughtCleanupError;
cleanupFailed = true;
}
if (cleanupFailed) {
throw new Error(`${error.message} Failed to remove the downloaded archive after verification failure: ${cleanupError.message}`, { cause: error });
}
throw error;
}
}
async fetchChecksum(checksumUrl, algorithm) {
// Some vendors (e.g. JetBrains) publish a single, generically-named
// checksum sibling (`.checksum`) whose digest algorithm isn't disclosed
// by the URL and has changed across releases. Accepting a list of
// candidate algorithms lets callers pass every algorithm the vendor is
// known to use; the actual algorithm is then inferred from the length of
// the returned digest.
const algorithms = Array.isArray(algorithm) ? algorithm : [algorithm];
const algorithmLabel = algorithms.join(' or ');
const response = await this.http.get(checksumUrl);
const statusCode = response.message.statusCode;
const source = (() => {
try {
const url = new URL(checksumUrl);
return `${url.origin}${url.pathname}`;
}
catch {
return 'an invalid checksum URL';
}
})();
if (statusCode === lib/* HttpCodes */.Hv.NotFound) {
core/* debug */.Yz(`No authoritative ${algorithmLabel} checksum is available for ${this.distribution} from ${source}; skipping checksum verification.`);
return undefined;
}
if (statusCode !== lib/* HttpCodes */.Hv.OK) {
throw new Error(`Failed to fetch the authoritative ${algorithmLabel} checksum for ${this.distribution} from ${source} (HTTP ${statusCode}).`);
}
const body = await response.readBody();
const value = body.trim().split(/\s+/, 1)[0] ?? '';
if (!value) {
throw new Error(`Received an empty authoritative ${algorithmLabel} checksum for ${this.distribution} from ${source}.`);
}
// Prefer the strongest algorithm whose digest length matches what was
// actually returned; fall back to the first candidate (preserving prior
// behavior/error messages) when the digest doesn't match any of them.
const resolvedAlgorithm = algorithms.find(algo => value.length === expectedDigestLength(algo)) ??
algorithms[0];
return { algorithm: resolvedAlgorithm, value, source: checksumUrl };
}
async setupJava() {
if (this.verifySignature && !this.supportsSignatureVerification()) {
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 &&
!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 {
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 {
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) {
this.logSetupError(error);
throw error;
}
}
if (!foundJava) {
throw new Error('Failed to resolve Java version');
}
// JDK folder may contain postfix "Contents/Home" on macOS
const macOSPostfixPath = external_path_default().join(foundJava.path, constants/* MACOS_JAVA_CONTENT_POSTFIX */.PG);
if (process.platform === 'darwin' && external_fs_.existsSync(macOSPostfixPath)) {
foundJava.path = macOSPostfixPath;
}
if (this.setDefault) {
core/* info */.pq(`Setting Java ${foundJava.version} as the default`);
this.setJavaDefault(foundJava.version, foundJava.path);
}
else {
core/* info */.pq(`Installing Java ${foundJava.version} (not setting as default)`);
this.setJavaEnvironment(foundJava.version, foundJava.path);
}
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
: error instanceof lib/* HttpClientError */.Kg
? error.statusCode
: undefined;
if (httpStatusCode) {
if (httpStatusCode === 403) {
core/* error */.z3('HTTP 403: Permission denied or access restricted.');
}
else if (httpStatusCode === 429) {
core/* warning */.$e('HTTP 429: Rate limit exceeded. Please retry later.');
}
else {
core/* error */.z3(`HTTP ${httpStatusCode}: ${error.message}`);
}
}
else if (error && error.errors && Array.isArray(error.errors)) {
core/* error */.z3(`Java setup failed due to network or configuration error(s)`);
if (error instanceof Error && error.stack) {
core/* debug */.Yz(error.stack);
}
for (const err of error.errors) {
const endpoint = err?.address || err?.hostname || '';
const port = err?.port ? `:${err.port}` : '';
const message = err?.message || 'Aggregate error';
const endpointInfo = !message.includes(endpoint)
? ` ${endpoint}${port}`
: '';
const localInfo = err.localAddress && err.localPort
? ` - Local (${err.localAddress}:${err.localPort})`
: '';
const logMessage = `${message}${endpointInfo}${localInfo}`;
core/* error */.z3(logMessage);
core/* debug */.Yz(`${err.stack || err.message}`);
Object.entries(err).forEach(([key, value]) => {
core/* debug */.Yz(`"${key}": ${JSON.stringify(value)}`);
});
}
}
else {
const message = error instanceof Error ? error.message : JSON.stringify(error);
core/* error */.z3(`Java setup process failed due to: ${message}`);
if (typeof error?.code === 'string') {
core/* debug */.Yz(error.stack);
}
const errorDetails = {
name: error.name,
message: error.message,
...Object.getOwnPropertyNames(error)
.filter(prop => !['name', 'message', 'stack'].includes(prop))
.reduce((acc, prop) => {
acc[prop] = error[prop];
return acc;
}, {})
};
Object.entries(errorDetails).forEach(([key, value]) => {
core/* debug */.Yz(`"${key}": ${JSON.stringify(value)}`);
});
}
}
get toolcacheFolderName() {
return `Java_${this.distribution}_${this.packageType}`;
}
supportsSignatureVerification() {
return false;
}
getToolcacheVersionName(version) {
if (!this.stable) {
if (version.includes('+')) {
return version.replace('+', '-ea.');
}
else {
return `${version}-ea`;
}
}
// Kotlin and some Java dependencies don't work properly when Java path contains "+" sign
// so replace "/hostedtoolcache/Java/11.0.3+4/x64" to "/hostedtoolcache/Java/11.0.3-4/x64" when saves to cache
// 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
const availableVersions = tool_cache/* findAllVersions */.iq(this.toolcacheFolderName, this.architecture)
.map(item => {
return {
version: item
.replace('-ea.', '+')
.replace(/-ea$/, '')
// Kotlin and some Java dependencies don't work properly when Java path contains "+" sign
// so replace "/hostedtoolcache/Java/11.0.3-4/x64" to "/hostedtoolcache/Java/11.0.3+4/x64" when retrieves to cache
// related issue: https://github.com/actions/virtual-environments/issues/3014
.replace('-', '+'),
path: (0,util/* getToolcachePath */.yH)(this.toolcacheFolderName, item, this.architecture) || '',
stable: !item.includes('-ea')
};
})
.filter(item => item.stable === this.stable);
const satisfiedVersions = availableVersions
.filter(item => (0,util/* isVersionSatisfies */.y)(this.version, item.version))
.filter(item => item.path)
.sort((a, b) => {
return -semver_default().compareBuild(a.version, b.version);
});
if (!satisfiedVersions || satisfiedVersions.length === 0) {
return null;
}
return {
version: satisfiedVersions[0].version,
path: satisfiedVersions[0].path
};
}
normalizeVersion(version) {
let stable = true;
const latest = false;
// Support the `latest` alias (case-insensitive), which floats to the newest
// available stable/GA release. It is translated to the SemVer wildcard `x`
// so the existing "newest satisfying version wins" resolution applies.
const normalized = version.trim().toLowerCase();
if (normalized === 'latest') {
return {
version: 'x',
stable: true,
latest: true
};
}
// Reject `latest` combined with any qualifier (e.g. `latest-ea`). Such inputs
// would otherwise have their `-ea` suffix stripped and fall through to the
// generic SemVer check, which fails with a confusing "'latest' is not valid
// SemVer" message even though `latest` is a supported value. Fail early with a
// targeted explanation instead.
if (normalized.startsWith('latest')) {
throw new Error(`The 'latest' alias resolves stable (GA) releases only and cannot be combined with '-ea' or other qualifiers (received '${version}'). Use 'latest' on its own, or specify a concrete version.`);
}
if (version.endsWith('-ea')) {
version = version.replace(/-ea$/, '');
stable = false;
}
else if (version.includes('-ea.')) {
// transform '11.0.3-ea.2' -> '11.0.3+2'
version = version.replace('-ea.', '+');
stable = false;
}
// Java uses a versioning scheme (JEP 322) that can contain more numeric
// fields than SemVer allows, e.g. '18.0.1.1' or '11.0.9.1'. Convert such
// exact versions to SemVer build notation ('18.0.1+1') so they are
// accepted. Ranges and versions that already carry build metadata are
// left untouched.
if (/^\d+(\.\d+){3,}$/.test(version)) {
version = (0,util/* convertVersionToSemver */.ZY)(version);
}
if (!semver_default().validRange(version)) {
throw new Error(`The string '${version}' is not valid SemVer notation for a Java version. Please check README file for code snippets and more detailed information`);
}
return {
version,
stable,
latest
};
}
createVersionNotFoundError(versionOrRange, availableVersions, additionalContext) {
const parts = [
`No matching version found for SemVer '${versionOrRange}'.`,
`Distribution: ${this.distribution}`,
`Package type: ${this.packageType}`,
`Architecture: ${this.architecture}`
];
// Add additional context if provided (e.g., platform/OS info)
if (additionalContext) {
parts.push(additionalContext);
}
if (availableVersions && availableVersions.length > 0) {
const maxVersionsToShow = core/* isDebug */._o() ? availableVersions.length : 50;
const versionsToShow = availableVersions.slice(0, maxVersionsToShow);
const truncated = availableVersions.length > maxVersionsToShow;
parts.push(`Available versions: ${versionsToShow.join(', ')}${truncated ? ', ...' : ''}`);
if (truncated) {
parts.push(`(showing first ${maxVersionsToShow} of ${availableVersions.length} versions, enable debug mode to see all)`);
}
}
const error = new Error(parts.join('\n'));
error.name = 'VersionNotFoundError';
return error;
}
setJavaDefault(version, toolPath) {
core/* exportVariable */.dN('JAVA_HOME', toolPath);
core/* addPath */.fM(external_path_default().join(toolPath, 'bin'));
this.setJavaEnvironment(version, toolPath);
}
setJavaEnvironment(version, toolPath) {
const majorVersion = version.split('.')[0];
core/* setOutput */.uH('distribution', this.distribution);
core/* setOutput */.uH('path', toolPath);
core/* setOutput */.uH('version', version);
core/* exportVariable */.dN(`JAVA_HOME_${majorVersion}_${this.architecture.toUpperCase()}`, toolPath);
}
distributionArchitecture() {
return this.architecture;
}
}
/***/ })
};
+211
View File
@@ -0,0 +1,211 @@
export const id = 282;
export const ids = [282];
export const modules = {
/***/ 2282:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ JetBrainsDistribution: () => (/* binding */ JetBrainsDistribution)
/* 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 _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);
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);
}
async findPackageForDownload(range) {
const versionsRaw = await this.getAvailableVersions();
const versions = versionsRaw.map(v => {
const formattedVersion = `${v.semver}+${v.build}`;
return {
version: formattedVersion,
url: v.url
};
});
const satisfiedVersions = versions
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(range, item.version))
.sort((a, b) => {
return -semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(a.version, b.version);
});
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableVersionStrings = versionsRaw.map(item => `${item.tag_name} (${item.semver}+${item.build})`);
throw this.createVersionNotFoundError(range, availableVersionStrings);
}
return {
...resolvedFullVersion,
// JetBrains' `.checksum` sibling doesn't disclose its algorithm via the
// filename, and older JBR builds (e.g. JBR 11) publish a SHA-256 digest
// there while newer builds publish SHA-512. Accept either, preferring
// the stronger SHA-512 when the digest length is ambiguous.
checksum: await this.fetchChecksum(`${resolvedFullVersion.url}.checksum`, ['sha512', 'sha256'])
};
}
async downloadTool(javaRelease) {
_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_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 (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
async getAvailableVersions() {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
console.time('Retrieving available versions for JBR took'); // eslint-disable-line no-console
}
const rawVersions = [];
const bearerToken = process.env.GITHUB_TOKEN;
const requestHeaders = {};
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;
}
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;
}
}
if (this.stable) {
// Add versions not available from the API but are downloadable
const hidden = ['11_0_10b1145.115', '11_0_11b1341.60'];
rawVersions.push(...hidden.map(tag => ({ tag_name: tag, name: tag, prerelease: false })));
}
const versions0 = rawVersions.map(async (v) => {
// Release tags look like one of these:
// jbr-release-21.0.3b465.3
// jbr17-b87.7
// jb11_0_11-b87.7
// jbr11_0_15b2043.56
// 11_0_11b1536.2
// 11_0_11-b1522
const tag = v.tag_name;
// Extract version string
const vstring = tag
.replace('jbr-release-', '')
.replace('jbr', '')
.replace('jb', '')
.replace('-', '');
const vsplit = vstring.split('b');
let semver = vsplit[0];
const build = vsplit[1];
// Normalize semver
if (!semver.includes('.') && !semver.includes('_'))
semver = `${semver}.0.0`;
// Construct URL
let type;
switch (this.packageType ?? '') {
case 'jre':
type = 'jbr';
break;
case 'jdk+jcef':
type = 'jbrsdk_jcef';
break;
case 'jre+jcef':
type = 'jbr_jcef';
break;
case 'jdk+ft':
type = 'jbrsdk_ft';
break;
case 'jre+ft':
type = 'jbr_ft';
break;
default:
type = 'jbrsdk';
break;
}
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_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_6__/* .HttpCodes */ .Hv.OK) {
include = true;
}
}
const version = {
tag_name: tag,
semver: semver.replace(/_/g, '.'),
build: build,
url: url
};
return {
item: version,
include: include
};
});
const versions = await Promise.all(versions0).then(res => res.filter(item => item.include).map(item => item.item));
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .startGroup */ .Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for JBR took'); // eslint-disable-line no-console
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Available versions: [${versions.length}]`);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(versions.map(item => item.semver).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .endGroup */ .N4();
}
return versions;
}
getPlatformOption() {
// Jetbrains has own platform names so need to map them
switch (process.platform) {
case 'darwin':
return 'osx';
case 'win32':
return 'windows';
default:
return process.platform;
}
}
}
/***/ })
};
+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);
}
/***/ })
};
+356
View File
@@ -0,0 +1,356 @@
export const id = 377;
export const ids = [377];
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 */ });
/* 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__(6971);
/* 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-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 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: ');
}
/***/ })
};
+32
View File
@@ -0,0 +1,32 @@
export const id = 394;
export const ids = [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;
}
/***/ })
};
+262
View File
@@ -0,0 +1,262 @@
export const id = 451;
export const ids = [451];
export const modules = {
/***/ 9451:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ configureToolchains: () => (/* binding */ configureToolchains),
/* harmony export */ createToolchainsSettings: () => (/* binding */ createToolchainsSettings),
/* harmony export */ generateNewToolchainDefinition: () => (/* binding */ generateNewToolchainDefinition),
/* harmony export */ generateToolchainDefinition: () => (/* binding */ generateToolchainDefinition),
/* harmony export */ validateToolchainIds: () => (/* reexport safe */ _toolchain_ids_js__WEBPACK_IMPORTED_MODULE_5__.O)
/* harmony export */ });
/* 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 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 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_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(8701);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7242);
/* harmony import */ var _toolchain_ids_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7083);
/* harmony import */ var _xml_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(22);
async function configureToolchains(version, distributionName, jdkHome, toolchainId) {
const vendor = _actions_core__WEBPACK_IMPORTED_MODULE_3__/* .getInput */ .V4(_constants_js__WEBPACK_IMPORTED_MODULE_6__/* .INPUT_MVN_TOOLCHAIN_VENDOR */ .m7) || distributionName;
const id = toolchainId || `${vendor}_${version}`;
const settingsDirectory = _actions_core__WEBPACK_IMPORTED_MODULE_3__/* .getInput */ .V4(_constants_js__WEBPACK_IMPORTED_MODULE_6__/* .INPUT_SETTINGS_PATH */ .Xh) ||
path__WEBPACK_IMPORTED_MODULE_2__.join(os__WEBPACK_IMPORTED_MODULE_1__.homedir(), _constants_js__WEBPACK_IMPORTED_MODULE_6__/* .M2_DIR */ .iT);
await createToolchainsSettings({
jdkInfo: {
version,
vendor,
id,
jdkHome
},
settingsDirectory
});
}
async function createToolchainsSettings({ jdkInfo, settingsDirectory }) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Creating ${_constants_js__WEBPACK_IMPORTED_MODULE_6__/* .MVN_TOOLCHAINS_FILE */ .qs} for JDK version ${jdkInfo.version} from ${jdkInfo.vendor}`);
// 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_4__/* .mkdirP */ .U$(settingsDirectory);
const originalToolchains = await readExistingToolchainsFile(settingsDirectory);
const updatedToolchains = await generateToolchainDefinition(originalToolchains, jdkInfo.version, jdkInfo.vendor, jdkInfo.id, jdkInfo.jdkHome);
await writeToolchainsFileToDisk(settingsDirectory, updatedToolchains);
}
// only exported for testing purposes
async function generateToolchainDefinition(original, version, vendor, id, jdkHome) {
if (!original?.length) {
return generateNewToolchainDefinition(version, vendor, id, jdkHome);
}
return generateMergedToolchainDefinition(original, version, vendor, id, jdkHome);
}
async function generateMergedToolchainDefinition(original, version, vendor, id, jdkHome) {
let jsToolchains = [
{
type: 'jdk',
provides: {
version: `${version}`,
vendor: `${vendor}`,
id: `${id}`
},
configuration: {
jdkHome: `${jdkHome}`
}
}
];
// default root attributes, used when the existing file does not declare its own
let rootAttributes = {
'@xmlns': 'http://maven.apache.org/TOOLCHAINS/1.1.0',
'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'@xsi:schemaLocation': 'http://maven.apache.org/TOOLCHAINS/1.1.0 https://maven.apache.org/xsd/toolchains-1.1.0.xsd'
};
const { XMLParser } = await __webpack_require__.e(/* import() */ 824).then(__webpack_require__.bind(__webpack_require__, 5824));
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@',
parseAttributeValue: false,
parseTagValue: false,
trimValues: true,
isArray: tagName => tagName === 'toolchain'
});
const jsObj = parser.parse(original);
if (isToolchainsRoot(jsObj.toolchains)) {
// preserve the existing root attributes (xmlns, schemaLocation, …) so we don't
// silently rewrite user-managed metadata or change the effective XML namespace;
// fast-xml-parser exposes attributes as `@`-prefixed keys on the element object
const existingAttributes = Object.fromEntries(Object.entries(jsObj.toolchains).filter(([key, value]) => key.startsWith('@') && typeof value === 'string'));
// fall back to the defaults only for attributes the existing file is missing
rootAttributes = { ...rootAttributes, ...existingAttributes };
if (jsObj.toolchains.toolchain) {
jsToolchains.push(...jsObj.toolchains.toolchain);
}
}
// remove potential duplicates based on type & id (which should be a unique combination);
// self.findIndex will only return the first occurrence, ensuring duplicates are skipped
jsToolchains = jsToolchains.filter((value, index, self) =>
// ensure non-jdk toolchains are kept in the results, we must not touch them because they belong to the user
value.type !== 'jdk' ||
// keep toolchains that lack a usable string id (e.g. partially-formed user files);
// we cannot safely deduplicate them and must not crash while reading them
typeof value.provides?.id !== 'string' ||
index ===
self.findIndex(t => t.type === value.type && t.provides?.id === value.provides?.id));
return serializeToolchains(rootAttributes, jsToolchains);
}
function generateNewToolchainDefinition(version, vendor, id, jdkHome) {
return [
'<?xml version="1.0"?>',
'<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.1.0"',
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
' xsi:schemaLocation="http://maven.apache.org/TOOLCHAINS/1.1.0 https://maven.apache.org/xsd/toolchains-1.1.0.xsd">',
' <toolchain>',
' <type>jdk</type>',
' <provides>',
` <version>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlText */ .I)(version)}</version>`,
` <vendor>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlText */ .I)(vendor)}</vendor>`,
` <id>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlText */ .I)(id)}</id>`,
' </provides>',
' <configuration>',
` <jdkHome>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlText */ .I)(jdkHome)}</jdkHome>`,
' </configuration>',
' </toolchain>',
'</toolchains>'
].join('\n');
}
async function readExistingToolchainsFile(directory) {
const location = path__WEBPACK_IMPORTED_MODULE_2__.join(directory, _constants_js__WEBPACK_IMPORTED_MODULE_6__/* .MVN_TOOLCHAINS_FILE */ .qs);
if (fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(location)) {
return fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(location, {
encoding: 'utf-8',
flag: 'r'
});
}
return '';
}
async function writeToolchainsFileToDisk(directory, settings) {
const location = path__WEBPACK_IMPORTED_MODULE_2__.join(directory, _constants_js__WEBPACK_IMPORTED_MODULE_6__/* .MVN_TOOLCHAINS_FILE */ .qs);
const settingsExists = fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(location);
// The toolchains file is produced by a non-destructive merge (existing JDK,
// custom, and non-jdk toolchains are preserved see generateToolchainDefinition),
// so it is always safe to write it. Unlike settings.xml, it is therefore not
// gated behind the `overwrite-settings` input; that would prevent subsequent
// setup-java runs from registering additional JDKs and silently drop the
// toolchain entries created by earlier runs.
if (settingsExists) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Updating existing file ${location}`);
}
else {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Writing to ${location}`);
}
return fs__WEBPACK_IMPORTED_MODULE_0__.writeFileSync(location, settings, {
encoding: 'utf-8',
flag: 'w'
});
}
function serializeToolchains(rootAttributes, toolchains) {
return [
'<?xml version="1.0"?>',
serializeOpeningTag('toolchains', rootAttributes, 0),
...toolchains.flatMap(toolchain => serializeXmlElement('toolchain', toolchain, 1)),
'</toolchains>'
].join('\n');
}
function serializeOpeningTag(name, attributes, depth) {
const indent = ' '.repeat(depth);
const attributeEntries = Object.entries(attributes);
if (!attributeEntries.length) {
return `${indent}<${name}>`;
}
const [firstAttribute, ...restAttributes] = attributeEntries;
const lines = [
`${indent}<${name} ${formatXmlAttribute(firstAttribute)}`,
...restAttributes.map(([attributeName, value]) => {
return `${indent} ${formatXmlAttribute([attributeName, value])}`;
})
];
lines[lines.length - 1] += '>';
return lines.join('\n');
}
function serializeXmlElement(name, value, depth) {
const indent = ' '.repeat(depth);
if (Array.isArray(value)) {
return value.flatMap(item => serializeXmlElement(name, item, depth));
}
if (!isXmlElementObject(value)) {
return [
`${indent}<${name}>${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlText */ .I)(String(value ?? ''))}</${name}>`
];
}
const attributes = Object.fromEntries(Object.entries(value)
.filter(([key, attributeValue]) => {
return key.startsWith('@') && typeof attributeValue === 'string';
})
.map(([key, attributeValue]) => [key, attributeValue]));
const childEntries = Object.entries(value).filter(([key]) => !key.startsWith('@') && key !== '#text');
const textValue = value['#text'];
if (!childEntries.length) {
if (textValue !== undefined) {
return [
`${serializeOpeningTag(name, attributes, depth)}${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlText */ .I)(String(textValue ?? ''))}</${name}>`
];
}
return [`${serializeOpeningTag(name, attributes, depth)}</${name}>`];
}
return [
serializeOpeningTag(name, attributes, depth),
...(textValue === undefined
? []
: [`${' '.repeat(depth + 1)}${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlText */ .I)(String(textValue ?? ''))}`]),
...childEntries.flatMap(([childName, childValue]) => serializeXmlElement(childName, childValue, depth + 1)),
`${indent}</${name}>`
];
}
function formatXmlAttribute([name, value]) {
return `${name.slice(1)}="${(0,_xml_js__WEBPACK_IMPORTED_MODULE_7__/* .escapeXmlAttribute */ .R)(value)}"`;
}
function isToolchainsRoot(value) {
return isXmlElementObject(value);
}
function isXmlElementObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/***/ }),
/***/ 22:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ I: () => (/* binding */ escapeXmlText),
/* harmony export */ R: () => (/* binding */ escapeXmlAttribute)
/* harmony export */ });
function escapeXmlText(value) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
// Use for user-controlled values written into XML attributes. Text nodes should
// use escapeXmlText so quotes remain byte-compatible with previous output.
function escapeXmlAttribute(value) {
return escapeXmlText(value).replace(/"/g, '&quot;').replace(/'/g, '&apos;');
}
/***/ })
};
+409
View File
@@ -0,0 +1,409 @@
export const id = 463;
export const ids = [463];
export const modules = {
/***/ 463:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
TemurinDistribution: () => (/* binding */ TemurinDistribution),
TemurinImplementation: () => (/* binding */ TemurinImplementation)
});
// UNUSED EXPORTS: ADOPTIUM_PUBLIC_KEY
// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js + 7 modules
var core = __webpack_require__(3838);
// 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/semver/index.js
var semver = __webpack_require__(2088);
var semver_default = /*#__PURE__*/__webpack_require__.n(semver);
// EXTERNAL MODULE: ./src/gpg.ts
var gpg = __webpack_require__(8343);
;// CONCATENATED MODULE: ./src/distributions/temurin/adoptium-key.ts
// Adoptium GPG signing key (fingerprint: 3B04D753C9050D9A5D343F39843C48A565F8F04B)
// Retrieved from: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3B04D753C9050D9A5D343F39843C48A565F8F04B
const ADOPTIUM_PUBLIC_KEY = `-----BEGIN PGP PUBLIC KEY BLOCK-----
xsBNBGGTvTQBCAC6ey144n7CG8foafF6mwgIBN1fIm1ILZDuGS4tMr0/XI8pgJnT
QvsPxZWEvtSm7bEMObzEoZJcXwjBcJl1B0ui8k5kHMTI75gCmZPsoKLFWIEpuRBQ
PBocusw80apDmLnNDQLVQvDFtEua5gaNa/fRw9YsmBoXBqvgrjFUIdGyWoQvH5+a
9OYlWD9n5VV0gnVMb+aclwVzB/zJw3kHGSgzuMtlAHeQiah7Y8yomQn/UIX8yqDf
+11sP3+c87YcjkRqImRTtmKEDcEtGPAIXC6SYA+uEEkbYE0Fy0chkvtnVWJ597fa
Epai4rnICU8zoJ6X5z3v1aM2WerhX9oq9X8PABEBAAHNQEFkb3B0aXVtIEdQRyBL
ZXkgKERFQi9SUE0gU2lnbmluZyBLZXkpIDx0ZW11cmluLWRldkBlY2xpcHNlLm9y
Zz7CwJIEEwEIADwWIQQ7BNdTyQUNml00PzmEPEilZfjwSwUCYZO9NAIbAwULCQgH
AgMiAgEGFQoJCAsCBBYCAwECHgcCF4AACgkQhDxIpWX48Et4AggAjjJzYWuKV3nG
7ngInngl8G/m9JoHr7BmwgcQXYhdy5hVkMcUx5JLeXz2LMBUH/F2nD595hgjMabk
kVib20X8lq9RsNbdfc2hBcWU6qyHKxsIqT4boI2/XDyEzzMyyZWWNGo/27Ci7Xmj
pWu31nh0pDdPqdyWDIKojbVVnxlCRY8as8Sm+1ufi709KCi4MuwHNsUlCSwb/fju
NKeHkrHbLcHKUUIEcmTSKRWrpMYBzm1HYOGBz4xPuELwUfUp71ehfoyBZlp6RDRf
l5TYI1FmCyHuvjNhrJgWv7bOTcf8yObGY+TEUhzc4xQqCrF4ur9d3opvsuPBQsv+
Klqi5KSZgs7ATQRhk700AQgAq14okly8cFrpYVenEQPiB75AUZfKRpMduiR6IxAj
SKcH7aSoFZ9AubUEBVpZsyT5svxoEPe1i4TdbF+m9FGy42EcOlLa3ArLTj5H8FRl
UdGZB9I5mk4GptOzPM+aHMMu92vW/ZwjuS8DvOiQSp+cUmG1EqOMJSM7e/4BM71z
E+OKaVJCj79pEzhG3SK/IC/OlxxyETT66NSfYJd7Sw5R6Vr19am/uNU690W0CJ+q
VQeFpmDMr7LnfdFRIh+lJe05+PvWXeidkGjox5cbG52wf8aRIR/FgkfcFvqRMN1f
B+dVOWueloUeVAnzcUznOKmUEs7LP9ObJhYHHgup4IAU2wARAQABwsB2BBgBCAAg
FiEEOwTXU8kFDZpdND85hDxIpWX48EsFAmGTvTQCGwwACgkQhDxIpWX48EvXHQf/
Q0nZsGDXnZHiBoojeSdpkO7WBjMIP3w1GdLvRpPQrS8TfOPbZuoevzCNh38Y3gwF
yelJspvzDQrBXhgkzAGlucYg8Y7KHa5Ebm7iDgMzc37L1hYSZTYCqwd7aowfgy34
hOk3B67LffkJpIh738Oa9CtlwxQ9xcytmBmQ1fBBOwm/9IhAwHPQuydYIs4DxWbj
0MGSP4fDntU7e4UjsHNmhudDcYol0FaqdHHIIB9C/G4CzetRwHFOn3b4JwXMU7YU
6aJA3mXhi3hggMC3wkT2HHZ/TquuOdNc02fypWOCDOHz0alBBJNqoVUNFNqU3tfJ
wI4qF/KKq9BfyfucAs0ykA==
=XLag
-----END PGP PUBLIC KEY BLOCK-----`;
// EXTERNAL MODULE: ./src/distributions/base-installer.ts + 2 modules
var base_installer = __webpack_require__(6242);
// EXTERNAL MODULE: ./src/constants.ts
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
var TemurinImplementation;
(function (TemurinImplementation) {
TemurinImplementation["Hotspot"] = "Hotspot";
})(TemurinImplementation || (TemurinImplementation = {}));
class TemurinDistribution extends base_installer/* JavaBase */.O {
jvmImpl;
includeJmods;
constructor(installerOptions, jvmImpl) {
super(`Temurin-${jvmImpl}`, installerOptions);
this.jvmImpl = jvmImpl;
this.includeJmods = this.packageType === 'jdk+jmods';
}
/**
* @internal For cross-distribution reuse only. Not intended as a public API.
*/
async findPackageForDownload(version) {
return this.resolvePackage(version, this.includeJmods ? 'jdk' : this.packageType);
}
async resolvePackage(version, imageType) {
const availableVersionsRaw = await this.getAvailableVersions(imageType);
const availableVersionsWithBinaries = availableVersionsRaw
.filter(item => item.binaries.length > 0)
.map(item => {
// normalize 17.0.0-beta+33.0.202107301459 to 17.0.0+33.0.202107301459 for earlier access versions
const formattedVersion = this.stable
? item.version_data.semver
: item.version_data.semver.replace('-beta+', '+');
return {
version: formattedVersion,
url: item.binaries[0].package.link,
signatureUrl: item.binaries[0].package.signature_link,
checksum: {
algorithm: 'sha256',
value: item.binaries[0].package.checksum,
source: item.binaries[0].package.checksum_link
}
};
});
const satisfiedVersions = availableVersionsWithBinaries
.filter(item => (0,util/* isVersionSatisfies */.y)(version, item.version))
.sort((a, b) => {
return -semver_default().compareBuild(a.version, b.version);
});
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableVersionStrings = availableVersionsWithBinaries.map(item => item.version);
throw this.createVersionNotFoundError(version, availableVersionStrings);
}
return resolvedFullVersion;
}
async downloadTool(javaRelease) {
core/* info */.pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadPackage(javaRelease);
core/* info */.pq(`Extracting Java archive...`);
const extension = (0,util/* getDownloadArchiveExtension */.ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,util/* renameWinArchive */.n2)(javaArchivePath);
}
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 javaHome = process.platform === 'darwin'
? external_path_default().join(archivePath, constants/* MACOS_JAVA_CONTENT_POSTFIX */.PG)
: archivePath;
if (this.includeJmods && !external_fs_default().existsSync(external_path_default().join(javaHome, 'jmods'))) {
await this.installJmods(javaRelease.version, javaHome);
}
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await (0,util/* cacheJdkDir */.Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
supportsSignatureVerification() {
return true;
}
async downloadPackage(release) {
const archivePath = await this.downloadAndVerify(release);
if (this.verifySignature) {
if (!release.signatureUrl) {
throw new Error(`Input 'verify-signature' is enabled, but no signature URL was found for Temurin version ${release.version}.`);
}
core/* info */.pq(`Verifying Java package signature...`);
try {
await gpg/* verifyPackageSignature */.Yi(archivePath, release.signatureUrl, this.verifySignaturePublicKey ?? ADOPTIUM_PUBLIC_KEY);
}
catch (error) {
throw new Error(`Failed to verify signature for Temurin version ${release.version} from ${release.signatureUrl}: ${error.message}`, { cause: error });
}
}
return archivePath;
}
async installJmods(version, javaHome) {
const jmodsRelease = await this.resolvePackage(version, 'jmods');
core/* info */.pq(`Downloading JMODs ${jmodsRelease.version} (${this.distribution}) from ${jmodsRelease.url} ...`);
let jmodsArchivePath = await this.downloadPackage(jmodsRelease);
if (process.platform === 'win32') {
jmodsArchivePath = (0,util/* renameWinArchive */.n2)(jmodsArchivePath);
}
const extractedJmodsPath = await (0,util/* extractJdkFile */.PE)(jmodsArchivePath, (0,util/* getDownloadArchiveExtension */.ag)());
const jmodsDirectory = external_path_default().join(extractedJmodsPath, external_fs_default().readdirSync(extractedJmodsPath)[0]);
external_fs_default().cpSync(jmodsDirectory, external_path_default().join(javaHome, 'jmods'), { recursive: true });
}
async getAvailableVersions(imageType = this.includeJmods ? 'jdk' : this.packageType) {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
const versionRange = encodeURI('[1.0,100.0]'); // retrieve all available versions
const releaseType = this.stable ? 'ga' : 'ea';
if (core/* isDebug */._o()) {
console.time('Retrieving available versions for Temurin took'); // eslint-disable-line no-console
}
const baseRequestArguments = [
`project=jdk`,
'vendor=adoptium',
`heap_size=normal`,
'sort_method=DEFAULT',
'sort_order=DESC',
`os=${platform}`,
`architecture=${arch}`,
`image_type=${imageType}`,
`release_type=${releaseType}`,
`jvm_impl=${this.jvmImpl.toLowerCase()}`
].join('&');
const requestArguments = `${baseRequestArguments}&page_size=20&page=0`;
let availableVersionsUrl = `https://api.adoptium.net/v3/assets/version/${versionRange}?${requestArguments}`;
const availableVersions = [];
let pageCount = 0;
if (core/* isDebug */._o()) {
core/* debug */.Yz(`Gathering available versions from '${availableVersionsUrl}'`);
}
while (availableVersionsUrl) {
pageCount++;
const response = await this.http.getJson(availableVersionsUrl);
const paginationPage = response.result;
const nextUrl = (0,util/* getNextPageUrlFromLinkHeader */.rC)(response.headers);
if (nextUrl &&
!(0,util/* validatePaginationUrl */.SA)(nextUrl, 'https://api.adoptium.net')) {
core/* warning */.$e(`Ignoring pagination link with unexpected origin: ${nextUrl}`);
availableVersionsUrl = null;
}
else {
availableVersionsUrl = nextUrl;
}
if (paginationPage === null || paginationPage.length === 0) {
break;
}
availableVersions.push(...paginationPage);
if (pageCount >= util/* MAX_PAGINATION_PAGES */.Tp) {
core/* warning */.$e(`Reached pagination safeguard limit (${util/* MAX_PAGINATION_PAGES */.Tp} pages) while listing Temurin releases.`);
break;
}
}
if (core/* isDebug */._o()) {
core/* startGroup */.Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for Temurin took'); // eslint-disable-line no-console
core/* debug */.Yz(`Available versions: [${availableVersions.length}]`);
core/* debug */.Yz(availableVersions.map(item => item.version_data.semver).join(', '));
core/* endGroup */.N4();
}
return availableVersions;
}
getPlatformOption() {
// Adoptium has own platform names so need to map them
switch (process.platform) {
case 'darwin':
return 'mac';
case 'win32':
return 'windows';
case 'linux':
if ((0,platform_types/* isAlpineLinux */.G6)()) {
return 'alpine-linux';
}
return 'linux';
default:
return process.platform;
}
}
distributionArchitecture() {
const architecture = super.distributionArchitecture();
return architecture === 'armv7' ? 'arm' : architecture;
}
}
/***/ }),
/***/ 8343:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Fh: () => (/* binding */ importKey),
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature),
/* harmony export */ mS: () => (/* binding */ removeGpgHome),
/* harmony export */ nY: () => (/* binding */ toGpgPath)
/* harmony export */ });
/* 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 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 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
// (exit code 2), so all paths passed to GPG must be in POSIX format on Windows.
function toGpgPath(p) {
if (process.platform !== 'win32')
return p;
return p
.replace(/\\/g, '/')
.replace(/^([A-Za-z]):\//, (_, drive) => `/${drive.toLowerCase()}/`);
}
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 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_5__/* .downloadTool */ .bq(signatureUrl);
let gpgHome;
try {
gpgHome = createGpgHome(VERIFY_GPG_HOME_PREFIX);
}
catch (error) {
try {
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
}
catch {
// ignore cleanup failures
}
throw new Error(`Failed to create temporary GPG home directory for signature verification: ${error.message}`, { cause: error });
}
try {
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_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(publicKeyFile)
], options);
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--verify',
toGpgPath(signaturePath),
toGpgPath(archivePath)
], options);
}
finally {
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(gpgHome);
}
}
/***/ })
};
+146
View File
@@ -0,0 +1,146 @@
export const id = 524;
export const ids = [524];
export const modules = {
/***/ 8524:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LibericaNikDistributions: () => (/* binding */ LibericaNikDistributions)
/* harmony export */ });
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_0__ = __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 _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4527);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* 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);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_6__);
const supportedPlatform = `'linux', 'macos', 'windows'`;
const supportedArchitectures = `'x64', 'aarch64'`;
class LibericaNikDistributions extends _base_installer_js__WEBPACK_IMPORTED_MODULE_0__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Liberica_NIK', installerOptions);
}
async downloadTool(javaRelease) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
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 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) {
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersions = availableVersionsRaw
.map(item => {
const jdkVersion = this.getJdkVersion(item);
return jdkVersion ? { url: item.downloadUrl, version: jdkVersion } : null;
})
.filter((item) => item !== null);
const satisfiedVersion = availableVersions
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .isVersionSatisfies */ .y)(range, item.version))
.sort((a, b) => -semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(a.version, b.version))[0];
if (!satisfiedVersion) {
const availableVersionStrings = availableVersions.map(item => item.version);
throw this.createVersionNotFoundError(range, availableVersionStrings);
}
return satisfiedVersion;
}
async getAvailableVersions() {
if (_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .isDebug */ ._o()) {
console.time('Retrieving available versions for Liberica NIK took'); // eslint-disable-line no-console
}
const url = this.prepareAvailableVersionsUrl();
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`Gathering available versions from '${url}'`);
const availableVersions = (await this.http.getJson(url)).result ?? [];
if (_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .startGroup */ .Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for Liberica NIK took'); // eslint-disable-line no-console
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`Available versions: [${availableVersions.length}]`);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(availableVersions.map(item => item.version).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .endGroup */ .N4();
}
return availableVersions;
}
prepareAvailableVersionsUrl() {
const urlOptions = {
os: this.getPlatformOption(),
'bundle-type': this.getBundleType(),
...this.getArchitectureOptions(),
'build-type': this.stable ? 'all' : 'ea',
'installation-type': 'archive',
fields: 'downloadUrl,version,components,component,embedded'
};
const searchParams = new URLSearchParams(urlOptions).toString();
return `https://api.bell-sw.com/v1/nik/releases?${searchParams}`;
}
// NIK's top-level `version` is the GraalVM/NIK version; the JDK version that
// users select on lives in the embedded `liberica` component.
getJdkVersion(release) {
const liberica = release.components?.find(component => component.component === 'liberica');
return liberica ? this.convertVersionToSemver(liberica.version) : null;
}
// The `full` bundle adds JavaFX/Swing GUI support; otherwise use `standard`.
getBundleType() {
const [, feature] = this.packageType.split('+');
return feature?.includes('fx') ? 'full' : 'standard';
}
getArchitectureOptions() {
const arch = this.distributionArchitecture();
switch (arch) {
case 'x64':
return { bitness: '64', arch: 'x86' };
case 'aarch64':
return { bitness: '64', arch: 'arm' };
default:
throw new Error(`Architecture '${this.architecture}' is not supported. Supported architectures: ${supportedArchitectures}`);
}
}
getPlatformOption(platform = process.platform) {
switch (platform) {
case 'darwin':
return 'macos';
case 'win32':
case 'cygwin':
return 'windows';
case '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}`);
}
}
// JDK versions come as strings like '25.0.1+16', '23+38' or '11.0.15.1+2'.
// Normalize them to valid SemVer while preserving build metadata so newer
// NIK builds of the same JDK sort ahead of older ones.
convertVersionToSemver(jdkVersion) {
const [main, build] = jdkVersion.split('+');
const parts = main.split('.');
while (parts.length < 3) {
parts.push('0');
}
const base = parts.slice(0, 3).join('.');
const buildMeta = [...parts.slice(3), ...(build ? [build] : [])];
return buildMeta.length ? `${base}+${buildMeta.join('.')}` : base;
}
}
/***/ })
};
+192
View File
@@ -0,0 +1,192 @@
export const id = 557;
export const ids = [557];
export const modules = {
/***/ 7557:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SapMachineDistribution: () => (/* binding */ SapMachineDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* 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);
class SapMachineDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_5__/* .JavaBase */ .O {
constructor(installerOptions) {
super('SapMachine', installerOptions);
}
async findPackageForDownload(version) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Only stable versions: ${this.stable}`);
if (!['jdk', 'jre'].includes(this.packageType)) {
throw new Error('SapMachine provides only the `jdk` and `jre` package type');
}
const availableVersions = await this.getAvailableVersions();
const matchedVersions = availableVersions
.filter(item => {
return (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .isVersionSatisfies */ .y)(version, item.version);
})
.map(item => {
return {
version: item.version,
url: item.downloadLink
};
});
if (!matchedVersions.length) {
const availableVersionStrings = availableVersions.map(item => item.version);
throw this.createVersionNotFoundError(version, availableVersionStrings);
}
const resolvedVersion = matchedVersions[0];
const checksumUrl = resolvedVersion.url.replace(/\.(?:tar\.gz|zip)$/, '.sha256.txt');
return {
...resolvedVersion,
checksum: await this.fetchChecksum(checksumUrl, 'sha256')
};
}
async getAvailableVersions() {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
let fetchedReleasesJson = await this.fetchReleasesFromUrl('https://sapmachine.io/assets/data/sapmachine-releases-all.json');
if (!fetchedReleasesJson) {
fetchedReleasesJson = await this.fetchReleasesFromUrl('https://sap.github.io/SapMachine/assets/data/sapmachine-releases-all.json');
}
if (!fetchedReleasesJson) {
throw new Error(`Couldn't fetch SapMachine versions information from both primary and backup urls`);
}
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz('Successfully fetched information about available SapMachine versions');
const availableVersions = this.parseVersions(platform, arch, fetchedReleasesJson);
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .startGroup */ .Oh('Print information about available versions');
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(availableVersions.map(item => item.version).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .endGroup */ .N4();
}
return availableVersions;
}
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 extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .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 version = this.getToolcacheVersionName(javaRelease.version);
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) {
const eligibleVersions = [];
for (const [, majorVersionMap] of Object.entries(versions)) {
for (const [, jdkVersionMap] of Object.entries(majorVersionMap.updates)) {
for (const [buildVersion, buildVersionMap] of Object.entries(jdkVersionMap)) {
let buildVersionWithoutPrefix = buildVersion.replace('sapmachine-', '');
if (!buildVersionWithoutPrefix.includes('.')) {
// replace major version with major.minor.patch and keep the remaining build identifier after the + as is with regex
buildVersionWithoutPrefix = buildVersionWithoutPrefix.replace(/(\d+)(\+.*)?/, '$1.0.0$2');
}
// replace + with . to convert to semver format if we have more than 3 version digits
if (buildVersionWithoutPrefix.split('.').length > 3) {
buildVersionWithoutPrefix = buildVersionWithoutPrefix.replace('+', '.');
}
buildVersionWithoutPrefix = (0,_util_js__WEBPACK_IMPORTED_MODULE_4__/* .convertVersionToSemver */ .ZY)(buildVersionWithoutPrefix);
// ignore invalid version
if (!semver__WEBPACK_IMPORTED_MODULE_1___default().valid(buildVersionWithoutPrefix)) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Invalid version: ${buildVersionWithoutPrefix}`);
continue;
}
const isEarlyAccess = buildVersionMap.ea === true || buildVersionMap.ea === 'true';
if (this.stable === isEarlyAccess) {
continue;
}
for (const [edition, editionAssets] of Object.entries(buildVersionMap.assets)) {
if (this.packageType !== edition) {
continue;
}
for (const [archAndPlatForm, archAssets] of Object.entries(editionAssets)) {
let expectedArchAndPlatform = `${platform}-${arch}`;
if (platform === 'linux-musl') {
expectedArchAndPlatform = `linux-${arch}-musl`;
}
if (archAndPlatForm !== expectedArchAndPlatform) {
continue;
}
for (const [contentType, contentTypeAssets] of Object.entries(archAssets)) {
// skip if not tar.gz and zip files
if (contentType !== 'tar.gz' && contentType !== 'zip') {
continue;
}
eligibleVersions.push({
os: platform,
architecture: arch,
version: buildVersionWithoutPrefix,
checksum: contentTypeAssets.checksum,
downloadLink: contentTypeAssets.url,
packageType: edition
});
}
}
}
}
}
}
const sortedVersions = this.sortParsedVersions(eligibleVersions);
return sortedVersions;
}
// Sorts versions in descending order as by default data in JSON isn't sorted
sortParsedVersions(eligibleVersions) {
const sortedVersions = eligibleVersions.sort((versionObj1, versionObj2) => {
const version1 = versionObj1.version;
const version2 = versionObj2.version;
return semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(version1, version2);
});
return sortedVersions.reverse();
}
getPlatformOption() {
switch (process.platform) {
case 'win32':
return 'windows';
case 'darwin':
return 'macos';
case 'linux':
// figure out if alpine/musl
if ((0,_platform_types_js__WEBPACK_IMPORTED_MODULE_6__/* .isAlpineLinux */ .G6)()) {
return 'linux-musl';
}
return 'linux';
default:
return process.platform;
}
}
async fetchReleasesFromUrl(url, headers = {}) {
try {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Trying to fetch available SapMachine versions info from the primary url: ${url}`);
const releases = (await this.http.getJson(url, headers)).result;
return releases;
}
catch (err) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Fetching SapMachine versions info from the link: ${url} ended up with the error: ${err.message}`);
return null;
}
}
}
/***/ })
};
+152
View File
@@ -0,0 +1,152 @@
export const id = 63;
export const ids = [63];
export const modules = {
/***/ 2063:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LibericaDistributions: () => (/* binding */ LibericaDistributions)
/* harmony export */ });
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_0__ = __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 _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4527);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* 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);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_6__);
const supportedPlatform = `'linux', 'linux-musl', 'macos', 'solaris', 'windows'`;
const supportedArchitectures = `'x86', 'x64', 'armv7', 'aarch64', 'ppc64le'`;
class LibericaDistributions extends _base_installer_js__WEBPACK_IMPORTED_MODULE_0__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Liberica', installerOptions);
}
async downloadTool(javaRelease) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
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 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) {
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersions = availableVersionsRaw.map(item => ({
url: item.downloadUrl,
version: this.convertVersionToSemver(item)
}));
const satisfiedVersion = availableVersions
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .isVersionSatisfies */ .y)(range, item.version))
.sort((a, b) => -semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(a.version, b.version))[0];
if (!satisfiedVersion) {
const availableVersionStrings = availableVersions.map(item => item.version);
throw this.createVersionNotFoundError(range, availableVersionStrings);
}
return satisfiedVersion;
}
async getAvailableVersions() {
if (_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .isDebug */ ._o()) {
console.time('Retrieving available versions for Liberica took'); // eslint-disable-line no-console
}
const url = this.prepareAvailableVersionsUrl();
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`Gathering available versions from '${url}'`);
const availableVersions = (await this.http.getJson(url)).result ?? [];
if (_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .startGroup */ .Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for Liberica took'); // eslint-disable-line no-console
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`Available versions: [${availableVersions.length}]`);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(availableVersions.map(item => item.version).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .endGroup */ .N4();
}
return availableVersions;
}
prepareAvailableVersionsUrl() {
const urlOptions = {
os: this.getPlatformOption(),
'bundle-type': this.getBundleType(),
...this.getArchitectureOptions(),
'build-type': this.stable ? 'all' : 'ea',
'installation-type': 'archive',
fields: 'downloadUrl,version,featureVersion,interimVersion,updateVersion,buildVersion'
};
const searchParams = new URLSearchParams(urlOptions).toString();
return `https://api.bell-sw.com/v1/liberica/releases?${searchParams}`;
}
getBundleType() {
const [bundleType, feature] = this.packageType.split('+');
if (feature?.includes('fx')) {
return bundleType + '-full';
}
return bundleType;
}
getArchitectureOptions() {
const arch = this.distributionArchitecture();
switch (arch) {
case 'x86':
return { bitness: '32', arch: 'x86' };
case 'x64':
return { bitness: '64', arch: 'x86' };
case 'armv7':
return { bitness: '32', arch: 'arm' };
case 'aarch64':
return { bitness: '64', arch: 'arm' };
case 'ppc64le':
return { bitness: '64', arch: 'ppc' };
default:
throw new Error(`Architecture '${this.architecture}' is not supported. Supported architectures: ${supportedArchitectures}`);
}
}
getPlatformOption(platform = process.platform) {
switch (platform) {
case 'darwin':
return 'macos';
case 'win32':
case 'cygwin':
return 'windows';
case 'linux':
return (0,_platform_types_js__WEBPACK_IMPORTED_MODULE_4__/* .isAlpineLinux */ .G6)(platform) ? 'linux-musl' : 'linux';
case 'sunos':
return 'solaris';
default:
throw new Error(`Platform '${platform}' is not supported. Supported platforms: ${supportedPlatform}`);
}
}
convertVersionToSemver(version) {
const { buildVersion, featureVersion, interimVersion, updateVersion } = version;
const mainVersion = [featureVersion, interimVersion, updateVersion].join('.');
if (buildVersion != 0) {
return `${mainVersion}+${buildVersion}`;
}
return mainVersion;
}
distributionArchitecture() {
const arch = super.distributionArchitecture();
switch (arch) {
case 'arm':
return 'armv7';
default:
return arch;
}
}
}
/***/ })
};
+190
View File
@@ -0,0 +1,190 @@
export const id = 675;
export const ids = [675];
export const modules = {
/***/ 7675:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ DragonwellDistribution: () => (/* binding */ DragonwellDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* 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);
class DragonwellDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Dragonwell', installerOptions);
}
async findPackageForDownload(version) {
if (!this.stable) {
throw new Error('Early access versions are not supported by Dragonwell');
}
if (this.packageType !== 'jdk') {
throw new Error('Dragonwell provides only the `jdk` package type');
}
const availableVersions = await this.getAvailableVersions();
const matchedVersions = availableVersions
.filter(item => {
return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .isVersionSatisfies */ .y)(version, item.jdk_version);
})
.map(item => {
return {
version: item.jdk_version,
url: item.download_link,
checksum: item.checksum
? {
algorithm: 'sha256',
value: item.checksum
}
: undefined
};
});
if (!matchedVersions.length) {
const availableVersionStrings = availableVersions.map(item => item.jdk_version);
throw this.createVersionNotFoundError(version, availableVersionStrings);
}
const resolvedVersion = matchedVersions[0];
return resolvedVersion;
}
async getAvailableVersions() {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
let fetchedDragonwellJson = await this.fetchJsonFromPrimaryUrl();
if (!fetchedDragonwellJson) {
fetchedDragonwellJson = await this.fetchJsonFromBackupUrl();
}
if (!fetchedDragonwellJson) {
throw new Error(`Couldn't fetch Dragonwell versions information from both primary and backup urls`);
}
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz('Successfully fetched information about available Dragonwell versions');
const availableVersions = this.parseVersions(platform, arch, fetchedDragonwellJson);
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .startGroup */ .Oh('Print information about available versions');
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(availableVersions.map(item => item.jdk_version).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .endGroup */ .N4();
}
return availableVersions;
}
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 extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .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 (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) {
const eligibleVersions = [];
for (const majorVersion in dragonwellVersions) {
const majorVersionMap = dragonwellVersions[majorVersion];
for (let jdkVersion in majorVersionMap) {
const jdkVersionMap = majorVersionMap[jdkVersion];
if (!(platform in jdkVersionMap)) {
continue;
}
const platformMap = jdkVersionMap[platform];
if (!(arch in platformMap)) {
continue;
}
const archMap = platformMap[arch];
if (jdkVersion === 'latest') {
continue;
}
// Some version of Dragonwell JDK are numerated with help of non-semver notation (more then 3 digits).
// Common practice is to transform excess digits to the so-called semver build part, which is prefixed with the plus sign, to be able to operate with them using semver tools.
const jdkVersionNums = jdkVersion
.replace('+', '.')
.split('.');
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,
architecture: arch,
jdk_version: jdkVersion,
checksum: archMap[edition].sha256 ?? '',
download_link: archMap[edition].download_url,
edition: edition,
image_type: 'jdk'
});
break; // Get the first available link to the JDK. In most cases it should point to the Extended version of JDK, in rare cases like with v17 it points to the Standard version (the only available).
}
}
}
const sortedVersions = this.sortParsedVersions(eligibleVersions);
return sortedVersions;
}
// Sorts versions in descending order as by default data in JSON isn't sorted
sortParsedVersions(eligibleVersions) {
const sortedVersions = eligibleVersions.sort((versionObj1, versionObj2) => {
const version1 = versionObj1.jdk_version;
const version2 = versionObj2.jdk_version;
return semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(version1, version2);
});
return sortedVersions.reverse();
}
getPlatformOption() {
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;
}
}
async fetchJsonFromPrimaryUrl() {
const primaryUrl = 'https://dragonwell-jdk.io/map_with_checksum.json';
try {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Trying to fetch available Dragonwell versions info from the primary url: ${primaryUrl}`);
const fetchedDragonwellJson = (await this.http.getJson(primaryUrl)).result;
return fetchedDragonwellJson;
}
catch (err) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Fetching Dragonwell versions info from the primary link: ${primaryUrl} ended up with the error: ${err.message}`);
return null;
}
}
async fetchJsonFromBackupUrl() {
const owner = 'dragonwell-releng';
const repository = 'dragonwell-setup-java';
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_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;
return fetchedDragonwellJson;
}
catch (err) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Fetching Dragonwell versions info from the backup url: ${backupUrl} ended up with the error: ${err.message}`);
return null;
}
}
}
/***/ })
};
+128
View File
@@ -0,0 +1,128 @@
export const id = 735;
export const ids = [735];
export const modules = {
/***/ 3735:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ OpenJdkDistribution: () => (/* binding */ OpenJdkDistribution)
/* 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 _base_installer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6242);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4527);
const OPENJDK_BASE_URL = 'https://jdk.java.net';
class OpenJdkDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Oracle OpenJDK', installerOptions);
}
async findPackageForDownload(range) {
if (this.packageType !== 'jdk') {
throw new Error('Oracle OpenJDK provides only the `jdk` package type');
}
const arch = this.distributionArchitecture();
if (!['x64', 'aarch64'].includes(arch)) {
throw new Error(`Unsupported architecture: ${this.architecture}`);
}
const platform = this.getPlatform();
const releases = await this.getAvailableVersions(platform, arch);
const matchingReleases = releases
.filter(release => (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}`);
}
const release = matchingReleases[0];
return {
...release,
checksum: await this.fetchChecksum(`${release.url}.sha256`, 'sha256')
};
}
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 extension = javaRelease.url.endsWith('.zip') ? 'zip' : 'tar.gz';
if (extension === 'zip') {
javaArchivePath = (0,_util_js__WEBPACK_IMPORTED_MODULE_5__/* .renameWinArchive */ .n2)(javaArchivePath);
}
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) {
const homePage = await this.fetchPage(`${OPENJDK_BASE_URL}/`);
const releasePageUrls = Array.from(homePage.matchAll(/href="\/(\d+)\/">JDK\s+\d+/g), match => `${OPENJDK_BASE_URL}/${match[1]}/`);
const pages = await Promise.all(releasePageUrls.map(url => this.fetchPage(url)));
if (this.stable) {
pages.push(await this.fetchPage(`${OPENJDK_BASE_URL}/archive/`));
}
const releases = pages.flatMap(page => this.parseReleases(page, platform, arch));
return releases.filter(release => release.url.includes('/early_access/') !== this.stable);
}
async fetchPage(url) {
const response = await this.http.get(url);
return response.readBody();
}
parseReleases(html, platform, arch) {
const platformPattern = platform === 'macos' ? '(?:macos|osx)' : platform;
const extensionPattern = platform === 'windows' ? '(?:zip|tar\\.gz)' : 'tar\\.gz';
const pattern = new RegExp(`href="(https://download\\.java\\.net/[^"]+/openjdk-([^"_]+)_${platformPattern}-${arch}_bin\\.${extensionPattern})"`, 'g');
return Array.from(html.matchAll(pattern), match => {
const url = match[1];
const build = url.match(/\/(\d+)\/(?:GPL\/)?openjdk-/)?.[1] ??
this.findBuildInArchiveHeading(html, match.index, match[2]);
return {
version: this.toSemver(match[2], build),
url
};
});
}
findBuildInArchiveHeading(html, assetIndex, version) {
const headings = Array.from(html.slice(0, assetIndex).matchAll(/\(build\s+([^)]+)\)/g));
const headingVersion = headings.at(-1)?.[1];
if (!headingVersion) {
return undefined;
}
const [javaVersion, build] = headingVersion.split('+');
return javaVersion === version ? build : undefined;
}
toSemver(version, urlBuild) {
const [javaVersion, filenameBuild] = version.replace('-ea', '').split('+');
const versionParts = javaVersion.split('.');
const normalizedVersion = (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;
}
getPlatform(platform = process.platform) {
switch (platform) {
case 'darwin':
return 'macos';
case 'linux':
return 'linux';
case 'win32':
return 'windows';
default:
throw new Error(`Platform '${platform}' is not supported. Supported platforms: 'linux', 'macos', 'windows'`);
}
}
}
/***/ })
};
+62535
View File
File diff suppressed because it is too large Load Diff
+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;
}
/***/ })
};
+291
View File
@@ -0,0 +1,291 @@
export const id = 81;
export const ids = [81];
export const modules = {
/***/ 9081:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ configureAuthentication: () => (/* binding */ configureAuthentication),
/* harmony export */ createAuthenticationSettings: () => (/* binding */ createAuthenticationSettings),
/* harmony export */ generate: () => (/* binding */ generate),
/* harmony export */ getInputWithDeprecatedAlias: () => (/* binding */ getInputWithDeprecatedAlias)
/* 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__);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3838);
/* harmony import */ var _actions_io__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8701);
/* 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 os__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(857);
/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(7242);
/* harmony import */ var _gpg_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8343);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4527);
/* harmony import */ var _xml_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(22);
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 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);
const gpgPrivateKey = _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getInput */ .V4(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_GPG_PRIVATE_KEY */ .wz) ||
_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_DEFAULT_GPG_PRIVATE_KEY */ .OD;
const gpgPassphraseEnvVar = getInputWithDeprecatedAlias(_constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_GPG_PASSPHRASE_ENV_VAR */ .db, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_GPG_PASSPHRASE_DEPRECATED */ .TY, gpgPrivateKey ? _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .INPUT_DEFAULT_GPG_PASSPHRASE */ .RX : undefined);
if (gpgPrivateKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .setSecret */ .Pq(gpgPrivateKey);
}
await createAuthenticationSettings(id, usernameEnvVar, passwordEnvVar, settingsDirectory, overwriteSettings, gpgPassphraseEnvVar);
if (gpgPrivateKey) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq('Importing private gpg key');
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) {
const value = _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getInput */ .V4(inputName);
const deprecatedValue = _actions_core__WEBPACK_IMPORTED_MODULE_1__/* .getInput */ .V4(deprecatedInputName);
if (deprecatedValue) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .warning */ .$e(`The '${deprecatedInputName}' input is deprecated and may be removed in a future release. Please use '${inputName}' instead.`);
}
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}`);
// 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);
}
// only exported for testing purposes
function generate(id, usernameEnvVar, passwordEnvVar, gpgPassphraseEnvVar) {
// 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;
// otherwise the plugin already reads the right variable and no extra settings
// are needed. Writing `gpg.passphrase` to settings.xml is deprecated and fails
// when the plugin's `bestPractices` mode is enabled.
const includeGpgPassphraseProfile = gpgPassphraseEnvVar &&
gpgPassphraseEnvVar !== _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MAVEN_GPG_PASSPHRASE_DEFAULT_ENV */ .ko;
const lines = [
'<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"',
' 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>'
];
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>');
}
lines.push('</settings>');
return lines.join('\n');
}
async function write(directory, settings, overwriteSettings) {
const location = path__WEBPACK_IMPORTED_MODULE_0__.join(directory, _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .MVN_SETTINGS_FILE */ .vO);
const settingsExists = fs__WEBPACK_IMPORTED_MODULE_3__.existsSync(location);
if (settingsExists && overwriteSettings) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Overwriting existing file ${location}`);
}
else if (!settingsExists) {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Writing to ${location}`);
}
else {
_actions_core__WEBPACK_IMPORTED_MODULE_1__/* .info */ .pq(`Skipping generation ${location} because file already exists and overwriting is not required`);
return;
}
return fs__WEBPACK_IMPORTED_MODULE_3__.writeFileSync(location, settings, {
encoding: 'utf-8',
flag: 'w'
});
}
/***/ }),
/***/ 8343:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Fh: () => (/* binding */ importKey),
/* harmony export */ Yi: () => (/* binding */ verifyPackageSignature),
/* harmony export */ mS: () => (/* binding */ removeGpgHome),
/* harmony export */ nY: () => (/* binding */ toGpgPath)
/* harmony export */ });
/* 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 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 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
// (exit code 2), so all paths passed to GPG must be in POSIX format on Windows.
function toGpgPath(p) {
if (process.platform !== 'win32')
return p;
return p
.replace(/\\/g, '/')
.replace(/^([A-Za-z]):\//, (_, drive) => `/${drive.toLowerCase()}/`);
}
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 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_5__/* .downloadTool */ .bq(signatureUrl);
let gpgHome;
try {
gpgHome = createGpgHome(VERIFY_GPG_HOME_PREFIX);
}
catch (error) {
try {
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
}
catch {
// ignore cleanup failures
}
throw new Error(`Failed to create temporary GPG home directory for signature verification: ${error.message}`, { cause: error });
}
try {
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_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--import',
toGpgPath(publicKeyFile)
], options);
await _actions_exec__WEBPACK_IMPORTED_MODULE_4__/* .exec */ .m('gpg', [
'--homedir',
toGpgPath(gpgHome),
'--batch',
'--verify',
toGpgPath(signaturePath),
toGpgPath(archivePath)
], options);
}
finally {
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(signaturePath);
await _actions_io__WEBPACK_IMPORTED_MODULE_3__/* .rmRF */ .Yz(gpgHome);
}
}
/***/ }),
/***/ 22:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ I: () => (/* binding */ escapeXmlText),
/* harmony export */ R: () => (/* binding */ escapeXmlAttribute)
/* harmony export */ });
function escapeXmlText(value) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
// Use for user-controlled values written into XML attributes. Text nodes should
// use escapeXmlText so quotes remain byte-compatible with previous output.
function escapeXmlAttribute(value) {
return escapeXmlText(value).replace(/"/g, '&quot;').replace(/'/g, '&apos;');
}
/***/ })
};
+7109
View File
File diff suppressed because it is too large Load Diff
+175
View File
@@ -0,0 +1,175 @@
export const id = 939;
export const ids = [939];
export const modules = {
/***/ 9939:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SemeruDistribution: () => (/* binding */ SemeruDistribution)
/* harmony export */ });
/* harmony import */ var _base_installer_js__WEBPACK_IMPORTED_MODULE_0__ = __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 _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4527);
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3838);
/* 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__);
const supportedArchitectures = [
'x64',
'x86',
'ppc64le',
'ppc64',
's390x',
'aarch64'
];
class SemeruDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_0__/* .JavaBase */ .O {
constructor(installerOptions) {
super('IBM_Semeru', installerOptions);
}
async findPackageForDownload(version) {
const arch = this.distributionArchitecture();
if (!supportedArchitectures.includes(arch)) {
throw new Error(`Unsupported architecture for IBM Semeru: ${this.architecture} for your current OS version, the following are supported: ${supportedArchitectures.join(', ')}`);
}
if (!this.stable) {
throw new Error('IBM Semeru does not provide builds for early access versions');
}
if (this.packageType !== 'jdk' && this.packageType !== 'jre') {
throw new Error('IBM Semeru only provide `jdk` and `jre` package types');
}
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersionsWithBinaries = availableVersionsRaw
.filter(item => item.binaries.length > 0)
.map(item => {
// normalize 17.0.0-beta+33.0.202107301459 to 17.0.0+33.0.202107301459 for earlier access versions
const formattedVersion = this.stable
? item.version_data.semver
: item.version_data.semver.replace('-beta+', '+');
return {
version: formattedVersion,
url: item.binaries[0].package.link,
checksum: {
algorithm: 'sha256',
value: item.binaries[0].package.checksum,
source: item.binaries[0].package.checksum_link
}
};
});
const satisfiedVersions = availableVersionsWithBinaries
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .isVersionSatisfies */ .y)(version, item.version))
.sort((a, b) => {
return -semver__WEBPACK_IMPORTED_MODULE_1___default().compareBuild(a.version, b.version);
});
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableVersionStrings = availableVersionsWithBinaries.map(item => item.version);
// Include platform context to help users understand OS-specific version availability
// IBM Semeru builds are OS-specific, so platform info aids in troubleshooting
const platformContext = `Platform: ${process.platform}`;
throw this.createVersionNotFoundError(version, availableVersionStrings, platformContext);
}
return resolvedFullVersion;
}
async downloadTool(javaRelease) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
let javaArchivePath = await this.downloadAndVerify(javaRelease);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .info */ .pq(`Extracting Java archive...`);
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
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_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 (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .cacheJdkDir */ .Vj)(archivePath, this.toolcacheFolderName, version, this.architecture);
return { version: javaRelease.version, path: javaPath };
}
get toolcacheFolderName() {
return super.toolcacheFolderName;
}
async getAvailableVersions() {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
const imageType = this.packageType;
const versionRange = encodeURI('[1.0,100.0]'); // retrieve all available versions
const releaseType = this.stable ? 'ga' : 'ea';
if (_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .isDebug */ ._o()) {
console.time('Retrieving available versions for Semeru took'); // eslint-disable-line no-console
}
const baseRequestArguments = [
`project=jdk`,
'vendor=ibm',
`heap_size=normal`,
'sort_method=DEFAULT',
'sort_order=DESC',
`os=${platform}`,
`architecture=${arch}`,
`image_type=${imageType}`,
`release_type=${releaseType}`,
`jvm_impl=openj9`
].join('&');
const requestArguments = `${baseRequestArguments}&page_size=20&page=0`;
let availableVersionsUrl = `https://api.adoptopenjdk.net/v3/assets/version/${versionRange}?${requestArguments}`;
const availableVersions = [];
let pageCount = 0;
if (_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`Gathering available versions from '${availableVersionsUrl}'`);
}
while (availableVersionsUrl) {
pageCount++;
const response = await this.http.getJson(availableVersionsUrl);
const paginationPage = response.result;
const nextUrl = (0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .getNextPageUrlFromLinkHeader */ .rC)(response.headers);
if (nextUrl &&
!(0,_util_js__WEBPACK_IMPORTED_MODULE_2__/* .validatePaginationUrl */ .SA)(nextUrl, 'https://api.adoptopenjdk.net')) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .warning */ .$e(`Ignoring pagination link with unexpected origin: ${nextUrl}`);
availableVersionsUrl = null;
}
else {
availableVersionsUrl = nextUrl;
}
if (paginationPage === null || paginationPage.length === 0) {
break;
}
availableVersions.push(...paginationPage);
if (pageCount >= _util_js__WEBPACK_IMPORTED_MODULE_2__/* .MAX_PAGINATION_PAGES */ .Tp) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .warning */ .$e(`Reached pagination safeguard limit (${_util_js__WEBPACK_IMPORTED_MODULE_2__/* .MAX_PAGINATION_PAGES */ .Tp} pages) while listing Semeru releases.`);
break;
}
}
if (_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .startGroup */ .Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for Semeru took'); // eslint-disable-line no-console
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(`Available versions: [${availableVersions.length}]`);
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .debug */ .Yz(availableVersions.map(item => item.version_data.semver).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_3__/* .endGroup */ .N4();
}
return availableVersions;
}
getPlatformOption() {
// Adopt has own platform names so need to map them
switch (process.platform) {
case 'darwin':
return 'mac';
case 'win32':
return 'windows';
default:
return process.platform;
}
}
}
/***/ })
};
+354
View File
@@ -0,0 +1,354 @@
export const id = 968;
export const ids = [968];
export const modules = {
/***/ 6968:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ GraalVMCommunityDistribution: () => (/* binding */ GraalVMCommunityDistribution),
/* harmony export */ GraalVMDistribution: () => (/* binding */ GraalVMDistribution)
/* 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 _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);
const GRAALVM_DL_BASE = 'https://download.oracle.com/graalvm';
const GRAALVM_DOWNLOAD_URL = 'https://www.graalvm.org/downloads/';
const GRAALVM_COMMUNITY_RELEASES_URL = 'https://api.github.com/repos/graalvm/graalvm-ce-builds/releases?per_page=100';
const GRAALVM_COMMUNITY_RELEASES_PAGE_ORIGIN = 'https://api.github.com';
const GRAALVM_COMMUNITY_DOWNLOAD_URL = 'https://github.com/graalvm/graalvm-ce-builds/releases';
const GRAALVM_COMMUNITY_ASSET_PREFIX = 'graalvm-community-jdk-';
const GRAALVM_COMMUNITY_VERSION_PATTERN = /^\d+(?:\.\d+)*$/;
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_4__/* .JavaBase */ .O {
constructor(installerOptions, distributionName = 'GraalVM') {
super(distributionName, installerOptions);
}
async downloadTool(javaRelease) {
try {
_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)();
if (IS_WINDOWS) {
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);
// Add validation for extracted path
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_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_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);
}
async findPackageForDownload(range) {
this.validateVersionRange(range);
const arch = this.getSupportedArchitecture();
if (!this.stable) {
return this.findEABuildDownloadUrl(`${range}-ea`);
}
// The `latest` alias is normalized to the SemVer wildcard. Oracle GraalVM
// 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_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'),
floating,
fingerprint: floating
? (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getArtifactFingerprint */ .VX)(response.message.headers)
: undefined
};
}
validateVersionRange(range) {
if (!range || typeof range !== 'string') {
throw new Error('Version range is required and must be a string');
}
}
getSupportedArchitecture() {
const arch = this.distributionArchitecture();
if (!SUPPORTED_ARCHITECTURES.includes(arch)) {
throw new Error(`Unsupported architecture: ${this.architecture}. Supported architectures are: ${SUPPORTED_ARCHITECTURES.join(', ')}`);
}
return arch;
}
validateStableBuildRequest(range) {
if (this.packageType !== 'jdk') {
throw new Error(`${this.distribution} provides only the \`jdk\` package type`);
}
const platform = this.getPlatform();
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)) {
throw new Error(`Invalid version format: ${range}`);
}
if (majorVersion < GRAALVM_MIN_VERSION) {
throw new Error(`${this.distribution} is only supported for JDK ${GRAALVM_MIN_VERSION} and later. Requested version: ${major}`);
}
return {
platform,
major,
extension
};
}
constructFileUrl(range, major, platform, arch, extension) {
return range.includes('.')
? `${GRAALVM_DL_BASE}/${major}/archive/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`
: `${GRAALVM_DL_BASE}/${range}/latest/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`;
}
handleHttpResponse(response, range) {
const statusCode = response.message.statusCode;
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) {
error.message += `\nThe latest Java major version (${range}) is not yet available for the ${this.distribution} distribution. Please specify a concrete version instead of 'latest'.`;
}
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_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_5__/* .HttpCodes */ .Hv.OK) {
throw new Error(`HTTP request for GraalVM failed with status code: ${statusCode} (${response.message.statusMessage || 'Unknown error'})`);
}
}
async findEABuildDownloadUrl(javaEaVersion) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Searching for EA build: ${javaEaVersion}`);
const versions = await this.fetchEAJson(javaEaVersion);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Found ${versions.length} EA versions`);
const latestVersion = versions.find(v => v.latest);
if (!latestVersion) {
const availableVersions = versions.map(v => v.version);
throw this.createVersionNotFoundError(javaEaVersion, availableVersions, 'Note: No EA build is marked as latest for this version.');
}
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Latest version found: ${latestVersion.version}`);
const arch = this.distributionArchitecture();
const file = latestVersion.files.find(f => f.arch === arch && f.platform === GRAALVM_PLATFORM);
if (!file) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .error */ .z3(`Available files for architecture ${arch}: ${JSON.stringify(latestVersion.files)}`);
throw new Error(`Unable to find file for architecture '${arch}' and platform '${GRAALVM_PLATFORM}'`);
}
if (!file.filename.startsWith('graalvm-jdk-')) {
throw new Error(`Invalid filename format: ${file.filename}. Expected to start with 'graalvm-jdk-'`);
}
const downloadUrl = `${latestVersion.download_base_url}${file.filename}`;
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Download URL: ${downloadUrl}`);
return {
url: downloadUrl,
version: latestVersion.version,
checksum: await this.fetchChecksum(`${downloadUrl}.sha256`, 'sha256')
};
}
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_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);
if (!response.result) {
throw new Error(`No GraalVM EA build found for version '${javaEaVersion}'. Please check if the version is correct.`);
}
return response.result;
}
catch (error) {
if (error instanceof Error) {
// Check if it's a 404 error (file not found)
if (error.message?.includes('404')) {
throw new Error(`GraalVM EA version '${javaEaVersion}' not found. Please verify the version exists in the EA builds repository.`, { cause: error });
}
// Re-throw with more context
throw new Error(`Failed to fetch GraalVM EA version information for '${javaEaVersion}': ${error.message}`, { cause: error });
}
// If it's not an Error instance, throw a generic error
throw new Error(`Failed to fetch GraalVM EA version information for '${javaEaVersion}'`, { cause: error });
}
}
getPlatform(platform = process.platform) {
const platformMap = {
darwin: 'macos',
win32: 'windows',
linux: 'linux'
};
const result = platformMap[platform];
if (!result) {
throw new Error(`Platform '${platform}' is not supported. Supported platforms: 'linux', 'macos', 'windows'`);
}
return result;
}
}
class GraalVMCommunityDistribution extends GraalVMDistribution {
constructor(installerOptions) {
super(installerOptions, 'GraalVM Community');
}
get toolcacheFolderName() {
return `Java_GraalVM_Community_${this.packageType}`;
}
async findPackageForDownload(range) {
this.validateVersionRange(range);
if (!this.stable) {
throw new Error('GraalVM Community does not provide early access builds');
}
const arch = this.getSupportedArchitecture();
// GraalVM Community publishes its releases on GitHub, so the `latest` alias
// (normalized to the SemVer wildcard `x`) can float to the newest GA it
// actually ships. Unlike Oracle GraalVM (which has no listing endpoint and
// must derive the newest major from the Adoptium API), we match against the
// real release list here, so `latest` never fails when GraalVM lags behind a
// brand-new Java major.
let platform;
let extension;
if (this.latest) {
if (this.packageType !== 'jdk') {
throw new Error(`${this.distribution} provides only the \`jdk\` package type`);
}
platform = this.getPlatform();
extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
}
else {
({ platform, extension } = this.validateStableBuildRequest(range));
}
// GraalVM Community asset names embed the platform, architecture and
// archive type, e.g. `graalvm-community-jdk-21.0.2_linux-x64_bin.tar.gz`.
const assetSuffix = `_${platform}-${arch}_bin.${extension}`;
const availableVersions = await this.getAvailableVersions(assetSuffix);
const satisfiedVersion = availableVersions
.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}.`;
throw error;
}
return satisfiedVersion;
}
async getAvailableVersions(assetSuffix) {
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_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
// limiting, auth failure, etc.) that must be surfaced instead of being
// silently treated as "no releases", which would later look like a
// misleading "version not found" error.
if (!Array.isArray(response.result)) {
throw new Error(`Unexpected response while listing GraalVM Community releases from ${releasesUrl} ` +
`(HTTP status code: ${response.statusCode}). Expected a JSON array of releases. ` +
`Please check if the service is available at ${GRAALVM_COMMUNITY_DOWNLOAD_URL}.`);
}
const releases = response.result;
if (releases.length === 0) {
break;
}
for (const release of releases) {
if (release.draft || release.prerelease) {
continue;
}
for (const asset of release.assets ?? []) {
const version = this.extractAssetVersion(asset.name, assetSuffix);
if (version) {
const digest = asset.digest?.match(/^sha256:([a-f0-9]{64})$/i)?.[1];
if (!digest) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`No authoritative sha256 digest is available for ${asset.name}; skipping checksum verification for this asset.`);
}
versions.set(version, {
version,
url: asset.browser_download_url,
checksum: digest
? {
algorithm: 'sha256',
value: digest,
source: GRAALVM_COMMUNITY_RELEASES_URL
}
: undefined
});
}
}
}
releasesUrl = this.getNextReleasesUrl(response.headers);
}
return [...versions.values()];
}
// Returns the GraalVM JDK version encoded in a release asset name when it
// matches the requested platform/architecture/archive suffix, otherwise null.
extractAssetVersion(assetName, assetSuffix) {
if (!assetName.startsWith(GRAALVM_COMMUNITY_ASSET_PREFIX) ||
!assetName.endsWith(assetSuffix)) {
return null;
}
const rawVersion = assetName.slice(GRAALVM_COMMUNITY_ASSET_PREFIX.length, -assetSuffix.length);
if (!GRAALVM_COMMUNITY_VERSION_PATTERN.test(rawVersion)) {
return null;
}
return (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .convertVersionToSemver */ .ZY)(rawVersion);
}
getNextReleasesUrl(headers) {
const nextUrl = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getNextPageUrlFromLinkHeader */ .rC)(headers);
if (nextUrl &&
!(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;
}
return nextUrl;
}
}
/***/ })
};
+55548
View File
File diff suppressed because it is too large Load Diff
+198
View File
@@ -0,0 +1,198 @@
export const id = 978;
export const ids = [978];
export const modules = {
/***/ 9597:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ZuluDistribution: () => (/* binding */ ZuluDistribution)
/* harmony export */ });
/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3838);
/* 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);
class ZuluDistribution extends _base_installer_js__WEBPACK_IMPORTED_MODULE_4__/* .JavaBase */ .O {
constructor(installerOptions) {
super('Zulu', installerOptions);
}
async findPackageForDownload(version) {
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersions = availableVersionsRaw.map(item => {
// The Azul Metadata API reports the JDK build number separately from
// java_version (e.g. java_version=[17,0,7], openjdk_build_number=7).
// Append it so the resulting semver retains the build (e.g. 17.0.7+7).
const javaVersion = item.openjdk_build_number != null
? [...item.java_version, item.openjdk_build_number]
: item.java_version;
return {
version: (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .convertVersionToSemver */ .ZY)(javaVersion),
url: item.download_url,
zuluVersion: (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .convertVersionToSemver */ .ZY)(item.distro_version),
packageUuid: item.package_uuid
};
});
const satisfiedVersions = availableVersions
.filter(item => (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .isVersionSatisfies */ .y)(version, item.version))
.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_3___default().compareBuild(a.version, b.version) ||
-semver__WEBPACK_IMPORTED_MODULE_3___default().compareBuild(a.zuluVersion, b.zuluVersion));
})
.map((item) => ({
version: item.version,
url: item.url,
packageUuid: item.packageUuid
}));
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableVersionStrings = availableVersions.map(item => item.version);
throw this.createVersionNotFoundError(version, availableVersionStrings);
}
const packageDetailsUrl = `https://api.azul.com/metadata/v1/zulu/packages/${resolvedFullVersion.packageUuid}`;
const packageDetails = (await this.http.getJson(packageDetailsUrl)).result;
const digest = packageDetails?.sha256_hash?.match(/^[a-f0-9]{64}$/i)?.[0];
if (!digest) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`No authoritative sha256 checksum is available for Zulu version ${resolvedFullVersion.version} from ${packageDetailsUrl}; skipping checksum verification.`);
}
return {
version: resolvedFullVersion.version,
url: resolvedFullVersion.url,
checksum: digest
? {
algorithm: 'sha256',
value: digest,
source: packageDetailsUrl
}
: undefined
};
}
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 extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
if (process.platform === 'win32') {
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_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() {
const arch = this.getArchitectureOptions();
const [bundleType, features] = this.packageType.split('+');
const platform = this.getPlatformOption();
const extension = (0,_util_js__WEBPACK_IMPORTED_MODULE_6__/* .getDownloadArchiveExtension */ .ag)();
const javafx = features?.includes('fx') ?? false;
const crac = features?.includes('crac') ?? false;
const releaseStatus = this.stable ? 'ga' : 'ea';
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
console.time('Retrieving available versions for Zulu took'); // eslint-disable-line no-console
}
const baseRequestArguments = [
`os=${platform}`,
`archive_type=${extension}`,
`java_package_type=${bundleType}`,
`javafx_bundled=${javafx}`,
`crac_supported=${crac}`,
`arch=${arch}`,
`release_status=${releaseStatus}`,
`availability_types=ca`
].join('&');
// Need to iterate through all pages to retrieve the list of all versions.
// The Azul API doesn't return a total page count, so paginate until a page
// comes back empty (or short), guarding against a runaway loop with a cap.
const pageSize = 100;
const maxPages = 100;
let pageIndex = 1;
const availableVersions = [];
while (pageIndex <= maxPages) {
const requestArguments = `${baseRequestArguments}&page=${pageIndex}&page_size=${pageSize}`;
const availableVersionsUrl = `https://api.azul.com/metadata/v1/zulu/packages/?${requestArguments}`;
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o() && pageIndex === 1) {
// the url is identical except for the page number, so print it once for debug
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Gathering available versions from '${availableVersionsUrl}'`);
}
const paginationPage = (await this.http.getJson(availableVersionsUrl)).result;
if (!paginationPage || paginationPage.length === 0) {
// stop paginating because we have reached the end of the results
break;
}
availableVersions.push(...paginationPage);
if (paginationPage.length < pageSize) {
// a short page means this was the last one; avoid an extra empty request
break;
}
pageIndex++;
}
if (pageIndex > maxPages) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .warning */ .$e(`Reached the maximum of ${maxPages} pages while listing Zulu versions; results may be truncated.`);
}
if (_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .isDebug */ ._o()) {
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .startGroup */ .Oh('Print information about available versions');
console.timeEnd('Retrieving available versions for Zulu took'); // eslint-disable-line no-console
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(`Available versions: [${availableVersions.length}]`);
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .debug */ .Yz(availableVersions.map(item => item.java_version.join('.')).join(', '));
_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .endGroup */ .N4();
}
return availableVersions;
}
getArchitectureOptions() {
const arch = this.distributionArchitecture();
switch (arch) {
case 'x64':
return 'x64';
case 'x86':
// The Azul Metadata API's "x86" value returns both 32-bit (i686) and
// 64-bit (x64) packages, which are indistinguishable by version and
// would let a 32-bit request resolve to a 64-bit JDK. Use "i686" to
// target only genuine 32-bit builds, matching the legacy API behavior.
return 'i686';
case 'armv7':
return 'arm';
case 'aarch64':
case 'arm64':
return 'aarch64';
default:
return arch;
}
}
getPlatformOption() {
// Azul has own platform names so need to map them
switch (process.platform) {
case 'darwin':
return 'macos';
case 'win32':
return 'windows';
case 'linux':
// 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;
}
}
}
/***/ })
};
+3259 -99055
View File
File diff suppressed because it is too large Load Diff
+201 -33
View File
@@ -1,13 +1,14 @@
# Usage
- [Selecting a Java distribution](#Selecting-a-Java-distribution)
- [Eclipse Temurin](#Eclipse-Temurin)
- [Adopt](#Adopt)
- [Zulu](#Zulu)
- [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)
@@ -18,13 +19,17 @@
- [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)
- [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)
@@ -33,8 +38,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
@@ -49,19 +63,6 @@ steps:
- run: java --version
```
### Adopt
**NOTE:** Adopt OpenJDK got moved to Eclipse Temurin and won't be updated anymore. It is highly recommended to migrate workflows from `adopt` to `temurin` to keep receiving software and security updates. See more details in the [Good-bye AdoptOpenJDK post](https://blog.adoptopenjdk.net/2021/08/goodbye-adoptopenjdk-hello-adoptium/).
```yaml
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: 'adopt-hotspot'
java-version: '11'
- run: java --version
```
### Zulu
```yaml
@@ -130,6 +131,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.
@@ -305,11 +320,9 @@ The package types have these meanings:
| Distribution | Supported `java-package` values | Version support and important details |
| --- | --- | --- |
| `temurin` | `jdk`, `jre`, `jdk+jmods` | `jdk` and `jre` follow the Adoptium catalog. `jdk+jmods` is available for Java 24 and later and resolves both artifacts at the exact same Java version. |
| `adopt`, `adopt-hotspot` | `jdk`, `jre` | HotSpot requests check Temurin first, then fall back to the archived AdoptOpenJDK catalog (Java 8 through 16). Migrate to `temurin` for supported releases. |
| `adopt-openj9` | `jdk`, `jre` | Uses the archived AdoptOpenJDK OpenJ9 catalog, which ended at Java 16. Migrate to `semeru`. Some historical JRE/platform combinations were not published. |
| `zulu` | `jdk`, `jre`, `jdk+fx`, `jre+fx`, `jdk+crac`, `jre+crac` | Standard JDK builds go back to Java 6; JRE and JavaFX bundles start at Java 8. The vendor catalog has gaps among older non-LTS releases. CRaC bundles start at Java 17 and have more limited OS and architecture availability. |
| `liberica` | `jdk`, `jre`, `jdk+fx`, `jre+fx` | Standard JDK builds go back to Java 8 in the supported action catalog; JRE and JavaFX "full" bundles also start at Java 8. Exact versions follow BellSoft's catalog for the requested platform. |
| `liberica-nik` | `jdk`, `jdk+fx` | `java-version` selects the embedded JDK version, not the NIK/GraalVM release number. BellSoft currently publishes matching standard and JavaFX "full" bundles for JDK 11 and later, with gaps between feature releases. Other values are not meaningful: they resolve to the standard bundle. |
| `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`. |
@@ -321,12 +334,10 @@ The package types have these meanings:
| `graalvm-community` | `jdk` | Stable GraalVM Community releases for JDK 17 and later only. |
| `jetbrains` | `jdk`, `jre`, `jdk+jcef`, `jre+jcef`, `jdk+ft`, `jre+ft` | JetBrains publishes selected LTS-based releases rather than every OpenJDK patch. JDK/JRE and JCEF bundles start with the Java 11 release family; FreeType bundles start with Java 17. Exact package, LTS family, patch, OS, and architecture availability is determined from release assets. |
| `kona` | `jdk` | Stable Java 8, 11, 17, 21, and 25 releases only. |
| `jdkfile` | `jdk` (recommended) | The package contents and version are supplied by `jdk-file`; `setup-java` does not validate them. `java-package` only separates the local archive's tool-cache entry, so use `jdk` unless separate cache namespaces are required. |
| `jdkfile` | `jdk` | The package contents and version are supplied by `jdk-file`; `setup-java` validates the package type but does not inspect the archive contents. |
Values outside this table are unsupported even when a distribution forwards the
value to its vendor API instead of rejecting it immediately. In that case, the
action normally fails with a version-not-found error because no matching
artifact exists.
Values outside this table are unsupported. The action rejects them before
checking the tool cache or requesting a vendor catalog.
```yaml
steps:
@@ -486,6 +497,163 @@ 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
or contacts a vendor. `amd64`, `ia32`, `arm`, and `arm64` are accepted aliases
for `x64`, `x86`, `armv7`, and `aarch64`. The table lists the combinations
setup-java validates up front; an individual Java patch release can still be
absent from a vendor catalog.
| Distribution | Linux | macOS | Windows | Other / version restrictions |
| --- | --- | --- | --- | --- |
| `temurin` | `x64`, `x86`, `armv7`, `aarch64`, `ppc64le`, `s390x` | `x64`, `aarch64` | `x64`, `x86`, `aarch64` | Linux `armv7` is available through Java 17. |
| `zulu` | `x64`, `x86`, `armv7`, `aarch64` | `x64`, `aarch64` | `x64`, `x86`, `aarch64` | |
| `liberica` | `x64`, `x86`, `armv7`, `aarch64`, `ppc64le` | `x64`, `aarch64` | `x64`, `x86`, `aarch64` | Solaris: `x64`. |
| `liberica-nik` | `x64`, `aarch64` | `x64`, `aarch64` | `x64`, `aarch64` | |
| `microsoft` | `x64`, `aarch64` | `x64`, `aarch64` | `x64`, `aarch64` | |
| `semeru` | `x64`, `x86`, `ppc64le`, `ppc64`, `s390x`, `aarch64` | `x64`, `aarch64` | `x64`, `aarch64` | |
| `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` | |
| `dragonwell` | `x64`, `aarch64` | — | `x64` | |
| `sapmachine` | `x64`, `aarch64`, `ppc64le` | `x64`, `aarch64` | `x64`, `aarch64` | |
| `graalvm`, `graalvm-community` | `x64`, `aarch64` | `x64`, `aarch64` | `x64` | |
| `jetbrains` | `x64`, `aarch64` | `x64`, `aarch64` | `x64`, `aarch64` | |
| `kona` | `x64`, `aarch64` | `x64`, `aarch64` | `x64` | |
| `jdkfile` | Any | Any | Any | Local archives are not restricted because setup-java does not inspect their contents. |
Unsupported combinations fail with a platform-capability error before a cache
lookup or vendor request. A supported combination can still produce a
version-not-found error when the requested release was not published.
## Installing custom Java architecture
```yaml
@@ -536,7 +704,7 @@ If your use-case requires a custom distribution or a version that is not provide
```yaml
steps:
- run: |
download_url="https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_linux_hotspot_11.0.10_9.tar.gz"
download_url="https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.12%2B7/OpenJDK11U-jdk_x64_linux_hotspot_11.0.12_7.tar.gz"
wget -O $RUNNER_TEMP/java_package.tar.gz $download_url
- uses: actions/setup-java@v6
with:
@@ -578,7 +746,7 @@ steps:
```yaml
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
strategy:
matrix:
distribution: [ 'zulu', 'temurin' ]
@@ -594,7 +762,7 @@ jobs:
- run: java --version
```
#### Testing against different platforms
## Testing against different platforms
```yaml
jobs:
build:
@@ -705,7 +873,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`.
@@ -892,9 +1060,9 @@ See the help docs on [Publishing a Package with Gradle](https://help.github.com/
## Hosted Tool Cache
GitHub Hosted Runners have a tool cache that comes with some Java versions pre-installed. This tool cache helps speed up runs and tool setup by not requiring any new downloads. There is an environment variable called `RUNNER_TOOL_CACHE` on each runner that describes the location of this tools cache and this is where you can find the pre-installed versions of Java. `setup-java` works by taking a specific version of Java in this tool cache and adding it to PATH if the version, architecture and distribution match.
Currently, LTS versions of Eclipse Temurin (`temurin`) are cached on the GitHub Hosted Runners.
Currently, LTS versions of Eclipse Temurin (`temurin`) are cached on GitHub-hosted runners. Using a cached version avoids downloading a JDK.
The tools cache gets updated on a weekly basis. For information regarding locally cached versions of Java on GitHub hosted runners, check out [GitHub Actions Virtual Environments](https://github.com/actions/virtual-environments).
The tools cache gets updated on a weekly basis. 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).
## Modifying Maven Toolchains
The `setup-java` action generates a basic [Maven Toolchains declaration](https://maven.apache.org/guides/mini/guide-using-toolchains.html) for specified Java versions by either creating a minimal toolchains file or extending an existing declaration with the additional JDKs.
@@ -933,7 +1101,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.
@@ -967,7 +1135,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:
@@ -980,7 +1148,7 @@ steps:
- run: java --version
```
In case you install multiple versions of Java at once you can use the same syntax as used in `java-versions`. Please note that you have to declare an ID for all Java versions that will be installed or the `mvn-toolchain-id` instruction will be skipped wholesale due to mapping ambiguities.
When installing multiple Java versions, use the same multiline syntax as `java-version`. You must declare exactly one ID for every Java version that will be installed. The action fails before installing a JDK unless the number of `mvn-toolchain-id` entries matches the number of `java-version` entries, or is exactly one when `java-version-file` is used.
```yaml
steps:
@@ -1132,7 +1300,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
+5 -96
View File
@@ -16,8 +16,8 @@
"@actions/http-client": "^4.0.1",
"@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0",
"semver": "^7.8.5",
"xmlbuilder2": "^4.0.3"
"fast-xml-parser": "^5.10.1",
"semver": "^7.8.5"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
@@ -1566,54 +1566,6 @@
],
"license": "MIT"
},
"node_modules/@oozcitak/dom": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@oozcitak/dom/-/dom-2.0.2.tgz",
"integrity": "sha512-GjpKhkSYC3Mj4+lfwEyI1dqnsKTgwGy48ytZEhm4A/xnH/8z9M3ZVXKr/YGQi3uCLs1AEBS+x5T2JPiueEDW8w==",
"license": "MIT",
"dependencies": {
"@oozcitak/infra": "^2.0.2",
"@oozcitak/url": "^3.0.0",
"@oozcitak/util": "^10.0.0"
},
"engines": {
"node": ">=20.0"
}
},
"node_modules/@oozcitak/infra": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@oozcitak/infra/-/infra-2.0.2.tgz",
"integrity": "sha512-2g+E7hoE2dgCz/APPOEK5s3rMhJvNxSMBrP+U+j1OWsIbtSpWxxlUjq1lU8RIsFJNYv7NMlnVsCuHcUzJW+8vA==",
"license": "MIT",
"dependencies": {
"@oozcitak/util": "^10.0.0"
},
"engines": {
"node": ">=20.0"
}
},
"node_modules/@oozcitak/url": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@oozcitak/url/-/url-3.0.0.tgz",
"integrity": "sha512-ZKfET8Ak1wsLAiLWNfFkZc/BraDccuTJKR6svTYc7sVjbR+Iu0vtXdiDMY4o6jaFl5TW2TlS7jbLl4VovtAJWQ==",
"license": "MIT",
"dependencies": {
"@oozcitak/infra": "^2.0.2",
"@oozcitak/util": "^10.0.0"
},
"engines": {
"node": ">=20.0"
}
},
"node_modules/@oozcitak/util": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@oozcitak/util/-/util-10.0.0.tgz",
"integrity": "sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA==",
"license": "MIT",
"engines": {
"node": ">=20.0"
}
},
"node_modules/@pkgr/core": {
"version": "0.3.6",
"resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz",
@@ -2683,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"
@@ -6042,49 +5994,6 @@
"node": ">=16.0.0"
}
},
"node_modules/xmlbuilder2": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/xmlbuilder2/-/xmlbuilder2-4.0.3.tgz",
"integrity": "sha512-bx8Q1STctnNaaDymWnkfQLKofs0mGNN7rLLapJlGuV3VlvegD7Ls4ggMjE3aUSWItCCzU0PEv45lI87iSigiCA==",
"license": "MIT",
"dependencies": {
"@oozcitak/dom": "^2.0.2",
"@oozcitak/infra": "^2.0.2",
"@oozcitak/util": "^10.0.0",
"js-yaml": "^4.1.1"
},
"engines": {
"node": ">=20.0"
}
},
"node_modules/xmlbuilder2/node_modules/argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
"license": "Python-2.0"
},
"node_modules/xmlbuilder2/node_modules/js-yaml": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/puzrin"
},
{
"type": "github",
"url": "https://github.com/sponsors/nodeca"
}
],
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+4 -4
View File
@@ -9,7 +9,7 @@
"node": ">=24.0.0"
},
"scripts": {
"build": "ncc build -o dist/setup src/setup-java.ts && ncc build -o dist/cleanup src/cleanup-java.ts",
"build": "node scripts/patch-is-unsafe.mjs && ncc build -o dist/setup src/setup-java.ts && ncc build -o dist/cleanup src/cleanup-java.ts",
"format": "prettier --no-error-on-unmatched-pattern --write \"**/*.{ts,yml,yaml}\"",
"format-check": "prettier --no-error-on-unmatched-pattern --check \"**/*.{ts,yml,yaml}\"",
"lint": "eslint \"**/*.ts\"",
@@ -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/index.js 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": {
@@ -49,8 +49,8 @@
"@actions/http-client": "^4.0.1",
"@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0",
"semver": "^7.8.5",
"xmlbuilder2": "^4.0.3"
"fast-xml-parser": "^5.10.1",
"semver": "^7.8.5"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
+20
View File
@@ -0,0 +1,20 @@
import {readFile, writeFile} from 'node:fs/promises';
const sourcePath = new URL('../node_modules/is-unsafe/src/contexts/xml.js', import.meta.url);
const vulnerablePattern = 'pattern: /-->/,';
const safePattern = 'pattern: /--!?>/,';
const source = await readFile(sourcePath, 'utf8');
// CodeQL treats this XML detector as an incomplete HTML comment-end filter.
if (source.includes(safePattern)) {
process.exit(0);
}
const occurrences = source.split(vulnerablePattern).length - 1;
if (occurrences !== 1) {
throw new Error(
`Expected one ${JSON.stringify(vulnerablePattern)} in ${sourcePath.pathname}, found ${occurrences}`
);
}
await writeFile(sourcePath, source.replace(vulnerablePattern, safePattern));
+42 -42
View File
@@ -4,11 +4,10 @@ import * as io from '@actions/io';
import * as fs from 'fs';
import * as os from 'os';
import {create as xmlCreate} from 'xmlbuilder2';
import * as constants from './constants.js';
import * as gpg from './gpg.js';
import {getBooleanInput} from './util.js';
import {escapeXmlText} from './xml.js';
export async function configureAuthentication() {
const id = core.getInput(constants.INPUT_SERVER_ID);
@@ -53,8 +52,14 @@ export async function configureAuthentication() {
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;
}
}
}
@@ -101,53 +106,48 @@ export function generate(
passwordEnvVar: string,
gpgPassphraseEnvVar?: string | undefined
) {
const xmlObj: {[key: string]: any} = {
settings: {
'@xmlns': 'http://maven.apache.org/SETTINGS/1.0.0',
'@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,
servers: {
server: [
{
id: id,
username: `\${env.${usernameEnvVar}}`,
password: `\${env.${passwordEnvVar}}`
}
]
}
}
};
// 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;
// otherwise the plugin already reads the right variable and no extra settings
// are needed. Writing `gpg.passphrase` to settings.xml is deprecated and fails
// when the plugin's `bestPractices` mode is enabled.
if (
const includeGpgPassphraseProfile =
gpgPassphraseEnvVar &&
gpgPassphraseEnvVar !== constants.MAVEN_GPG_PASSPHRASE_DEFAULT_ENV
) {
xmlObj.settings.profiles = {
profile: {
id: constants.GPG_PASSPHRASE_PROFILE_ID,
properties: {
'gpg.passphraseEnvName': gpgPassphraseEnvVar
}
}
};
xmlObj.settings.activeProfiles = {
activeProfile: constants.GPG_PASSPHRASE_PROFILE_ID
};
gpgPassphraseEnvVar !== constants.MAVEN_GPG_PASSPHRASE_DEFAULT_ENV;
const lines = [
'<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"',
' 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>'
];
if (includeGpgPassphraseProfile) {
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>'
);
}
return xmlCreate(xmlObj).end({
headless: true,
prettyPrint: true,
width: 80
});
lines.push('</settings>');
return lines.join('\n');
}
async function write(
+21
View File
@@ -0,0 +1,21 @@
import * as cache from '@actions/cache';
import * as core from '@actions/core';
import {isGhes} from './util.js';
export function isCacheFeatureAvailable(): boolean {
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;
}
+107 -27
View File
@@ -9,6 +9,7 @@ import * as core from '@actions/core';
import * as glob from '@actions/glob';
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';
@@ -36,6 +37,11 @@ interface AdditionalCache {
pattern: string[];
}
interface PreparedAdditionalCache {
cache: AdditionalCache;
primaryKey: string;
}
interface PackageManager {
id: 'maven' | 'gradle' | 'sbt';
/**
@@ -131,6 +137,29 @@ function findPackageManager(id: string): PackageManager {
return packageManager;
}
function resolveCachePaths(
packageManager: PackageManager,
cachePaths: string[]
): string[] {
return cachePaths.length > 0 ? cachePaths : packageManager.path;
}
function getCachePathsFromState(packageManager: PackageManager): string[] {
const cachePathsState = core.getState(STATE_CACHE_PATHS);
if (!cachePathsState) {
return packageManager.path;
}
const cachePaths: unknown = 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.
@@ -184,18 +213,52 @@ async function computeAdditionalCacheKey(
/**
* Restore the dependency cache
* @param id ID of the package manager, should be "maven" or "gradle"
* @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
*/
export async function restore(id: string, cacheDependencyPath: string) {
export async function restore(
id: string,
cacheDependencyPath: string,
cachePaths: string[] = []
) {
const packageManager = findPackageManager(id);
const primaryKey = await computeCacheKey(packageManager, cacheDependencyPath);
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: PackageManager,
cachePaths: string[],
primaryKey: string
) {
// 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(packageManager.path, primaryKey);
const matchedKey = await cache.restoreCache(cachePaths, primaryKey);
if (matchedKey) {
core.saveState(CACHE_MATCHED_KEY, matchedKey);
core.setOutput('cache-hit', matchedKey === primaryKey);
@@ -204,32 +267,39 @@ export async function restore(id: string, cacheDependencyPath: string) {
core.setOutput('cache-hit', false);
core.info(`${packageManager.id} cache is not found`);
}
for (const additionalCache of packageManager.additionalCaches ?? []) {
await restoreAdditionalCache(additionalCache);
}
}
/**
* Restore an additional cache (e.g. a build-tool wrapper distribution) that is
* keyed independently of the main dependency cache so that it survives changes
* to volatile dependency files. Skips silently when the project does not use
* the corresponding feature.
* Compute keys for additional caches (e.g. build-tool wrapper distributions).
* Additional caches without a matching configuration file are omitted.
*/
async function restoreAdditionalCache(additionalCache: AdditionalCache) {
const primaryKey = await computeAdditionalCacheKey(additionalCache);
if (!primaryKey) {
core.debug(
`No file matched [${additionalCache.pattern}] for the ${additionalCache.name} cache, skipping.`
);
return;
}
core.debug(`${additionalCache.name} primary key is ${primaryKey}`);
core.saveState(
additionalCachePrimaryKeyState(additionalCache.name),
primaryKey
async function prepareAdditionalCaches(
additionalCaches: AdditionalCache[]
): Promise<PreparedAdditionalCache[]> {
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 is PreparedAdditionalCache =>
preparedCache !== undefined
);
}
/**
* Restore an additional cache keyed independently of the main dependency cache.
*/
async function restoreAdditionalCache(preparedCache: PreparedAdditionalCache) {
const {cache: additionalCache, primaryKey} = preparedCache;
const matchedKey = await cache.restoreCache(additionalCache.path, primaryKey);
if (matchedKey) {
core.saveState(
@@ -237,6 +307,8 @@ async function restoreAdditionalCache(additionalCache: AdditionalCache) {
matchedKey
);
core.info(`${additionalCache.name} cache restored from key: ${matchedKey}`);
} else {
core.info(`${additionalCache.name} cache is not found`);
}
}
@@ -246,13 +318,21 @@ async function restoreAdditionalCache(additionalCache: AdditionalCache) {
*/
export async function save(id: string) {
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 ?? []) {
await saveAdditionalCache(packageManager, additionalCache);
try {
await saveAdditionalCache(packageManager, additionalCache);
} catch (error) {
const err = error as Error;
core.warning(
`Failed to save ${additionalCache.name} cache: ${err.message}. Continuing with primary cache save.`
);
}
}
if (!primaryKey) {
@@ -266,7 +346,7 @@ export async function save(id: string) {
return;
}
try {
const cacheId = await cache.saveCache(packageManager.path, primaryKey);
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
@@ -360,7 +440,7 @@ async function saveAdditionalCache(
} 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.'
`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;
+83
View File
@@ -0,0 +1,83 @@
import {createHash, timingSafeEqual} from 'crypto';
import {createReadStream} from 'fs';
import {pipeline} from 'stream/promises';
import {ChecksumMetadata} from './distributions/base-models.js';
export interface ChecksumVerificationContext {
distribution: string;
version: string;
}
function sanitizedSource(source: string | undefined): string {
if (!source) {
return '';
}
try {
const url = new URL(source);
return ` from ${url.origin}${url.pathname}`;
} catch {
return ' from an invalid checksum source';
}
}
// Length, in hex characters, of a digest produced by each supported algorithm.
// Exported so callers (e.g. fetchChecksum) can infer which algorithm a vendor
// actually used when it doesn't disclose it via the checksum URL/filename.
export function expectedDigestLength(
algorithm: ChecksumMetadata['algorithm']
): number {
return algorithm === 'sha256' ? 64 : algorithm === 'sha512' ? 128 : 0;
}
function normalizeExpectedDigest(checksum: ChecksumMetadata): string {
const algorithm = checksum.algorithm;
const digest =
typeof checksum.value === 'string'
? checksum.value.trim().toLowerCase()
: '';
const expectedLength = expectedDigestLength(algorithm);
if (expectedLength === 0) {
throw new Error(
`Unsupported checksum algorithm '${String(algorithm)}'${sanitizedSource(checksum.source)}. Supported algorithms are sha256 and sha512.`
);
}
if (!new RegExp(`^[a-f0-9]{${expectedLength}}$`).test(digest)) {
throw new Error(
`Malformed ${algorithm} checksum metadata${sanitizedSource(checksum.source)}: expected a ${expectedLength}-character hexadecimal digest.`
);
}
return digest;
}
export async function calculateChecksum(
filePath: string,
algorithm: ChecksumMetadata['algorithm']
): Promise<string> {
const hash = createHash(algorithm);
await pipeline(createReadStream(filePath), hash);
return hash.digest('hex');
}
export async function verifyChecksum(
filePath: string,
checksum: ChecksumMetadata,
context: ChecksumVerificationContext
): Promise<void> {
const expected = normalizeExpectedDigest(checksum);
const actual = await calculateChecksum(filePath, checksum.algorithm);
const matches = timingSafeEqual(
Buffer.from(expected, 'hex'),
Buffer.from(actual, 'hex')
);
if (!matches) {
throw new Error(
`Checksum verification failed for ${context.distribution} version ${context.version}: ${checksum.algorithm} expected ${expected}, actual ${actual}.`
);
}
}

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