Merge branch 'main' into include-versions.properties-in-cache-key

This commit is contained in:
Ivan Zosimov 2023-07-20 12:23:28 +02:00
commit 450ead13d3
103 changed files with 143854 additions and 125027 deletions

6
.eslintignore Normal file
View File

@ -0,0 +1,6 @@
# Ignore list
/*
# Do not ignore these folders:
!__tests__/
!src/

51
.eslintrc.js Normal file
View File

@ -0,0 +1,51 @@
// This is a reusable configuration file copied from https://github.com/actions/reusable-workflows/tree/main/reusable-configurations. Please don't make changes to this file as it's the subject of an automatic update.
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:eslint-plugin-jest/recommended',
'eslint-config-prettier'
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'eslint-plugin-node', 'eslint-plugin-jest'],
rules: {
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-ignore': 'allow-with-description'
}
],
'no-console': 'error',
'yoda': 'error',
'prefer-const': [
'error',
{
destructuring: 'all'
}
],
'no-control-regex': 'off',
'no-constant-condition': ['error', {checkLoops: false}],
'node/no-extraneous-import': 'error'
},
overrides: [
{
files: ['**/*{test,spec}.ts'],
rules: {
'@typescript-eslint/no-unused-vars': 'off',
'jest/no-standalone-expect': 'off',
'jest/no-conditional-expect': 'off',
'no-console': 'off',
}
}
],
env: {
node: true,
es6: true,
'jest/globals': true
}
};

1
.gitattributes vendored
View File

@ -1,3 +1,4 @@
* text=auto eol=lf
dist/index.js -diff -merge
dist/index.js linguist-generated=true
.licenses/** -diff linguist-generated=true

3
.github/CODEOWNERS vendored
View File

@ -1,2 +1 @@
* @actions/actions-service
* @actions/virtual-environments-owners
* @actions/setup-actions-team

View File

@ -1 +1 @@
blank_issues_enabled: false
blank_issues_enabled: false

17
.github/workflows/basic-validation.yml vendored Normal file
View File

@ -0,0 +1,17 @@
name: Basic validation
on:
push:
branches:
- main
- releases/*
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
jobs:
call-basic-validation:
name: Basic validation
uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@main

View File

@ -1,31 +0,0 @@
name: Build Action
on:
push:
branches:
- main
- releases/*
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v2
- name: Setup Node.JS 12
uses: actions/setup-node@v2
with:
node-version: 12.x
cache: npm
- run: npm ci
- run: npm run build
- run: npm run format-check
- run: npm test

View File

@ -1,8 +1,3 @@
# `dist/index.js` is a special file in Actions.
# When you reference an action with `uses:` in a workflow,
# `index.js` is the code that will run.
# For our project, we generate this file through a build process from other source files.
# We need to make sure the checked-in `index.js` actually matches what we expect it to be.
name: Check dist/
on:
@ -17,35 +12,6 @@ on:
workflow_dispatch:
jobs:
check-dist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set Node.js 12.x
uses: actions/setup-node@v1
with:
node-version: 12.x
- name: Install dependencies
run: npm ci
- name: Rebuild the dist/ directory
run: npm run build
- name: Compare the expected and actual dist/ directories
run: |
if [ "$(git diff --ignore-space-at-eol dist/ | wc -l)" -gt "0" ]; then
echo "Detected uncommitted changes after build. See status below:"
git diff
exit 1
fi
id: diff
# If index.js was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v2
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with:
name: dist
path: dist/
call-check-dist:
name: Check dist/
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main

14
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,14 @@
name: CodeQL analysis
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 3 * * 0'
jobs:
call-codeQL-analysis:
name: CodeQL analysis
uses: actions/reusable-workflows/.github/workflows/codeql-analysis.yml@main

View File

@ -1,4 +1,5 @@
name: Validate cache
on:
push:
branches:
@ -23,7 +24,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Run setup-java with the cache for gradle
uses: ./
id: setup-java
@ -49,7 +50,7 @@ jobs:
needs: gradle-save
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Run setup-java with the cache for gradle
uses: ./
id: setup-java
@ -72,7 +73,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Run setup-java with the cache for maven
uses: ./
id: setup-java
@ -96,7 +97,7 @@ jobs:
needs: maven-save
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Run setup-java with the cache for maven
uses: ./
id: setup-java
@ -111,3 +112,98 @@ jobs:
exit 1
fi
ls ~/.m2/repository
sbt-save:
runs-on: ${{ matrix.os }}
defaults:
run:
shell: bash
working-directory: __tests__/cache/sbt
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Run setup-java with the cache for sbt
uses: ./
id: setup-java
with:
distribution: 'adopt'
java-version: '11'
cache: sbt
- name: Create files to cache
run: sbt update
- name: Check files to cache on macos-latest
if: matrix.os == 'macos-latest'
run: |
if [ ! -d ~/Library/Caches/Coursier ]; then
echo "::error::The ~/Library/Caches/Coursier directory does not exist unexpectedly"
exit 1
fi
- name: Check files to cache on windows-latest
if: matrix.os == 'windows-latest'
run: |
if [ ! -d ~/AppData/Local/Coursier/Cache ]; then
echo "::error::The ~/AppData/Local/Coursier/Cache directory does not exist unexpectedly"
exit 1
fi
- name: Check files to cache on ubuntu-latest
if: matrix.os == 'ubuntu-latest'
run: |
if [ ! -d ~/.cache/coursier ]; then
echo "::error::The ~/.cache/coursier directory does not exist unexpectedly"
exit 1
fi
sbt-restore:
runs-on: ${{ matrix.os }}
defaults:
run:
shell: bash
working-directory: __tests__/cache/sbt
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
needs: sbt-save
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Run setup-java with the cache for sbt
uses: ./
id: setup-java
with:
distribution: 'adopt'
java-version: '11'
cache: sbt
- name: Confirm that ~/Library/Caches/Coursier directory has been made
if: matrix.os == 'macos-latest'
run: |
if [ ! -d ~/Library/Caches/Coursier ]; then
echo "::error::The ~/Library/Caches/Coursier directory does not exist unexpectedly"
exit 1
fi
ls ~/Library/Caches/Coursier
- name: Confirm that ~/AppData/Local/Coursier/Cache directory has been made
if: matrix.os == 'windows-latest'
run: |
if [ ! -d ~/AppData/Local/Coursier/Cache ]; then
echo "::error::The ~/AppData/Local/Coursier/Cache directory does not exist unexpectedly"
exit 1
fi
ls ~/AppData/Local/Coursier/Cache
- name: Confirm that ~/.cache/coursier directory has been made
if: matrix.os == 'ubuntu-latest'
run: |
if [ ! -d ~/.cache/coursier ]; then
echo "::error::The ~/.cache/coursier directory does not exist unexpectedly"
exit 1
fi
ls ~/.cache/coursier

View File

@ -1,4 +1,5 @@
name: Validate local file
on:
push:
branches:
@ -20,7 +21,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Download Adopt OpenJDK file
run: |
if ($IsLinux) {
@ -57,7 +58,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Download Zulu OpenJDK file
run: |
if ($IsLinux) {
@ -94,7 +95,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Download Eclipse Temurin file
run: |
if ($IsLinux) {

View File

@ -1,4 +1,5 @@
name: Validate publishing functionality
on:
push:
branches:
@ -24,7 +25,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -59,7 +60,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Create fake settings.xml
run: |
$xmlDirectory = Join-Path $HOME ".m2"
@ -85,7 +86,7 @@ jobs:
if ($content -notlike '*maven*') {
throw "settings.xml file is not overwritten"
}
test-publishing-skip-overwrite:
name: settings.xml is not overwritten if flag is false
runs-on: ${{ matrix.os }}
@ -95,7 +96,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Create fake settings.xml
run: |
$xmlDirectory = Join-Path $HOME ".m2"
@ -132,7 +133,7 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -149,4 +150,4 @@ jobs:
$path = Join-Path $env:RUNNER_TEMP "settings.xml"
if (-not (Test-Path $path)) {
throw "settings.xml file is not found in expected location"
}
}

View File

@ -1,4 +1,5 @@
name: Validate Java e2e
on:
push:
branches:
@ -10,7 +11,7 @@ on:
paths-ignore:
- '**.md'
schedule:
- cron: '0 */12 * * *'
- cron: '0 */12 * * *'
workflow_dispatch:
jobs:
setup-java-major-versions:
@ -20,14 +21,33 @@ jobs:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['temurin', 'adopt', 'adopt-openj9', 'zulu', 'liberica', 'microsoft' ] # internally 'adopt-hotspot' is the same as 'adopt'
version: ['8', '11', '16']
distribution: [
'temurin',
'adopt',
'adopt-openj9',
'zulu',
'liberica',
'microsoft',
'semeru',
'corretto'
] # internally 'adopt-hotspot' is the same as 'adopt'
version: ['8', '11', '17']
exclude:
- distribution: microsoft
version: 8
- distribution: microsoft
version: 8
include:
- distribution: oracle
os: macos-latest
version: 17
- distribution: oracle
os: windows-latest
version: 20
- distribution: oracle
os: ubuntu-latest
version: 20
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -48,12 +68,16 @@ jobs:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['temurin', 'zulu', 'liberica']
version:
- '11.0'
- '8.0.302'
- '16.0.2+7'
- '11.0'
- '8.0.302'
- '17.0.7+7'
include:
- distribution: oracle
os: ubuntu-latest
version: '20.0.1'
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -75,7 +99,7 @@ jobs:
distribution: ['temurin', 'zulu', 'liberica']
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -87,6 +111,43 @@ jobs:
run: bash __tests__/verify-java.sh "11" "${{ steps.setup-java.outputs.path }}"
shell: bash
setup-java-multiple-jdks:
name: ${{ matrix.distribution }} ${{ matrix.version }} - multiple jdks - ${{ matrix.os }}
needs: setup-java-major-versions
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['temurin', 'zulu', 'liberica']
steps:
- name: Checkout
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
with:
distribution: ${{ matrix.distribution }}
java-version: |
11
17
- name: Verify Java env variables
run: |
$versionsArr = "11","17"
foreach ($version in $versionsArr)
{
$envName = "JAVA_HOME_${version}_${env:RUNNER_ARCH}"
$JavaVersionPath = [Environment]::GetEnvironmentVariable($envName)
if (-not (Test-Path "$JavaVersionPath")) {
Write-Host "$envName is not found"
exit 1
}
}
shell: pwsh
- name: Verify Java
run: bash __tests__/verify-java.sh "17" "${{ steps.setup-java.outputs.path }}"
shell: bash
setup-java-ea-versions-zulu:
name: zulu ${{ matrix.version }} (jdk-x64) - ${{ matrix.os }}
needs: setup-java-major-minor-versions
@ -98,7 +159,7 @@ jobs:
version: ['17-ea', '15.0.0-ea.14']
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -120,7 +181,7 @@ jobs:
version: ['17-ea']
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -139,9 +200,9 @@ jobs:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['temurin', 'zulu', 'liberica']
distribution: ['temurin', 'zulu', 'liberica', 'semeru']
java-package: ['jre']
version: ['16.0']
version: ['17.0']
include:
- distribution: 'zulu'
java-package: jre+fx
@ -159,13 +220,13 @@ jobs:
java-package: jre+fx
version: '11'
os: ubuntu-latest
exclude:
# Eclipse Temurin currently doesn't publish JREs, only JDKs
- distribution: 'temurin'
java-package: 'jre'
- distribution: 'corretto'
java-package: jre
version: '8'
os: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -187,11 +248,11 @@ jobs:
matrix:
# x86 is not supported on macOS
os: [windows-latest, ubuntu-latest]
distribution: ['liberica', 'zulu']
distribution: ['liberica', 'zulu', 'corretto']
version: ['11']
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: setup-java
uses: ./
id: setup-java
@ -203,4 +264,99 @@ jobs:
run: bash __tests__/verify-java.sh "${{ matrix.version }}" "${{ steps.setup-java.outputs.path }}"
shell: bash
# Only Microsoft provides AArch64. However, GitHub-hosted runners do not support this architecture.
setup-java-version-both-version-inputs-presents:
name: ${{ matrix.distribution }} version (should be from input) - ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['temurin', 'microsoft', 'corretto']
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Create .java-version file
shell: bash
run: echo "8" > .java-version
- name: setup-java
uses: ./
id: setup-java
with:
distribution: ${{ matrix.distribution }}
java-version: 11
java-version-file: '.java-version'
- name: Verify Java
run: bash __tests__/verify-java.sh "11" "${{ steps.setup-java.outputs.path }}"
shell: bash
setup-java-version-from-file-major-notation:
name: ${{ matrix.distribution }} version from file X - ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['temurin', 'zulu', 'liberica', 'microsoft', 'corretto']
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Create .java-version file
shell: bash
run: echo "11" > .java-version
- name: setup-java
uses: ./
id: setup-java
with:
distribution: ${{ matrix.distribution }}
java-version-file: '.java-version'
- name: Verify Java
run: bash __tests__/verify-java.sh "11" "${{ steps.setup-java.outputs.path }}"
shell: bash
setup-java-version-from-file-major-minor-patch-notation:
name: ${{ matrix.distribution }} version from file X.Y.Z - ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['adopt', 'adopt-openj9', 'zulu']
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Create .java-version file
shell: bash
run: echo "11.0.2" > .java-version
- name: setup-java
uses: ./
id: setup-java
with:
distribution: ${{ matrix.distribution }}
java-version-file: '.java-version'
- name: Verify Java
run: bash __tests__/verify-java.sh "11.0.2" "${{ steps.setup-java.outputs.path }}"
shell: bash
setup-java-version-from-file-major-minor-patch-with-dist:
name: ${{ matrix.distribution }} version from file 'openjdk64-11.0.2' - ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
distribution: ['adopt', 'zulu', 'liberica']
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Create .java-version file
shell: bash
run: echo "openjdk64-11.0.2" > .java-version
- name: setup-java
uses: ./
id: setup-java
with:
distribution: ${{ matrix.distribution }}
java-version-file: '.java-version'
- name: Verify Java
run: bash __tests__/verify-java.sh "11.0.2" "${{ steps.setup-java.outputs.path }}"
shell: bash

View File

@ -10,16 +10,6 @@ on:
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
name: Check licenses
steps:
- uses: actions/checkout@v2
- run: npm ci
- name: Install licensed
run: |
cd $RUNNER_TEMP
curl -Lfs -o licensed.tar.gz https://github.com/github/licensed/releases/download/3.3.1/licensed-3.3.1-linux-x64.tar.gz
sudo tar -xzf licensed.tar.gz
sudo mv licensed /usr/local/bin/licensed
- run: licensed status
call-licensed:
name: Licensed
uses: actions/reusable-workflows/.github/workflows/licensed.yml@main

View File

@ -1,4 +1,5 @@
name: Release new action version
on:
release:
types: [released]
@ -20,9 +21,9 @@ jobs:
name: releaseNewActionVersion
runs-on: ubuntu-latest
steps:
- name: Update the ${{ env.TAG_NAME }} tag
id: update-major-tag
uses: actions/publish-action@v0.1.0
with:
source-tag: ${{ env.TAG_NAME }}
slack-webhook: ${{ secrets.SLACK_WEBHOOK }}
- name: Update the ${{ env.TAG_NAME }} tag
id: update-major-tag
uses: actions/publish-action@v0.2.2
with:
source-tag: ${{ env.TAG_NAME }}
slack-webhook: ${{ secrets.SLACK_WEBHOOK }}

View File

@ -0,0 +1,11 @@
name: Update configuration files
on:
schedule:
- cron: '0 3 * * 0'
workflow_dispatch:
jobs:
call-update-configuration-files:
name: Update configuration files
uses: actions/reusable-workflows/.github/workflows/update-config-files.yml@main

3
.gitignore vendored
View File

@ -94,3 +94,6 @@ typings/
# DynamoDB Local files
.dynamodb/
.vscode/
# IntelliJ / WebStorm
/.idea/

View File

@ -1,6 +1,6 @@
---
name: "@actions/cache"
version: 1.0.8
version: 3.0.4
type: npm
summary: Actions cache lib
homepage: https://github.com/actions/toolkit/tree/main/packages/cache

View File

@ -1,6 +1,6 @@
---
name: "@actions/core"
version: 1.2.6
version: 1.10.0
type: npm
summary: Actions core lib
homepage: https://github.com/actions/toolkit/tree/main/packages/core

View File

@ -29,4 +29,4 @@ licenses:
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: []
notices: []

View File

@ -0,0 +1,32 @@
---
name: "@actions/http-client"
version: 2.0.1
type: npm
summary: Actions Http Client
homepage: https://github.com/actions/toolkit/tree/main/packages/http-client
license: mit
licenses:
- sources: LICENSE
text: |
Actions Http Client for Node.js
Copyright (c) GitHub, Inc.
All rights reserved.
MIT License
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: []

View File

@ -1,32 +1,32 @@
---
name: "@azure/core-asynciterator-polyfill"
version: 1.0.0
version: 1.0.2
type: npm
summary: Polyfill for IE/Node 8 for Symbol.asyncIterator
homepage: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/core/core-asynciterator-polyfill
homepage: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/core-asynciterator-polyfill/README.md
license: mit
licenses:
- sources: LICENSE
text: |2
MIT License
text: |
The MIT License (MIT)
Copyright (c) Microsoft Corporation. All rights reserved.
Copyright (c) 2020 Microsoft
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:
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 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
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: []

View File

@ -1,6 +1,6 @@
---
name: "@azure/core-http"
version: 2.2.2
version: 3.0.1
type: npm
summary: Isomorphic client Runtime for Typescript/node.js/browser javascript client
libraries generated using AutoRest

View File

@ -1,6 +1,6 @@
---
name: "@azure/core-lro"
version: 2.2.1
version: 2.2.4
type: npm
summary: Isomorphic client library for supporting long-running operations in node.js
and browser.

View File

@ -1,6 +1,6 @@
---
name: "@azure/core-paging"
version: 1.2.0
version: 1.2.1
type: npm
summary: Core types for paging async iterable iterators
homepage: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/core-paging/README.md

32
.licenses/npm/@azure/core-util.dep.yml generated Normal file
View File

@ -0,0 +1,32 @@
---
name: "@azure/core-util"
version: 1.3.0
type: npm
summary: Core library for shared utility methods
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-util/
license: mit
licenses:
- sources: LICENSE
text: |
The MIT License (MIT)
Copyright (c) 2020 Microsoft
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: []

View File

@ -1,6 +1,6 @@
---
name: "@azure/ms-rest-js"
version: 2.6.0
version: 2.7.0
type: npm
summary: Isomorphic client Runtime for Typescript/node.js/browser javascript client
libraries generated using AutoRest

View File

@ -1,6 +1,6 @@
---
name: "@azure/storage-blob"
version: 12.8.0
version: 12.14.0
type: npm
summary: Microsoft Azure Storage SDK for JavaScript - Blob
homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/storage/storage-blob/

View File

@ -1,6 +1,6 @@
---
name: "@opentelemetry/api"
version: 1.0.3
version: 1.0.4
type: npm
summary: Public API for OpenTelemetry
homepage: https://github.com/open-telemetry/opentelemetry-js-api#readme
@ -218,10 +218,6 @@ licenses:
[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions
[license-url]: https://github.com/open-telemetry/opentelemetry-js-api/blob/main/LICENSE
[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
[dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-api.svg
[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-api
[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-api.svg?type=dev
[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-api?type=dev
[npm-url]: https://www.npmjs.com/package/@opentelemetry/api
[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fapi.svg
[docs-tracing]: https://github.com/open-telemetry/opentelemetry-js-api/blob/main/docs/tracing.md

View File

@ -1,9 +1,9 @@
---
name: "@types/node"
version: 12.20.4
version: 16.11.25
type: npm
summary: TypeScript definitions for Node.js
homepage: https://github.com/DefinitelyTyped/DefinitelyTyped#readme
homepage: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node
license: mit
licenses:
- sources: LICENSE

View File

@ -1,6 +1,6 @@
---
name: "@types/node-fetch"
version: 2.5.12
version: 2.6.3
type: npm
summary: TypeScript definitions for node-fetch
homepage: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node-fetch

View File

@ -1,6 +1,6 @@
---
name: minimatch
version: 3.0.4
version: 3.1.2
type: npm
summary: a glob matcher in javascript
homepage: https://github.com/isaacs/minimatch#readme

View File

@ -1,6 +1,6 @@
---
name: node-fetch
version: 2.6.6
version: 2.6.7
type: npm
summary: A light-weight module that brings window.fetch to node.js
homepage: https://github.com/bitinn/node-fetch

View File

@ -1,9 +1,9 @@
---
name: semver
version: 7.3.4
version: 7.3.8
type: npm
summary: The semantic version parser used by npm.
homepage: https://github.com/npm/node-semver#readme
homepage:
license: isc
licenses:
- sources: LICENSE

26
.licenses/npm/semver-7.5.4.dep.yml generated Normal file
View File

@ -0,0 +1,26 @@
---
name: semver
version: 7.5.4
type: npm
summary: The semantic version parser used by npm.
homepage:
license: isc
licenses:
- sources: LICENSE
text: |
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, 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: []

View File

@ -1,23 +0,0 @@
---
name: tough-cookie
version: 4.0.0
type: npm
summary: RFC6265 Cookies and Cookie Jar for node.js
homepage: https://github.com/salesforce/tough-cookie
license: bsd-3-clause
licenses:
- sources: LICENSE
text: |
Copyright (c) 2015, Salesforce.com, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
notices: []

35
.licenses/npm/tslib-2.5.0.dep.yml generated Normal file
View File

@ -0,0 +1,35 @@
---
name: tslib
version: 2.5.0
type: npm
summary: Runtime library for TypeScript helper functions
homepage: https://www.typescriptlang.org/
license: 0bsd
licenses:
- sources: LICENSE.txt
text: |-
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
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:
- sources: CopyrightNotice.txt
text: "/******************************************************************************\r\nCopyright
(c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute
this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE
SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD
TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS
SOFTWARE.\r\n*****************************************************************************
*/"

View File

@ -1,33 +0,0 @@
---
name: universalify
version: 0.1.2
type: npm
summary: Make a callback- or promise-based function support both promises and callbacks.
homepage: https://github.com/RyanZim/universalify#readme
license: mit
licenses:
- sources: LICENSE
text: |
(The MIT License)
Copyright (c) 2017, Ryan Zimmerman <opensrc@ryanzim.com>
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.
- sources: README.md
text: MIT
notices: []

View File

@ -1,6 +1,6 @@
---
name: xml2js
version: 0.4.23
version: 0.5.0
type: npm
summary: Simple XML to JavaScript object converter.
homepage: https://github.com/Leonidas-from-XIV/node-xml2js

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
# Ignore list
/*
# Do not ignore these folders:
!__tests__/
!.github/
!src/

11
.prettierrc.js Normal file
View File

@ -0,0 +1,11 @@
// This is a reusable configuration file copied from https://github.com/actions/reusable-workflows/tree/main/reusable-configurations. Please don't make changes to this file as it's the subject of an automatic update.
module.exports = {
printWidth: 80,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: false,
arrowParens: 'avoid'
};

View File

@ -1,11 +0,0 @@
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "avoid",
"parser": "typescript"
}

76
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at opensource+actions/setup-java@github.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@ -1,38 +0,0 @@
# Contributors
### Checkin
- Do checkin source (src)
- Do checkin a single index.js file after running `ncc`
- Do not checking node_modules
### NCC
In order to avoid uploading `node_modules` to the repository, we use [zeit/ncc](https://github.com/zeit/ncc) to create multiple `index.js` files that gets saved under `dist/`.
There are two main files that get created
- `dist/setup/index.js`
- Core `setup-java` logic that downloads and installs an appropriate version of Java
- Handling creating a `settings.xml` file to make it easier to publish packages
- `dist/cleanup/index/js`
- Extra cleanup script that is used to remove GPG keys (needed for certain self-hosted runner scenarios)
If you're developing locally, after doing `npm install`, you can use the following commands
```yaml
npm run build # runs tsc along with ncc
npm run format # runs prettier --write
npm run format-check # runs prettier --check
npm run test # runs jest
npm run release # add all the necessary ncc files under dist/* to the git staging area
```
Any files generated using `tsc` will be added to `lib/*`, however those files also are not uploaded to the repository and are excluded using `.gitignore`.
### Testing
Tests are included under `_tests_/*` and can be run using `npm run-script test`.
We ask that you include a link to a successful run that utilizes the changes you are working on. For example, if your changes are in the branch `newAwesomeFeature`, then show an example run that uses `setup-python@newAwesomeFeature` or `my-fork@newAwesomeFeature`. This will help speed up testing and help us confirm that there are no breaking changes or bugs.
### Licensed
This repository uses a tool called [Licensed](https://github.com/github/licensed) to verify third party dependencies. You may need to locally install licensed and run `licensed cache` to update the dependency cache if you install or update a production dependency. If licensed cache is unable to determine the dependency, you may need to modify the cache file yourself to put the correct license. You should still verify the dependency, licensed is a tool to help, but is not a substitute for human review of dependencies.

187
README.md
View File

@ -1,47 +1,89 @@
# setup-java
# Setup Java
<p align="left">
<a href="https://github.com/actions/setup-java"><img alt="GitHub Actions status" src="https://github.com/actions/setup-java/workflows/Main%20workflow/badge.svg"></a>
</p>
[![Basic validation](https://github.com/actions/setup-java/actions/workflows/basic-validation.yml/badge.svg?branch=main)](https://github.com/actions/setup-java/actions/workflows/basic-validation.yml)
[![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)
This 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
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.
This action allows you to work with Java and Scala projects.
## V2 vs V1
- V2 supports custom distributions and provides support for Zulu OpenJDK, Eclipse Temurin and Adopt OpenJDK out of the box. V1 supports only Zulu OpenJDK
- V2 requires you to specify distribution along with the version. V1 defaults to Zulu OpenJDK, only version input is required. Follow [the migration guide](docs/switching-to-v2.md) to switch from V1 to V2
- V2 supports custom distributions and provides support for Azul Zulu OpenJDK, Eclipse Temurin and AdoptOpenJDK out of the box. V1 supports only Azul Zulu OpenJDK.
- V2 requires you to specify distribution along with the version. V1 defaults to Azul Zulu OpenJDK, only version input is required. Follow [the migration guide](docs/switching-to-v2.md) to switch from V1 to V2.
## Usage
Inputs `java-version` and `distribution` are mandatory. See [Supported distributions](#supported-distributions) section for a list of available options.
### Basic
**Eclipse Temurin**
- `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.
- `java-version-file`: The path to the `.java-version` file. See more details in [about `.java-version` file](docs/advanced-usage.md#Java-version-file).
- `distribution`: _(required)_ Java [distribution](#supported-distributions).
- `java-package`: The packaging variant of the choosen distribution. Possible values: `jdk`, `jre`, `jdk+fx`, `jre+fx`. Default value: `jdk`.
- `architecture`: The target architecture of the package. Possible values: `x86`, `x64`, `armv7`, `aarch64`, `ppc64le`. Default value: Derived from the runner machine.
- `jdkFile`: 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.
- `check-latest`: Setting this option makes the action to check for the latest available version for the version spec.
- `cache`: Quick [setup caching](#caching-packages-dependencies) for the dependencies managed through one of the predifined package managers. It can be one of "maven", "gradle" or "sbt".
#### 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`: Environment variable name for the username for authentication to the Apache Maven repository. Default is GITHUB_ACTOR.
- `server-password`: 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`: description: 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.
### Basic Configuration
#### Eclipse Temurin
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'temurin' # See 'Supported distributions' for available options
java-version: '17'
- run: java -cp java HelloWorldApp
- run: java HelloWorldApp.java
```
**Zulu OpenJDK**
#### Azul Zulu OpenJDK
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'zulu' # See 'Supported distributions' for available options
java-version: '11'
- run: java -cp java HelloWorldApp
java-version: '17'
- run: java HelloWorldApp.java
```
#### Supported version syntax
@ -55,31 +97,39 @@ Currently, the following distributions are supported:
| Keyword | Distribution | Official site | License
|-|-|-|-|
| `temurin` | Eclipse Temurin | [Link](https://adoptium.net/) | [Link](https://adoptium.net/about.html)
| `zulu` | Zulu OpenJDK | [Link](https://www.azul.com/downloads/zulu-community/?package=jdk) | [Link](https://www.azul.com/products/zulu-and-zulu-enterprise/zulu-terms-of-use/) |
| `adopt` or `adopt-hotspot` | Adopt OpenJDK Hotspot | [Link](https://adoptopenjdk.net/) | [Link](https://adoptopenjdk.net/about.html) |
| `adopt-openj9` | Adopt OpenJDK OpenJ9 | [Link](https://adoptopenjdk.net/) | [Link](https://adoptopenjdk.net/about.html) |
| `zulu` | Azul Zulu OpenJDK | [Link](https://www.azul.com/downloads/zulu-community/?package=jdk) | [Link](https://www.azul.com/products/zulu-and-zulu-enterprise/zulu-terms-of-use/) |
| `adopt` or `adopt-hotspot` | AdoptOpenJDK Hotspot | [Link](https://adoptopenjdk.net/) | [Link](https://adoptopenjdk.net/about.html) |
| `adopt-openj9` | AdoptOpenJDK OpenJ9 | [Link](https://adoptopenjdk.net/) | [Link](https://adoptopenjdk.net/about.html) |
| `liberica` | Liberica JDK | [Link](https://bell-sw.com/) | [Link](https://bell-sw.com/liberica_eula/) |
| `microsoft` | Microsoft Build of OpenJDK | [Link](https://www.microsoft.com/openjdk) | [Link](https://docs.microsoft.com/java/openjdk/faq)
| `corretto` | Amazon Corretto Build of OpenJDK | [Link](https://aws.amazon.com/corretto/) | [Link](https://aws.amazon.com/corretto/faqs/)
| `semeru` | IBM Semeru Runtime Open Edition | [Link](https://developer.ibm.com/languages/java/semeru-runtimes/downloads/) | [Link](https://openjdk.java.net/legal/gplv2+ce.html) |
| `oracle` | Oracle JDK | [Link](https://www.oracle.com/java/technologies/downloads/) | [Link](https://java.com/freeuselicense)
**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.
**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/).
**NOTE:** 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/).
**NOTE:** For Azul Zulu OpenJDK architectures x64 and arm64 are mapped to x86 / arm with proper hw_bitness.
### Caching packages dependencies
The action has a built-in functionality for caching and restoring dependencies. It uses [actions/cache](https://github.com/actions/cache) under hood for caching dependencies but requires less configuration settings. Supported package managers are gradle and maven. 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`, `**/versions.properties`
The action has a built-in functionality for caching and restoring dependencies. It uses [actions/cache](https://github.com/actions/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 s`**/versions.properties`
- maven: `**/pom.xml`
- sbt: all sbt build definition files `**/*.sbt`, `**/project/build.properties`, `**/project/**.scala`, `**/project/**.sbt`
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 cache input is optional, and caching is turned off by default.
#### Caching gradle dependencies
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
java-version: '17'
cache: 'gradle'
- run: ./gradlew build --no-daemon
```
@ -87,33 +137,47 @@ steps:
#### Caching maven dependencies
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
java-version: '17'
cache: 'maven'
- name: Build with Maven
run: mvn -B package --file pom.xml
```
#### Caching sbt dependencies
```yaml
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '17'
cache: 'sbt'
- name: Build with SBT
run: sbt package
```
### Check latest
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.
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.
For Java distributions that are not cached on Hosted images, `check-latest` always behaves as `true` and downloads Java on-flight. Check out [Hosted Tool Cache](docs/advanced-usage.md#Hosted-Tool-Cache) for more details about pre-cached Java versions.
For Java distributions that are not cached on Hosted images, `check-latest` always behaves as `true` and downloads Java on-flight. Check out [Hosted Tool Cache](docs/advanced-usage.md#Hosted-Tool-Cache) for more details about pre-cached Java versions.
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'adopt'
java-version: '11'
distribution: 'temurin'
java-version: '17'
check-latest: true
- run: java -cp java HelloWorldApp
- run: java HelloWorldApp.java
```
### Testing against different Java versions
@ -123,24 +187,46 @@ jobs:
runs-on: ubuntu-20.04
strategy:
matrix:
java: [ '8', '11', '13', '15' ]
java: [ '8', '11', '17' ]
name: Java ${{ matrix.Java }} sample
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Setup java
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: ${{ matrix.java }}
- run: java -cp java HelloWorldApp
- run: java HelloWorldApp.java
```
### Advanced
### Install multiple JDKs
All versions are added to the PATH. The last version will be used and available globally. Other Java versions can be accessed through env variables with such specification as 'JAVA_HOME_{{ MAJOR_VERSION }}_{{ ARCHITECTURE }}'.
```yaml
steps:
- uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: |
8
11
15
```
### 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)
- [Microsoft](docs/advanced-usage.md#Microsoft)
- [Amazon Corretto](docs/advanced-usage.md#Amazon-Corretto)
- [Oracle](docs/advanced-usage.md#Oracle)
- [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)
@ -149,6 +235,7 @@ jobs:
- [Publishing using Apache Maven](docs/advanced-usage.md#Publishing-using-Apache-Maven)
- [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)
## License
@ -156,4 +243,4 @@ The scripts and documentation in this project are released under the [MIT Licens
## Contributions
Contributions are welcome! See [Contributor's Guide](CONTRIBUTING.md)
Contributions are welcome! See [Contributor's Guide](docs/contributors.md)

View File

@ -1,13 +1,14 @@
import io = require('@actions/io');
import fs = require('fs');
import path = require('path');
import * as io from '@actions/io';
import * as core from '@actions/core';
import * as fs from 'fs';
import * as path from 'path';
import os from 'os';
import * as auth from '../src/auth';
import {M2_DIR, MVN_SETTINGS_FILE} from '../src/constants';
const m2Dir = path.join(__dirname, auth.M2_DIR);
const settingsFile = path.join(m2Dir, auth.SETTINGS_FILE);
const m2Dir = path.join(__dirname, M2_DIR);
const settingsFile = path.join(m2Dir, MVN_SETTINGS_FILE);
describe('auth tests', () => {
let spyOSHomedir: jest.SpyInstance;
@ -38,10 +39,16 @@ describe('auth tests', () => {
const password = 'TOLKIEN';
const altHome = path.join(__dirname, 'runner', 'settings');
const altSettingsFile = path.join(altHome, auth.SETTINGS_FILE);
const altSettingsFile = path.join(altHome, MVN_SETTINGS_FILE);
await io.rmRF(altHome); // ensure it doesn't already exist
await auth.createAuthenticationSettings(id, username, password, altHome, true);
await auth.createAuthenticationSettings(
id,
username,
password,
altHome,
true
);
expect(fs.existsSync(m2Dir)).toBe(false);
expect(fs.existsSync(settingsFile)).toBe(false);
@ -60,11 +67,19 @@ describe('auth tests', () => {
const username = 'UNAME';
const password = 'TOKEN';
await auth.createAuthenticationSettings(id, username, password, m2Dir, true);
await auth.createAuthenticationSettings(
id,
username,
password,
m2Dir,
true
);
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
expect(fs.readFileSync(settingsFile, 'utf-8')).toEqual(auth.generate(id, username, password));
expect(fs.readFileSync(settingsFile, 'utf-8')).toEqual(
auth.generate(id, username, password)
);
}, 100000);
it('creates settings.xml with additional configuration', async () => {
@ -73,7 +88,14 @@ describe('auth tests', () => {
const password = 'TOKEN';
const gpgPassphrase = 'GPG';
await auth.createAuthenticationSettings(id, username, password, m2Dir, true, gpgPassphrase);
await auth.createAuthenticationSettings(
id,
username,
password,
m2Dir,
true,
gpgPassphrase
);
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
@ -87,16 +109,24 @@ describe('auth tests', () => {
const username = 'USERNAME';
const password = 'PASSWORD';
fs.mkdirSync(m2Dir, { recursive: true });
fs.mkdirSync(m2Dir, {recursive: true});
fs.writeFileSync(settingsFile, 'FAKE FILE');
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
await auth.createAuthenticationSettings(id, username, password, m2Dir, true);
await auth.createAuthenticationSettings(
id,
username,
password,
m2Dir,
true
);
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
expect(fs.readFileSync(settingsFile, 'utf-8')).toEqual(auth.generate(id, username, password));
expect(fs.readFileSync(settingsFile, 'utf-8')).toEqual(
auth.generate(id, username, password)
);
}, 100000);
it('does not overwrite existing settings.xml files', async () => {
@ -104,12 +134,18 @@ describe('auth tests', () => {
const username = 'USERNAME';
const password = 'PASSWORD';
fs.mkdirSync(m2Dir, { recursive: true });
fs.mkdirSync(m2Dir, {recursive: true});
fs.writeFileSync(settingsFile, 'FAKE FILE');
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
await auth.createAuthenticationSettings(id, username, password, m2Dir, false);
await auth.createAuthenticationSettings(
id,
username,
password,
m2Dir,
false
);
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(settingsFile)).toBe(true);
@ -158,6 +194,8 @@ describe('auth tests', () => {
</servers>
</settings>`;
expect(auth.generate(id, username, password, gpgPassphrase)).toEqual(expectedSettings);
expect(auth.generate(id, username, password, gpgPassphrase)).toEqual(
expectedSettings
);
});
});

View File

@ -1,7 +1,7 @@
import { mkdtempSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { restore, save } from '../src/cache';
import {mkdtempSync} from 'fs';
import {tmpdir} from 'os';
import {join} from 'path';
import {restore, save} from '../src/cache';
import * as fs from 'fs';
import * as os from 'os';
import * as core from '@actions/core';
@ -68,17 +68,21 @@ describe('dependency cache', () => {
beforeEach(() => {
spyCacheRestore = jest
.spyOn(cache, 'restoreCache')
.mockImplementation((paths: string[], primaryKey: string) => Promise.resolve(undefined));
.mockImplementation((paths: string[], primaryKey: string) =>
Promise.resolve(undefined)
);
spyWarning.mockImplementation(() => null);
});
it('throws error if unsupported package manager specified', () => {
return expect(restore('ant')).rejects.toThrowError('unknown package manager specified: ant');
return expect(restore('ant')).rejects.toThrow(
'unknown package manager specified: ant'
);
});
describe('for maven', () => {
it('throws error if no pom.xml found', async () => {
await expect(restore('maven')).rejects.toThrowError(
await expect(restore('maven')).rejects.toThrow(
`No file in ${projectRoot(
workspace
)} matched to [**/pom.xml], make sure you have checked out the target repository`
@ -88,43 +92,100 @@ describe('dependency cache', () => {
createFile(join(workspace, 'pom.xml'));
await restore('maven');
expect(spyCacheRestore).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith('maven cache is not found');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('maven cache is not found');
});
});
describe('for gradle', () => {
it('throws error if no build.gradle found', async () => {
await expect(restore('gradle')).rejects.toThrowError(
await expect(restore('gradle')).rejects.toThrow(
`No file in ${projectRoot(
workspace
)} matched to [**/*.gradle*,**/gradle-wrapper.properties,**/versions.properties], make sure you have checked out the target repository`
)} matched to [**/*.gradle*,**/gradle-wrapper.properties,buildSrc/**/Versions.kt,buildSrc/**/Dependencies.kt,gradle/*.versions.toml,**/versions.properties], make sure you have checked out the target repository`
);
});
it('downloads cache based on build.gradle', async () => {
createFile(join(workspace, 'build.gradle'));
await restore('gradle');
expect(spyCacheRestore).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith('gradle cache is not found');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
});
it('downloads cache based on build.gradle.kts', async () => {
createFile(join(workspace, 'build.gradle.kts'));
await restore('gradle');
expect(spyCacheRestore).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith('gradle cache is not found');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
});
it('downloads cache based on libs.versions.toml', async () => {
createDirectory(join(workspace, 'gradle'));
createFile(join(workspace, 'gradle', 'libs.versions.toml'));
await restore('gradle');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
});
});
it('downloads cache based on buildSrc/Versions.kt', async () => {
createDirectory(join(workspace, 'buildSrc'));
createFile(join(workspace, 'buildSrc', 'Versions.kt'));
await restore('gradle');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
});
describe('for sbt', () => {
it('throws error if no build.sbt found', async () => {
await expect(restore('sbt')).rejects.toThrow(
`No file in ${projectRoot(
workspace
)} matched to [**/*.sbt,**/project/build.properties,**/project/**.scala,**/project/**.sbt], make sure you have checked out the target repository`
);
});
it('downloads cache', async () => {
createFile(join(workspace, 'build.sbt'));
await restore('sbt');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('sbt cache is not found');
});
it('detects scala and sbt changes under **/project/ folder', async () => {
createFile(join(workspace, 'build.sbt'));
createDirectory(join(workspace, 'project'));
createFile(join(workspace, 'project/DependenciesV1.scala'));
await restore('sbt');
const firstCall = spySaveState.mock.calls.toString();
spySaveState.mockClear();
await restore('sbt');
const secondCall = spySaveState.mock.calls.toString();
// Make sure multiple restores produce the same cache
expect(firstCall).toBe(secondCall);
spySaveState.mockClear();
createFile(join(workspace, 'project/DependenciesV2.scala'));
await restore('sbt');
const thirdCall = spySaveState.mock.calls.toString();
expect(firstCall).not.toBe(thirdCall);
});
});
it('downloads cache based on versions.properties', async () => {
createFile(join(workspace, 'versions.properties'));
await restore('gradle');
expect(spyCacheRestore).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith('gradle cache is not found');
expect(spyCacheRestore).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith('gradle cache is not found');
});
});
describe('save', () => {
@ -136,36 +197,69 @@ describe('dependency cache', () => {
beforeEach(() => {
spyCacheSave = jest
.spyOn(cache, 'saveCache')
.mockImplementation((paths: string[], key: string) => Promise.resolve(0));
.mockImplementation((paths: string[], key: string) =>
Promise.resolve(0)
);
spyWarning.mockImplementation(() => null);
});
it('throws error if unsupported package manager specified', () => {
return expect(save('ant')).rejects.toThrowError('unknown package manager specified: ant');
return expect(save('ant')).rejects.toThrow(
'unknown package manager specified: ant'
);
});
it('save with -1 cacheId , should not fail workflow', async () => {
spyCacheSave.mockImplementation(() => Promise.resolve(-1));
createStateForMissingBuildFile();
await save('maven');
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Cache saved with the key:.*/)
);
});
it('saves with error from toolkit, should fail workflow', async () => {
spyCacheSave.mockImplementation(() =>
Promise.reject(new cache.ValidationError('Validation failed'))
);
createStateForMissingBuildFile();
expect.assertions(1);
await expect(save('maven')).rejects.toEqual(
new cache.ValidationError('Validation failed')
);
});
describe('for maven', () => {
it('uploads cache even if no pom.xml found', async () => {
createStateForMissingBuildFile();
await save('maven');
expect(spyCacheSave).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
});
it('does not upload cache if no restore run before', async () => {
createFile(join(workspace, 'pom.xml'));
await save('maven');
expect(spyCacheSave).not.toBeCalled();
expect(spyWarning).toBeCalledWith('Error retrieving key from state.');
expect(spyCacheSave).not.toHaveBeenCalled();
expect(spyWarning).toHaveBeenCalledWith(
'Error retrieving key from state.'
);
});
it('uploads cache', async () => {
createFile(join(workspace, 'pom.xml'));
createStateForSuccessfulRestore();
await save('maven');
expect(spyCacheSave).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith(expect.stringMatching(/^Cache saved with the key:.*/));
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Cache saved with the key:.*/)
);
});
});
describe('for gradle', () => {
@ -173,90 +267,143 @@ describe('dependency cache', () => {
createStateForMissingBuildFile();
await save('gradle');
expect(spyCacheSave).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
});
it('does not upload cache if no restore run before', async () => {
createFile(join(workspace, 'build.gradle'));
await save('gradle');
expect(spyCacheSave).not.toBeCalled();
expect(spyWarning).toBeCalledWith('Error retrieving key from state.');
expect(spyCacheSave).not.toHaveBeenCalled();
expect(spyWarning).toHaveBeenCalledWith(
'Error retrieving key from state.'
);
});
it('uploads cache based on build.gradle', async () => {
createFile(join(workspace, 'build.gradle'));
createStateForSuccessfulRestore();
await save('gradle');
expect(spyCacheSave).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith(expect.stringMatching(/^Cache saved with the key:.*/));
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Cache saved with the key:.*/)
);
});
it('uploads cache based on build.gradle.kts', async () => {
createFile(join(workspace, 'build.gradle.kts'));
createStateForSuccessfulRestore();
await save('gradle');
expect(spyCacheSave).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith(expect.stringMatching(/^Cache saved with the key:.*/));
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Cache saved with the key:.*/)
);
});
it('uploads cache based on buildSrc/Versions.kt', async () => {
createDirectory(join(workspace, 'buildSrc'));
createFile(join(workspace, 'buildSrc', 'Versions.kt'));
createStateForSuccessfulRestore();
await save('gradle');
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Cache saved with the key:.*/)
);
});
});
describe('for sbt', () => {
it('uploads cache even if no build.sbt found', async () => {
createStateForMissingBuildFile();
await save('sbt');
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
});
it('does not upload cache if no restore run before', async () => {
createFile(join(workspace, 'build.sbt'));
await save('sbt');
expect(spyCacheSave).not.toHaveBeenCalled();
expect(spyWarning).toHaveBeenCalledWith(
'Error retrieving key from state.'
);
});
it('uploads cache', async () => {
createFile(join(workspace, 'build.sbt'));
createStateForSuccessfulRestore();
await save('sbt');
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Cache saved with the key:.*/)
);
});
it('uploads cache based on versions.properties', async () => {
createFile(join(workspace, 'versions.properties'));
createStateForSuccessfulRestore();
await save('gradle');
expect(spyCacheSave).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith(expect.stringMatching(/^Cache saved with the key:.*/));
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
expect(spyInfo).toHaveBeenCalledWith(
expect.stringMatching(/^Cache saved with the key:.*/)
);
});
});
});
function resetState() {
jest.spyOn(core, 'getState').mockReset();
}
/**
* Create states to emulate a restore process without build file.
*/
function createStateForMissingBuildFile() {
jest.spyOn(core, 'getState').mockImplementation(name => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-';
default:
return '';
}
});
}
/**
* Create states to emulate a successful restore process.
*/
function createStateForSuccessfulRestore() {
jest.spyOn(core, 'getState').mockImplementation(name => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-primary-key';
case 'cache-matched-key':
return 'setup-java-cache-matched-key';
default:
return '';
}
});
}
function createFile(path: string) {
core.info(`created a file at ${path}`);
fs.writeFileSync(path, '');
}
function projectRoot(workspace: string): string {
if (os.platform() === 'darwin') {
return `/private${workspace}`;
} else {
return workspace;
}
}
});
function resetState() {
jest.spyOn(core, 'getState').mockReset();
}
/**
* Create states to emulate a restore process without build file.
*/
function createStateForMissingBuildFile() {
jest.spyOn(core, 'getState').mockImplementation(name => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-';
default:
return '';
}
});
}
/**
* Create states to emulate a successful restore process.
*/
function createStateForSuccessfulRestore() {
jest.spyOn(core, 'getState').mockImplementation(name => {
switch (name) {
case 'cache-primary-key':
return 'setup-java-cache-primary-key';
case 'cache-matched-key':
return 'setup-java-cache-matched-key';
default:
return '';
}
});
}
function createFile(path: string) {
core.info(`created a file at ${path}`);
fs.writeFileSync(path, '');
}
function createDirectory(path: string) {
core.info(`created a directory at ${path}`);
fs.mkdirSync(path);
}
function projectRoot(workspace: string): string {
if (os.platform() === 'darwin') {
return `/private${workspace}`;
} else {
return workspace;
}
}

1
__tests__/cache/sbt/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
target/

3
__tests__/cache/sbt/build.sbt vendored Normal file
View File

@ -0,0 +1,3 @@
ThisBuild / scalaVersion := "2.12.15"
libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.1.2"

View File

@ -0,0 +1 @@
sbt.version=1.6.2

View File

@ -1,4 +1,4 @@
import { run as cleanup } from '../src/cleanup-java';
import {run as cleanup} from '../src/cleanup-java';
import * as core from '@actions/core';
import * as cache from '@actions/cache';
import * as util from '../src/util';
@ -26,7 +26,7 @@ describe('cleanup', () => {
resetState();
});
it('does not fail nor warn even when the save provess throws a ReserveCacheError', async () => {
it('does not fail nor warn even when the save process throws a ReserveCacheError', async () => {
spyCacheSave.mockImplementation((paths: string[], key: string) =>
Promise.reject(
new cache.ReserveCacheError(
@ -38,8 +38,8 @@ describe('cleanup', () => {
return name === 'cache' ? 'gradle' : '';
});
await cleanup();
expect(spyCacheSave).toBeCalled();
expect(spyWarning).not.toBeCalled();
expect(spyCacheSave).toHaveBeenCalled();
expect(spyWarning).not.toHaveBeenCalled();
});
it('does not fail even though the save process throws error', async () => {
@ -50,7 +50,7 @@ describe('cleanup', () => {
return name === 'cache' ? 'gradle' : '';
});
await cleanup();
expect(spyCacheSave).toBeCalled();
expect(spyCacheSave).toHaveBeenCalled();
});
});

1183
__tests__/data/corretto.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,218 @@
[
{
"version": "17.0.7",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.7-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.7-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.7-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.7-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.7-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-linux-aarch64.tar.gz"
}
]
},
{
"version": "17.0.1+12.1",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.1.12.1-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-linux-aarch64.tar.gz"
}
]
},
{
"version": "16.0.2+7.1",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-16.0.2.7.1-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-windows-x64.zip"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.19",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.19-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.19-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.19-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.19-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.19-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.15",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.15-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.15-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.15-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.15-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.15-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.13+8.1",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.13.8.1-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.13.8.1-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.13.8.1-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.13.8.1-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-linux-aarch64.tar.gz"
}
]
}
]

2168
__tests__/data/semeru.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,14 @@
import { HttpClient } from '@actions/http-client';
import {HttpClient} from '@actions/http-client';
import {IAdoptAvailableVersions} from '../../src/distributions/adopt/models';
import {
AdoptDistribution,
AdoptImplementation
} from '../../src/distributions/adopt/installer';
import {JavaInstallerOptions} from '../../src/distributions/base-models';
import { AdoptDistribution, AdoptImplementation } from '../../src/distributions/adopt/installer';
import { JavaInstallerOptions } from '../../src/distributions/base-models';
import os from 'os';
let manifestData = require('../data/adopt.json') as [];
import manifestData from '../data/adopt.json';
describe('getAvailableVersions', () => {
let spyHttpClient: jest.SpyInstance;
@ -25,42 +30,82 @@ describe('getAvailableVersions', () => {
it.each([
[
{ version: '11', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
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 },
{
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 },
{
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 },
{
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 },
{
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 },
{
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 },
{
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 },
{
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'
]
@ -72,7 +117,8 @@ describe('getAvailableVersions', () => {
expectedParameters
) => {
const distribution = new AdoptDistribution(installerOptions, impl);
const baseUrl = 'https://api.adoptopenjdk.net/v3/assets/version/%5B1.0,100.0%5D';
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';
@ -89,12 +135,12 @@ describe('getAvailableVersions', () => {
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: manifestData
result: manifestData as any
})
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: manifestData
result: manifestData as any
})
.mockReturnValueOnce({
statusCode: 200,
@ -103,7 +149,12 @@ describe('getAvailableVersions', () => {
});
const distribution = new AdoptDistribution(
{ version: '11', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
const availableVersions = await distribution['getAvailableVersions']();
@ -120,7 +171,12 @@ describe('getAvailableVersions', () => {
'find right toolchain folder',
(impl: AdoptImplementation, packageType: string, expected: string) => {
const distribution = new AdoptDistribution(
{ version: '11', architecture: 'x64', packageType: packageType, checkLatest: false },
{
version: '11',
architecture: 'x64',
packageType: packageType,
checkLatest: false
},
impl
);
@ -128,6 +184,39 @@ describe('getAvailableVersions', () => {
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);
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', () => {
@ -145,43 +234,63 @@ describe('findPackageForDownload', () => {
['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 },
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => manifestData;
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 },
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => manifestData;
await expect(distribution['findPackageForDownload']('9.0.8')).rejects.toThrowError(
/Could not find satisfied version for SemVer */
);
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(
distribution['findPackageForDownload']('9.0.8')
).rejects.toThrow(/Could not find satisfied version for SemVer */);
});
it('version is not found', async () => {
const distribution = new AdoptDistribution(
{ version: '11', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => manifestData;
await expect(distribution['findPackageForDownload']('7.x')).rejects.toThrowError(
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(distribution['findPackageForDownload']('7.x')).rejects.toThrow(
/Could not find satisfied version for SemVer */
);
});
it('version list is empty', async () => {
const distribution = new AdoptDistribution(
{ version: '11', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
AdoptImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => [];
await expect(distribution['findPackageForDownload']('11')).rejects.toThrowError(
await expect(distribution['findPackageForDownload']('11')).rejects.toThrow(
/Could not find satisfied version for SemVer */
);
});

View File

@ -5,26 +5,37 @@ import * as util from '../../src/util';
import path from 'path';
import * as semver from 'semver';
import { JavaBase } from '../../src/distributions/base-installer';
import {JavaBase} from '../../src/distributions/base-installer';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../../src/distributions/base-models';
import os from 'os';
class EmptyJavaBase extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('Empty', installerOptions);
}
protected async downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults> {
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
return {
version: '11.0.9',
path: path.join('toolcache', this.toolcacheFolderName, '11.0.9', this.architecture)
path: path.join(
'toolcache',
this.toolcacheFolderName,
'11.0.9',
this.architecture
)
};
}
protected async findPackageForDownload(range: string): Promise<JavaDownloadRelease> {
protected async findPackageForDownload(
range: string
): Promise<JavaDownloadRelease> {
const availableVersion = '11.0.9';
if (!semver.satisfies(availableVersion, range)) {
throw new Error('Available version not found');
@ -58,44 +69,111 @@ describe('findInToolcache', () => {
it.each([
[
{ version: '11', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{ version: actualJavaVersion, path: javaPath }
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
{version: actualJavaVersion, path: javaPath}
],
[
{ version: '11.0', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{ version: actualJavaVersion, path: javaPath }
{
version: '11.0',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
{version: actualJavaVersion, path: javaPath}
],
[
{ version: '11.0.8', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{ version: actualJavaVersion, path: javaPath }
{
version: '11.0.8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
{version: actualJavaVersion, path: javaPath}
],
[
{ version: '11', architecture: 'x64', packageType: 'jdk', checkLatest: true },
{ version: actualJavaVersion, path: javaPath }
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: true
},
{version: actualJavaVersion, path: javaPath}
],
[
{ version: '11.0', architecture: 'x64', packageType: 'jdk', checkLatest: true },
{ version: actualJavaVersion, path: javaPath }
{
version: '11.0',
architecture: 'x64',
packageType: 'jdk',
checkLatest: true
},
{version: actualJavaVersion, path: javaPath}
],
[
{ version: '11.0.8', architecture: 'x64', packageType: 'jdk', checkLatest: true },
{ version: actualJavaVersion, path: javaPath }
{
version: '11.0.8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: true
},
{version: actualJavaVersion, path: javaPath}
],
[{ version: '11', architecture: 'x64', packageType: 'jre', checkLatest: false }, null],
[{ version: '8', architecture: 'x64', packageType: 'jdk', checkLatest: false }, null],
[{ version: '11', architecture: 'x86', packageType: 'jdk', checkLatest: false }, null],
[{ version: '11', architecture: 'x86', packageType: 'jre', checkLatest: false }, null]
[
{
version: '11',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
null
],
[
{
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
null
],
[
{
version: '11',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
null
],
[
{
version: '11',
architecture: 'x86',
packageType: 'jre',
checkLatest: false
},
null
]
])(`should find java for path %s -> %s`, (input, expected) => {
spyTcFindAllVersions.mockReturnValue([actualJavaVersion]);
spyGetToolcachePath.mockImplementation(
(toolname: string, javaVersion: string, architecture: string) => {
const semverVersion = new semver.Range(javaVersion);
if (path.basename(javaPath) !== architecture || !javaPath.includes(toolname)) {
if (
path.basename(javaPath) !== architecture ||
!javaPath.includes(toolname)
) {
return '';
}
return semver.satisfies(actualJavaVersion, semverVersion) ? javaPath : '';
return semver.satisfies(actualJavaVersion, semverVersion)
? javaPath
: '';
}
);
mockJavaBase = new EmptyJavaBase(input);
@ -103,52 +181,63 @@ describe('findInToolcache', () => {
});
it.each([
['11', { version: '11.0.3+2', versionInPath: '11.0.3-2' }],
['11.0', { version: '11.0.3+2', versionInPath: '11.0.3-2' }],
['11.0.1', { version: '11.0.1', versionInPath: '11.0.1' }],
['11.0.3', { version: '11.0.3+2', versionInPath: '11.0.3-2' }],
['15', { version: '15.0.2+4', versionInPath: '15.0.2-4' }],
['x', { version: '15.0.2+4', versionInPath: '15.0.2-4' }],
['x-ea', { version: '17.4.4', versionInPath: '17.4.4-ea' }],
['11-ea', { version: '11.3.3+5.2.1231421', versionInPath: '11.3.3-ea.5.2.1231421' }],
['11.2-ea', { version: '11.2.1', versionInPath: '11.2.1-ea' }],
['11.2.1-ea', { version: '11.2.1', versionInPath: '11.2.1-ea' }]
])('should choose correct java from tool-cache for input %s', (input, expected) => {
spyTcFindAllVersions.mockReturnValue([
'17.4.4-ea',
'11.0.2',
'15.0.2-4',
'11.0.3-2',
'11.2.1-ea',
'11.3.2-ea',
'11.3.2-ea.5',
'11.3.3-ea.5.2.1231421',
'12.3.2-0',
'11.0.1'
]);
spyGetToolcachePath.mockImplementation(
(toolname: string, javaVersion: string, architecture: string) =>
`/hostedtoolcache/${toolname}/${javaVersion}/${architecture}`
);
mockJavaBase = new EmptyJavaBase({
version: input,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
const foundVersion = mockJavaBase['findInToolcache']();
expect(foundVersion).toEqual({
version: expected.version,
path: `/hostedtoolcache/Java_Empty_jdk/${expected.versionInPath}/x64`
});
});
['11', {version: '11.0.3+2', versionInPath: '11.0.3-2'}],
['11.0', {version: '11.0.3+2', versionInPath: '11.0.3-2'}],
['11.0.1', {version: '11.0.1', versionInPath: '11.0.1'}],
['11.0.3', {version: '11.0.3+2', versionInPath: '11.0.3-2'}],
['15', {version: '15.0.2+4', versionInPath: '15.0.2-4'}],
['x', {version: '15.0.2+4', versionInPath: '15.0.2-4'}],
['x-ea', {version: '17.4.4', versionInPath: '17.4.4-ea'}],
[
'11-ea',
{version: '11.3.3+5.2.1231421', versionInPath: '11.3.3-ea.5.2.1231421'}
],
['11.2-ea', {version: '11.2.1', versionInPath: '11.2.1-ea'}],
['11.2.1-ea', {version: '11.2.1', versionInPath: '11.2.1-ea'}]
])(
'should choose correct java from tool-cache for input %s',
(input, expected) => {
spyTcFindAllVersions.mockReturnValue([
'17.4.4-ea',
'11.0.2',
'15.0.2-4',
'11.0.3-2',
'11.2.1-ea',
'11.3.2-ea',
'11.3.2-ea.5',
'11.3.3-ea.5.2.1231421',
'12.3.2-0',
'11.0.1'
]);
spyGetToolcachePath.mockImplementation(
(toolname: string, javaVersion: string, architecture: string) =>
`/hostedtoolcache/${toolname}/${javaVersion}/${architecture}`
);
mockJavaBase = new EmptyJavaBase({
version: input,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
const foundVersion = mockJavaBase['findInToolcache']();
expect(foundVersion).toEqual({
version: expected.version,
path: `/hostedtoolcache/Java_Empty_jdk/${expected.versionInPath}/x64`
});
}
);
});
describe('setupJava', () => {
const actualJavaVersion = '11.0.9';
const installedJavaVersion = '11.0.8';
const javaPath = path.join('Java_Empty_jdk', installedJavaVersion, 'x86');
const javaPathInstalled = path.join('toolcache', 'Java_Empty_jdk', actualJavaVersion, 'x86');
const javaPathInstalled = path.join(
'toolcache',
'Java_Empty_jdk',
actualJavaVersion,
'x86'
);
let mockJavaBase: EmptyJavaBase;
@ -166,11 +255,16 @@ describe('setupJava', () => {
(toolname: string, javaVersion: string, architecture: string) => {
const semverVersion = new semver.Range(javaVersion);
if (path.basename(javaPath) !== architecture || !javaPath.includes(toolname)) {
if (
path.basename(javaPath) !== architecture ||
!javaPath.includes(toolname)
) {
return '';
}
return semver.satisfies(installedJavaVersion, semverVersion) ? javaPath : '';
return semver.satisfies(installedJavaVersion, semverVersion)
? javaPath
: '';
}
);
@ -192,6 +286,8 @@ describe('setupJava', () => {
spyCoreSetOutput = jest.spyOn(core, 'setOutput');
spyCoreSetOutput.mockImplementation(() => undefined);
jest.spyOn(os, 'arch').mockReturnValue('x86');
});
afterEach(() => {
@ -202,23 +298,46 @@ describe('setupJava', () => {
it.each([
[
{ version: '11', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{ version: installedJavaVersion, path: javaPath }
{
version: '11',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
{version: installedJavaVersion, path: javaPath}
],
[
{ version: '11.0', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{ version: installedJavaVersion, path: javaPath }
{
version: '11.0',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
{version: installedJavaVersion, path: javaPath}
],
[
{ version: '11.0.8', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{ version: installedJavaVersion, path: javaPath }
{
version: '11.0.8',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
{version: installedJavaVersion, path: javaPath}
],
[
{version: '11', architecture: '', packageType: 'jdk', checkLatest: false},
{version: installedJavaVersion, path: javaPath}
]
])('should find java locally for %s', (input, expected) => {
])('should find java locally for %s', async (input, expected) => {
mockJavaBase = new EmptyJavaBase(input);
expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyGetToolcachePath).toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith(`Resolved Java ${expected.version} from tool-cache`);
expect(spyCoreInfo).toHaveBeenCalledWith(`Setting Java ${expected.version} as the default`);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved Java ${expected.version} from tool-cache`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Setting Java ${expected.version} as the default`
);
expect(spyCoreInfo).not.toHaveBeenCalledWith(
'Trying to resolve the latest version from remote'
);
@ -227,16 +346,47 @@ describe('setupJava', () => {
it.each([
[
{ version: '11', architecture: 'x86', packageType: 'jre', checkLatest: false },
{ path: path.join('toolcache', 'Java_Empty_jre', '11.0.9', 'x86'), version: '11.0.9' }
{
version: '11',
architecture: 'x86',
packageType: 'jre',
checkLatest: false
},
{
path: path.join('toolcache', 'Java_Empty_jre', '11.0.9', 'x86'),
version: '11.0.9'
}
],
[
{ version: '11', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{ path: path.join('toolcache', 'Java_Empty_jdk', '11.0.9', 'x64'), version: '11.0.9' }
{
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
{
path: path.join('toolcache', 'Java_Empty_jdk', '11.0.9', 'x64'),
version: '11.0.9'
}
],
[
{ version: '11', architecture: 'x64', packageType: 'jre', checkLatest: false },
{ path: path.join('toolcache', 'Java_Empty_jre', '11.0.9', 'x64'), version: '11.0.9' }
{
version: '11',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
{
path: path.join('toolcache', 'Java_Empty_jre', '11.0.9', 'x64'),
version: '11.0.9'
}
],
[
{version: '11', architecture: '', packageType: 'jre', checkLatest: false},
{
path: path.join('toolcache', 'Java_Empty_jre', '11.0.9', 'x86'),
version: '11.0.9'
}
]
])('download java with configuration %s', async (input, expected) => {
mockJavaBase = new EmptyJavaBase(input);
@ -244,82 +394,177 @@ describe('setupJava', () => {
expect(spyGetToolcachePath).toHaveBeenCalled();
expect(spyCoreAddPath).toHaveBeenCalled();
expect(spyCoreExportVariable).toHaveBeenCalled();
expect(spyCoreExportVariable).toHaveBeenCalledWith(
`JAVA_HOME_${input.version}_${(
input.architecture || 'x86'
).toLocaleUpperCase()}`,
expected.path
);
expect(spyCoreSetOutput).toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith('Trying to resolve the latest version from remote');
expect(spyCoreInfo).toHaveBeenCalledWith(`Resolved latest version as ${expected.version}`);
expect(spyCoreInfo).toHaveBeenCalledWith(
'Trying to resolve the latest version from remote'
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved latest version as ${expected.version}`
);
expect(spyCoreInfo).toHaveBeenCalledWith('Trying to download...');
expect(spyCoreInfo).toHaveBeenCalledWith(`Java ${expected.version} was downloaded`);
expect(spyCoreInfo).toHaveBeenCalledWith(`Setting Java ${expected.version} as the default`);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Java ${expected.version} was downloaded`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Setting Java ${expected.version} as the default`
);
});
it.each([
[
{ version: '11.0.9', architecture: 'x86', packageType: 'jdk', checkLatest: true },
{ version: '11.0.9', path: javaPathInstalled }
]
])('should check the latest java version for %s and resolve locally', async (input, expected) => {
mockJavaBase = new EmptyJavaBase(input);
mockJavaBase['findInToolcache'] = () => ({ version: '11.0.9', path: expected.path });
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyCoreInfo).toHaveBeenCalledWith('Trying to resolve the latest version from remote');
expect(spyCoreInfo).toHaveBeenCalledWith(`Resolved latest version as ${expected.version}`);
expect(spyCoreInfo).toHaveBeenCalledWith(`Resolved Java ${expected.version} from tool-cache`);
expect(spyCoreInfo).toHaveBeenCalledWith(`Setting Java ${expected.version} as the default`);
});
it.each([
[
{ version: '11', architecture: 'x86', packageType: 'jdk', checkLatest: true },
{ version: actualJavaVersion, path: javaPathInstalled }
{
version: '11.0.9',
architecture: 'x86',
packageType: 'jdk',
checkLatest: true
},
{version: '11.0.9', path: javaPathInstalled}
],
[
{ version: '11.0', architecture: 'x86', packageType: 'jdk', checkLatest: true },
{ version: actualJavaVersion, path: javaPathInstalled }
],
[
{ version: '11.0.x', architecture: 'x86', packageType: 'jdk', checkLatest: true },
{ version: actualJavaVersion, path: javaPathInstalled }
{
version: '11.0.9',
architecture: '',
packageType: 'jdk',
checkLatest: true
},
{version: '11.0.9', path: javaPathInstalled}
]
])('should check the latest java version for %s and download', async (input, expected) => {
mockJavaBase = new EmptyJavaBase(input);
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyGetToolcachePath).toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith('Trying to resolve the latest version from remote');
expect(spyCoreInfo).toHaveBeenCalledWith(`Resolved latest version as ${actualJavaVersion}`);
expect(spyCoreInfo).toHaveBeenCalledWith('Trying to download...');
expect(spyCoreInfo).toHaveBeenCalledWith(`Java ${actualJavaVersion} was downloaded`);
expect(spyCoreInfo).toHaveBeenCalledWith(`Setting Java ${expected.version} as the default`);
});
])(
'should check the latest java version for %s and resolve locally',
async (input, expected) => {
mockJavaBase = new EmptyJavaBase(input);
mockJavaBase['findInToolcache'] = () => ({
version: '11.0.9',
path: expected.path
});
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyCoreInfo).toHaveBeenCalledWith(
'Trying to resolve the latest version from remote'
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved latest version as ${expected.version}`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved Java ${expected.version} from tool-cache`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Setting Java ${expected.version} as the default`
);
}
);
it.each([
[{ version: '15', architecture: 'x86', packageType: 'jre', checkLatest: false }],
[{ version: '11.0.7', architecture: 'x64', packageType: 'jre', checkLatest: false }]
])('should throw an error for Available version not found for %s', async input => {
mockJavaBase = new EmptyJavaBase(input);
await expect(mockJavaBase.setupJava()).rejects.toThrowError('Available version not found');
expect(spyTcFindAllVersions).toHaveBeenCalled();
expect(spyCoreAddPath).not.toHaveBeenCalled();
expect(spyCoreExportVariable).not.toHaveBeenCalled();
expect(spyCoreSetOutput).not.toHaveBeenCalled();
});
[
{
version: '11',
architecture: 'x86',
packageType: 'jdk',
checkLatest: true
},
{version: actualJavaVersion, path: javaPathInstalled}
],
[
{
version: '11.0',
architecture: 'x86',
packageType: 'jdk',
checkLatest: true
},
{version: actualJavaVersion, path: javaPathInstalled}
],
[
{
version: '11.0.x',
architecture: 'x86',
packageType: 'jdk',
checkLatest: true
},
{version: actualJavaVersion, path: javaPathInstalled}
],
[
{version: '11', architecture: '', packageType: 'jdk', checkLatest: true},
{version: actualJavaVersion, path: javaPathInstalled}
]
])(
'should check the latest java version for %s and download',
async (input, expected) => {
mockJavaBase = new EmptyJavaBase(input);
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyGetToolcachePath).toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith(
'Trying to resolve the latest version from remote'
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved latest version as ${actualJavaVersion}`
);
expect(spyCoreInfo).toHaveBeenCalledWith('Trying to download...');
expect(spyCoreInfo).toHaveBeenCalledWith(
`Java ${actualJavaVersion} was downloaded`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Setting Java ${expected.version} as the default`
);
}
);
it.each([
[
{
version: '15',
architecture: 'x86',
packageType: 'jre',
checkLatest: false
}
],
[
{
version: '11.0.7',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
}
]
])(
'should throw an error for Available version not found for %s',
async input => {
mockJavaBase = new EmptyJavaBase(input);
await expect(mockJavaBase.setupJava()).rejects.toThrow(
'Available version not found'
);
expect(spyTcFindAllVersions).toHaveBeenCalled();
expect(spyCoreAddPath).not.toHaveBeenCalled();
expect(spyCoreExportVariable).not.toHaveBeenCalled();
expect(spyCoreSetOutput).not.toHaveBeenCalled();
}
);
});
describe('normalizeVersion', () => {
const DummyJavaBase = JavaBase as any;
it.each([
['11', { version: '11', stable: true }],
['11.0', { version: '11.0', stable: true }],
['11.0.10', { version: '11.0.10', stable: true }],
['11-ea', { version: '11', stable: false }],
['11.0.2-ea', { version: '11.0.2', stable: false }]
['11', {version: '11', stable: true}],
['11.0', {version: '11.0', stable: true}],
['11.0.10', {version: '11.0.10', stable: true}],
['11-ea', {version: '11', stable: false}],
['11.0.2-ea', {version: '11.0.2', stable: false}]
])('normalizeVersion from %s to %s', (input, expected) => {
expect(DummyJavaBase.prototype.normalizeVersion.call(null, input)).toEqual(expected);
expect(DummyJavaBase.prototype.normalizeVersion.call(null, input)).toEqual(
expected
);
});
it('normalizeVersion should throw an error for non semver', () => {
const version = '11g';
expect(DummyJavaBase.prototype.normalizeVersion.bind(null, version)).toThrowError(
expect(
DummyJavaBase.prototype.normalizeVersion.bind(null, version)
).toThrow(
`The string '${version}' is not valid SemVer notation for a Java version. Please check README file for code snippets and more detailed information`
);
});
@ -329,14 +574,14 @@ describe('getToolcacheVersionName', () => {
const DummyJavaBase = JavaBase as any;
it.each([
[{ version: '11', stable: true }, '11'],
[{ version: '11.0.2', stable: true }, '11.0.2'],
[{ version: '11.0.2+4', stable: true }, '11.0.2-4'],
[{ version: '11.0.2+4.1.2563234', stable: true }, '11.0.2-4.1.2563234'],
[{ version: '11.0', stable: false }, '11.0-ea'],
[{ version: '11.0.3', stable: false }, '11.0.3-ea'],
[{ version: '11.0.3+4', stable: false }, '11.0.3-ea.4'],
[{ version: '11.0.3+4.2.256', stable: false }, '11.0.3-ea.4.2.256']
[{version: '11', stable: true}, '11'],
[{version: '11.0.2', stable: true}, '11.0.2'],
[{version: '11.0.2+4', stable: true}, '11.0.2-4'],
[{version: '11.0.2+4.1.2563234', stable: true}, '11.0.2-4.1.2563234'],
[{version: '11.0', stable: false}, '11.0-ea'],
[{version: '11.0.3', stable: false}, '11.0.3-ea'],
[{version: '11.0.3+4', stable: false}, '11.0.3-ea.4'],
[{version: '11.0.3+4.2.256', stable: false}, '11.0.3-ea.4.2.256']
])('returns correct version name for %s', (input, expected) => {
const inputVersion = input.stable ? '11' : '11-ea';
const mockJavaBase = new EmptyJavaBase({

View File

@ -0,0 +1,243 @@
import {HttpClient} from '@actions/http-client';
import {JavaInstallerOptions} from '../../src/distributions/base-models';
import {CorrettoDistribution} from '../../src/distributions/corretto/installer';
import * as util from '../../src/util';
import os from 'os';
import {isGeneratorFunction} from 'util/types';
import manifestData from '../data/corretto.json';
describe('getAvailableVersions', () => {
let spyHttpClient: jest.SpyInstance;
let spyGetDownloadArchiveExtension: jest.SpyInstance;
beforeEach(() => {
spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
spyHttpClient.mockReturnValue({
statusCode: 200,
headers: {},
result: manifestData
});
spyGetDownloadArchiveExtension = jest.spyOn(
util,
'getDownloadArchiveExtension'
);
});
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
jest.restoreAllMocks();
});
describe('getAvailableVersions', () => {
it('load available versions', async () => {
const distribution = new CorrettoDistribution({
version: '11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, 'linux');
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions).not.toBeNull();
expect(availableVersions.length).toBe(6);
});
it.each([
[
{
version: '16',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'macos',
6
],
[
{
version: '16',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
'macos',
0
],
[
{
version: '16',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
'macos',
0
],
[
{
version: '16',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'linux',
6
],
[
{
version: '18',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'windows',
6
],
[
{
version: '18',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
'windows',
1
]
])(
'fetch expected amount of available versions for %s',
async (
installerOptions: JavaInstallerOptions,
platform: string,
expectedAmountOfAvailableVersions
) => {
const distribution = new CorrettoDistribution(installerOptions);
mockPlatform(distribution, platform);
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions).not.toBeNull();
expect(availableVersions.length).toBe(
expectedAmountOfAvailableVersions
);
}
);
});
describe('findPackageForDownload', () => {
it.each([
[
'macos',
'https://corretto.aws/downloads/resources/18.0.0.37.1/amazon-corretto-18.0.0.37.1-macosx-x64.tar.gz'
],
[
'windows',
'https://corretto.aws/downloads/resources/18.0.0.37.1/amazon-corretto-18.0.0.37.1-windows-x64-jdk.zip'
],
[
'linux',
'https://corretto.aws/downloads/resources/18.0.0.37.1/amazon-corretto-18.0.0.37.1-linux-x64.tar.gz'
]
])('for os: %s', async (platform: string, expectedLink: string) => {
const version = '18';
const distribution = new CorrettoDistribution({
version,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, platform);
const availableVersion = await distribution['findPackageForDownload'](
version
);
expect(availableVersion).not.toBeNull();
expect(availableVersion.url).toBe(expectedLink);
});
it('with unstable version expect to throw not supported error', async () => {
const version = '18.0.1-ea';
const distribution = new CorrettoDistribution({
version,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, 'linux');
await expect(
distribution['findPackageForDownload'](version)
).rejects.toThrow('Early access versions are not supported');
});
it('with non major version expect to throw not supported error', async () => {
const version = '18.0.1';
const distribution = new CorrettoDistribution({
version,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, 'linux');
await expect(
distribution['findPackageForDownload'](version)
).rejects.toThrow('Only major versions are supported');
});
it('with unfound version throw could not find error', async () => {
const version = '4';
const distribution = new CorrettoDistribution({
version,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
mockPlatform(distribution, 'linux');
await expect(
distribution['findPackageForDownload'](version)
).rejects.toThrow("Could not find satisfied version for SemVer '4'");
});
it.each([
['arm64', 'aarch64'],
['amd64', 'x64']
])(
'defaults to os.arch(): %s mapped to distro arch: %s',
async (osArch: string, distroArch: string) => {
jest.spyOn(os, 'arch').mockReturnValue(osArch);
const version = '17';
const installerOptions: JavaInstallerOptions = {
version,
architecture: '', // to get default value
packageType: 'jdk',
checkLatest: false
};
const distribution = new CorrettoDistribution(installerOptions);
mockPlatform(distribution, 'macos');
const expectedLink = `https://corretto.aws/downloads/resources/17.0.2.8.1/amazon-corretto-17.0.2.8.1-macosx-${distroArch}.tar.gz`;
const availableVersion = await distribution['findPackageForDownload'](
version
);
expect(availableVersion).not.toBeNull();
expect(availableVersion.url).toBe(expectedLink);
}
);
});
const mockPlatform = (
distribution: CorrettoDistribution,
platform: string
) => {
distribution['getPlatformOption'] = () => platform;
const mockedExtension = platform === 'windows' ? 'zip' : 'tar.gz';
spyGetDownloadArchiveExtension.mockReturnValue(mockedExtension);
};
});

View File

@ -1,8 +1,12 @@
import { LibericaDistributions } from '../../src/distributions/liberica/installer';
import { ArchitectureOptions, LibericaVersion } from '../../src/distributions/liberica/models';
import { HttpClient } from '@actions/http-client';
import {LibericaDistributions} from '../../src/distributions/liberica/installer';
import {
ArchitectureOptions,
LibericaVersion
} from '../../src/distributions/liberica/models';
import {HttpClient} from '@actions/http-client';
import os from 'os';
const manifestData = require('../data/liberica.json') as LibericaVersion[];
import manifestData from '../data/liberica.json';
describe('getAvailableVersions', () => {
let spyHttpClient: jest.SpyInstance;
@ -12,7 +16,7 @@ describe('getAvailableVersions', () => {
spyHttpClient.mockReturnValue({
statusCode: 200,
headers: {},
result: manifestData
result: manifestData as LibericaVersion[]
});
});
@ -24,27 +28,57 @@ describe('getAvailableVersions', () => {
it.each([
[
{ version: '11.x', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{
version: '11.x',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
'bundle-type=jdk&bitness=32&arch=x86&build-type=all'
],
[
{ version: '11-ea', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{
version: '11-ea',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
'bundle-type=jdk&bitness=32&arch=x86&build-type=ea'
],
[
{ version: '16.0.2', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '16.0.2',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'bundle-type=jdk&bitness=64&arch=x86&build-type=all'
],
[
{ version: '16.0.2', architecture: 'x64', packageType: 'jre', checkLatest: false },
{
version: '16.0.2',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
'bundle-type=jre&bitness=64&arch=x86&build-type=all'
],
[
{ version: '8', architecture: 'armv7', packageType: 'jdk+fx', checkLatest: false },
{
version: '8',
architecture: 'armv7',
packageType: 'jdk+fx',
checkLatest: false
},
'bundle-type=jdk-full&bitness=32&arch=arm&build-type=all'
],
[
{ version: '8', architecture: 'aarch64', packageType: 'jre+fx', checkLatest: false },
{
version: '8',
architecture: 'aarch64',
packageType: 'jre+fx',
checkLatest: false
},
'bundle-type=jre-full&bitness=64&arch=arm&build-type=all'
]
])('build correct url for %s -> %s', async (input, urlParams) => {
@ -61,6 +95,39 @@ describe('getAvailableVersions', () => {
expect(spyHttpClient.mock.calls[0][0]).toBe(buildUrl);
});
type DistroArch = {
bitness: string;
arch: string;
};
it.each([
['amd64', {bitness: '64', arch: 'x86'}],
['arm64', {bitness: '64', arch: 'arm'}]
])(
'defaults to os.arch(): %s mapped to distro arch: %s',
async (osArch: string, distroArch: DistroArch) => {
jest.spyOn(os, 'arch').mockReturnValue(osArch);
const distribution = new LibericaDistributions({
version: '17',
architecture: '', // to get default value
packageType: 'jdk',
checkLatest: false
});
const additionalParams =
'&installation-type=archive&fields=downloadUrl%2Cversion%2CfeatureVersion%2CinterimVersion%2C' +
'updateVersion%2CbuildVersion';
distribution['getPlatformOption'] = () => 'macos';
const buildUrl = `https://api.bell-sw.com/v1/liberica/releases?os=macos&bundle-type=jdk&bitness=${distroArch.bitness}&arch=${distroArch.arch}&build-type=all${additionalParams}`;
await distribution['getAvailableVersions']();
expect(spyHttpClient.mock.calls).toHaveLength(1);
expect(spyHttpClient.mock.calls[0][0]).toBe(buildUrl);
}
);
it('load available versions', async () => {
const distribution = new LibericaDistributions({
version: '11',
@ -75,21 +142,24 @@ describe('getAvailableVersions', () => {
describe('getArchitectureOptions', () => {
it.each([
['x86', { bitness: '32', arch: 'x86' }],
['x64', { bitness: '64', arch: 'x86' }],
['armv7', { bitness: '32', arch: 'arm' }],
['aarch64', { bitness: '64', arch: 'arm' }],
['ppc64le', { bitness: '64', arch: 'ppc' }]
] as [string, ArchitectureOptions][])('parse architecture %s -> %s', (input, expected) => {
const distributions = new LibericaDistributions({
architecture: input,
checkLatest: false,
packageType: '',
version: ''
});
['x86', {bitness: '32', arch: 'x86'}],
['x64', {bitness: '64', arch: 'x86'}],
['armv7', {bitness: '32', arch: 'arm'}],
['aarch64', {bitness: '64', arch: 'arm'}],
['ppc64le', {bitness: '64', arch: 'ppc'}]
] as [string, ArchitectureOptions][])(
'parse architecture %s -> %s',
(input, expected) => {
const distributions = new LibericaDistributions({
architecture: input,
checkLatest: false,
packageType: '',
version: ''
});
expect(distributions['getArchitectureOptions']()).toEqual(expected);
});
expect(distributions['getArchitectureOptions']()).toEqual(expected);
}
);
it.each(['armv6', 's390x'])('not support architecture %s', input => {
const distributions = new LibericaDistributions({
@ -165,9 +235,9 @@ describe('getPlatformOption', () => {
it.each(['aix', 'android', 'freebsd', 'openbsd', 'netbsd'])(
'not support os version %s',
input => {
expect(() => distributions['getPlatformOption'](input as NodeJS.Platform)).toThrow(
/Platform '\w+' is not supported\. Supported platforms: .+/
);
expect(() =>
distributions['getPlatformOption'](input as NodeJS.Platform)
).toThrow(/Platform '\w+' is not supported\. Supported platforms: .+/);
}
);
});
@ -181,9 +251,33 @@ describe('convertVersionToSemver', () => {
});
it.each([
[{ featureVersion: 11, interimVersion: 0, updateVersion: 12, buildVersion: 7 }, '11.0.12+7'],
[{ featureVersion: 11, interimVersion: 0, updateVersion: 12, buildVersion: 0 }, '11.0.12'],
[{ featureVersion: 11, interimVersion: 0, updateVersion: 0, buildVersion: 13 }, '11.0.0+13']
[
{
featureVersion: 11,
interimVersion: 0,
updateVersion: 12,
buildVersion: 7
},
'11.0.12+7'
],
[
{
featureVersion: 11,
interimVersion: 0,
updateVersion: 12,
buildVersion: 0
},
'11.0.12'
],
[
{
featureVersion: 11,
interimVersion: 0,
updateVersion: 0,
buildVersion: 13
},
'11.0.0+13'
]
])('%s -> %s', (input, expected) => {
const actual = distributions['convertVersionToSemver']({
downloadUrl: '',

View File

@ -7,7 +7,7 @@ import path from 'path';
import * as semver from 'semver';
import * as util from '../../src/util';
import { LocalDistribution } from '../../src/distributions/local/installer';
import {LocalDistribution} from '../../src/distributions/local/installer';
describe('setupJava', () => {
const actualJavaVersion = '11.1.10';
@ -27,7 +27,7 @@ describe('setupJava', () => {
let spyFsReadDir: jest.SpyInstance;
let spyUtilsExtractJdkFile: jest.SpyInstance;
let spyPathResolve: jest.SpyInstance;
let expectedJdkFile = 'JavaLocalJdkFile';
const expectedJdkFile = 'JavaLocalJdkFile';
beforeEach(() => {
spyGetToolcachePath = jest.spyOn(util, 'getToolcachePath');
@ -35,18 +35,27 @@ describe('setupJava', () => {
(toolname: string, javaVersion: string, architecture: string) => {
const semverVersion = new semver.Range(javaVersion);
if (path.basename(javaPath) !== architecture || !javaPath.includes(toolname)) {
if (
path.basename(javaPath) !== architecture ||
!javaPath.includes(toolname)
) {
return '';
}
return semver.satisfies(actualJavaVersion, semverVersion) ? javaPath : '';
return semver.satisfies(actualJavaVersion, semverVersion)
? javaPath
: '';
}
);
spyTcCacheDir = jest.spyOn(tc, 'cacheDir');
spyTcCacheDir.mockImplementation(
(archivePath: string, toolcacheFolderName: string, version: string, architecture: string) =>
path.join(toolcacheFolderName, version, architecture)
(
archivePath: string,
toolcacheFolderName: string,
version: string,
architecture: string
) => path.join(toolcacheFolderName, version, architecture)
);
spyTcFindAllVersions = jest.spyOn(tc, 'findAllVersions');
@ -74,7 +83,7 @@ describe('setupJava', () => {
spyFsStat = jest.spyOn(fs, 'statSync');
spyFsStat.mockImplementation((file: string) => {
return { isFile: () => file === expectedJdkFile };
return {isFile: () => file === expectedJdkFile};
});
// Spy on util methods
@ -108,7 +117,9 @@ describe('setupJava', () => {
mockJavaBase = new LocalDistribution(inputs, jdkFile);
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyGetToolcachePath).toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith(`Resolved Java ${actualJavaVersion} from tool-cache`);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved Java ${actualJavaVersion} from tool-cache`
);
expect(spyCoreInfo).not.toHaveBeenCalledWith(
`Java ${inputs.version} was not found in tool-cache. Trying to unpack JDK file...`
);
@ -130,7 +141,9 @@ describe('setupJava', () => {
mockJavaBase = new LocalDistribution(inputs, jdkFile);
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyGetToolcachePath).toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith(`Resolved Java ${actualJavaVersion} from tool-cache`);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved Java ${actualJavaVersion} from tool-cache`
);
expect(spyCoreInfo).not.toHaveBeenCalledWith(
`Java ${inputs.version} was not found in tool-cache. Trying to unpack JDK file...`
);
@ -155,7 +168,9 @@ describe('setupJava', () => {
expect(spyCoreInfo).not.toHaveBeenCalledWith(
`Resolved Java ${actualJavaVersion} from tool-cache`
);
expect(spyCoreInfo).toHaveBeenCalledWith(`Extracting Java from '${jdkFile}'`);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Extracting Java from '${jdkFile}'`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Java ${inputs.version} was not found in tool-cache. Trying to unpack JDK file...`
);
@ -171,46 +186,163 @@ describe('setupJava', () => {
const jdkFile = 'not_existing_one';
const expected = {
javaVersion: '11.0.289',
javaPath: path.join('Java_jdkfile_jdk', inputs.version, inputs.architecture)
javaPath: path.join(
'Java_jdkfile_jdk',
inputs.version,
inputs.architecture
)
};
mockJavaBase = new LocalDistribution(inputs, jdkFile);
expected.javaPath = path.join('Java_jdkfile_jdk', inputs.version, inputs.architecture);
await expect(mockJavaBase.setupJava()).rejects.toThrowError(
expected.javaPath = path.join(
'Java_jdkfile_jdk',
inputs.version,
inputs.architecture
);
await expect(mockJavaBase.setupJava()).rejects.toThrow(
"JDK file was not found in path 'not_existing_one'"
);
expect(spyTcFindAllVersions).toHaveBeenCalled();
expect(spyCoreInfo).not.toHaveBeenCalledWith(
`Resolved Java ${actualJavaVersion} from tool-cache`
);
expect(spyCoreInfo).not.toHaveBeenCalledWith(`Extracting Java from '${jdkFile}'`);
expect(spyCoreInfo).not.toHaveBeenCalledWith(
`Extracting Java from '${jdkFile}'`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Java ${inputs.version} was not found in tool-cache. Trying to unpack JDK file...`
);
});
it('java is resolved from toolcache including Contents/Home on MacOS', async () => {
const inputs = {
version: actualJavaVersion,
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
};
const jdkFile = 'not_existing_one';
const expected = {
version: actualJavaVersion,
path: path.join(
'Java_jdkfile_jdk',
inputs.version,
inputs.architecture,
'Contents',
'Home'
)
};
const originalPlatform = process.platform;
Object.defineProperty(process, 'platform', {
value: 'darwin'
});
spyFsStat = jest.spyOn(fs, 'existsSync');
spyFsStat.mockImplementation((file: string) => {
return file.endsWith('Home');
});
mockJavaBase = new LocalDistribution(inputs, jdkFile);
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyGetToolcachePath).toHaveBeenCalled();
expect(spyCoreInfo).toHaveBeenCalledWith(
`Resolved Java ${actualJavaVersion} from tool-cache`
);
expect(spyCoreInfo).not.toHaveBeenCalledWith(
`Java ${inputs.version} was not found in tool-cache. Trying to unpack JDK file...`
);
Object.defineProperty(process, 'platform', {
value: originalPlatform
});
});
it('java is unpacked from jdkfile including Contents/Home on MacOS', async () => {
const inputs = {
version: '11.0.289',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
};
const jdkFile = expectedJdkFile;
const expected = {
version: '11.0.289',
path: path.join(
'Java_jdkfile_jdk',
inputs.version,
inputs.architecture,
'Contents',
'Home'
)
};
const originalPlatform = process.platform;
Object.defineProperty(process, 'platform', {
value: 'darwin'
});
spyFsStat = jest.spyOn(fs, 'existsSync');
spyFsStat.mockImplementation((file: string) => {
return file.endsWith('Home');
});
mockJavaBase = new LocalDistribution(inputs, jdkFile);
await expect(mockJavaBase.setupJava()).resolves.toEqual(expected);
expect(spyTcFindAllVersions).toHaveBeenCalled();
expect(spyCoreInfo).not.toHaveBeenCalledWith(
`Resolved Java ${actualJavaVersion} from tool-cache`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Extracting Java from '${jdkFile}'`
);
expect(spyCoreInfo).toHaveBeenCalledWith(
`Java ${inputs.version} was not found in tool-cache. Trying to unpack JDK file...`
);
Object.defineProperty(process, 'platform', {
value: originalPlatform
});
});
it.each([
[
{ version: '8.0.289', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '8.0.289',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'otherJdkFile'
],
[
{ version: '11.0.289', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '11.0.289',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'otherJdkFile'
],
[
{ version: '12.0.289', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '12.0.289',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'otherJdkFile'
],
[
{ version: '11.1.11', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '11.1.11',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'not_existing_one'
]
])(
`Throw an error if jdkfile has wrong path, inputs %s, jdkfile %s, real name ${expectedJdkFile}`,
async (inputs, jdkFile) => {
mockJavaBase = new LocalDistribution(inputs, jdkFile);
await expect(mockJavaBase.setupJava()).rejects.toThrowError(
await expect(mockJavaBase.setupJava()).rejects.toThrow(
/JDK file was not found in path */
);
expect(spyTcFindAllVersions).toHaveBeenCalled();
@ -218,18 +350,41 @@ describe('setupJava', () => {
);
it.each([
[{ version: '8.0.289', architecture: 'x64', packageType: 'jdk', checkLatest: false }, ''],
[
{ version: '7.0.289', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '8.0.289',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
''
],
[
{
version: '7.0.289',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
undefined
],
[
{ version: '11.0.289', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '11.0.289',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
undefined
]
])('Throw an error if jdkfile is not specified, inputs %s', async (inputs, jdkFile) => {
mockJavaBase = new LocalDistribution(inputs, jdkFile);
await expect(mockJavaBase.setupJava()).rejects.toThrowError("'jdkFile' is not specified");
expect(spyTcFindAllVersions).toHaveBeenCalled();
});
])(
'Throw an error if jdkfile is not specified, inputs %s',
async (inputs, jdkFile) => {
mockJavaBase = new LocalDistribution(inputs, jdkFile);
await expect(mockJavaBase.setupJava()).rejects.toThrow(
"'jdkFile' is not specified"
);
expect(spyTcFindAllVersions).toHaveBeenCalled();
}
);
});

View File

@ -1,7 +1,13 @@
import { MicrosoftDistributions } from '../../src/distributions/microsoft/installer';
import {MicrosoftDistributions} from '../../src/distributions/microsoft/installer';
import os from 'os';
import data from '../data/microsoft.json';
import * as httpm from '@actions/http-client';
import * as core from '@actions/core';
describe('findPackageForDownload', () => {
let distribution: MicrosoftDistributions;
let spyGetManifestFromRepo: jest.SpyInstance;
let spyDebug: jest.SpyInstance;
beforeEach(() => {
distribution = new MicrosoftDistributions({
@ -10,23 +16,48 @@ describe('findPackageForDownload', () => {
packageType: 'jdk',
checkLatest: false
});
spyGetManifestFromRepo = jest.spyOn(httpm.HttpClient.prototype, 'getJson');
spyGetManifestFromRepo.mockReturnValue({
result: data,
statusCode: 200,
headers: {}
});
spyDebug = jest.spyOn(core, 'debug');
spyDebug.mockImplementation(() => {});
});
it.each([
[
'17.x',
'17.0.1',
'17.0.1+12.1',
'https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-{{OS_TYPE}}-x64.{{ARCHIVE_TYPE}}'
],
[
'17.x',
'17.0.7',
'https://aka.ms/download-jdk/microsoft-jdk-17.0.7-{{OS_TYPE}}-x64.{{ARCHIVE_TYPE}}'
],
[
'16.0.x',
'16.0.2',
'16.0.2+7.1',
'https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-{{OS_TYPE}}-x64.{{ARCHIVE_TYPE}}'
],
[
'11.0.13',
'11.0.13',
'11.0.13+8.1',
'https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-{{OS_TYPE}}-x64.{{ARCHIVE_TYPE}}'
],
[
'11.0.15',
'11.0.15',
'https://aka.ms/download-jdk/microsoft-jdk-11.0.15-{{OS_TYPE}}-x64.{{ARCHIVE_TYPE}}'
],
[
'11.x',
'11.0.19',
'https://aka.ms/download-jdk/microsoft-jdk-11.0.19-{{OS_TYPE}}-x64.{{ARCHIVE_TYPE}}'
]
])('version is %s -> %s', async (input, expectedVersion, expectedUrl) => {
const result = await distribution['findPackageForDownload'](input);
@ -47,42 +78,39 @@ describe('findPackageForDownload', () => {
archive = 'tar.gz';
break;
}
const url = expectedUrl.replace('{{OS_TYPE}}', os).replace('{{ARCHIVE_TYPE}}', archive);
const url = expectedUrl
.replace('{{OS_TYPE}}', os)
.replace('{{ARCHIVE_TYPE}}', archive);
expect(result.url).toBe(url);
});
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);
jest.spyOn(os, 'platform').mockReturnValue('linux');
const version = '17';
const distro = new MicrosoftDistributions({
version,
architecture: '', // to get default value
packageType: 'jdk',
checkLatest: false
});
const result = await distro['findPackageForDownload'](version);
const expectedUrl = `https://aka.ms/download-jdk/microsoft-jdk-17.0.7-linux-${distroArch}.tar.gz`;
expect(result.url).toBe(expectedUrl);
}
);
it('should throw an error', async () => {
await expect(distribution['findPackageForDownload']('8')).rejects.toThrow(
/Could not find satisfied version for SemVer */
);
});
});
describe('getPlatformOption', () => {
const distributions = new MicrosoftDistributions({
architecture: 'x64',
version: '11',
packageType: 'jdk',
checkLatest: false
});
it.each([
['linux', 'tar.gz', 'linux'],
['darwin', 'tar.gz', 'macos'],
['win32', 'zip', 'windows']
])('os version %s -> %s', (input, expectedArchive, expectedOs) => {
const actual = distributions['getPlatformOption'](input as NodeJS.Platform);
expect(actual.archive).toEqual(expectedArchive);
expect(actual.os).toEqual(expectedOs);
});
it.each(['aix', 'android', 'freebsd', 'openbsd', 'netbsd', 'solaris', 'cygwin'])(
'not support os version %s',
input => {
expect(() => distributions['getPlatformOption'](input as NodeJS.Platform)).toThrow(
/Platform '\w+' is not supported\. Supported platforms: .+/
);
}
);
});

View File

@ -0,0 +1,124 @@
import {OracleDistribution} from '../../src/distributions/oracle/installer';
import os from 'os';
import * as core from '@actions/core';
import {getDownloadArchiveExtension} from '../../src/util';
import {HttpClient} from '@actions/http-client';
describe('findPackageForDownload', () => {
let distribution: OracleDistribution;
let spyDebug: jest.SpyInstance;
let spyHttpClient: jest.SpyInstance;
beforeEach(() => {
distribution = new OracleDistribution({
version: '',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
spyDebug = jest.spyOn(core, 'debug');
spyDebug.mockImplementation(() => {});
});
it.each([
[
'20',
'20',
'https://download.oracle.com/java/20/latest/jdk-20_{{OS_TYPE}}-x64_bin.{{ARCHIVE_TYPE}}'
],
[
'18',
'18',
'https://download.oracle.com/java/18/archive/jdk-18_{{OS_TYPE}}-x64_bin.{{ARCHIVE_TYPE}}'
],
[
'20.0.1',
'20.0.1',
'https://download.oracle.com/java/20/archive/jdk-20.0.1_{{OS_TYPE}}-x64_bin.{{ARCHIVE_TYPE}}'
],
[
'17',
'17',
'https://download.oracle.com/java/17/latest/jdk-17_{{OS_TYPE}}-x64_bin.{{ARCHIVE_TYPE}}'
],
[
'17.0.1',
'17.0.1',
'https://download.oracle.com/java/17/archive/jdk-17.0.1_{{OS_TYPE}}-x64_bin.{{ARCHIVE_TYPE}}'
]
])('version is %s -> %s', async (input, expectedVersion, expectedUrl) => {
/* Needed only for this particular test because some urls might change */
spyHttpClient = jest.spyOn(HttpClient.prototype, 'head');
spyHttpClient.mockReturnValue(
Promise.resolve({
message: {
statusCode: 200
}
})
);
/**
* NOTE - Should fail to retrieve 18 from latest and check archive instead
*/
if (input === '18') {
spyHttpClient.mockReturnValueOnce(
Promise.resolve({
message: {
statusCode: 404
}
})
);
}
const result = await distribution['findPackageForDownload'](input);
jest.restoreAllMocks();
expect(result.version).toBe(expectedVersion);
const osType = distribution.getPlatform();
const archiveType = getDownloadArchiveExtension();
const url = expectedUrl
.replace('{{OS_TYPE}}', osType)
.replace('{{ARCHIVE_TYPE}}', archiveType);
expect(result.url).toBe(url);
});
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);
jest.spyOn(os, 'platform').mockReturnValue('linux');
const version = '18';
const distro = new OracleDistribution({
version,
architecture: '', // to get default value
packageType: 'jdk',
checkLatest: false
});
const osType = distribution.getPlatform();
if (osType === 'windows' && distroArch == 'aarch64') {
return; // skip, aarch64 is not available for Windows
}
const archiveType = getDownloadArchiveExtension();
const result = await distro['findPackageForDownload'](version);
const expectedUrl = `https://download.oracle.com/java/18/archive/jdk-18_${osType}-${distroArch}_bin.${archiveType}`;
expect(result.url).toBe(expectedUrl);
}
);
it('should throw an error', async () => {
await expect(distribution['findPackageForDownload']('8')).rejects.toThrow(
/Oracle JDK is only supported for JDK 17 and later/
);
await expect(distribution['findPackageForDownload']('11')).rejects.toThrow(
/Oracle JDK is only supported for JDK 17 and later/
);
});
});

View File

@ -0,0 +1,287 @@
import {HttpClient} from '@actions/http-client';
import {JavaInstallerOptions} from '../../src/distributions/base-models';
import {SemeruDistribution} from '../../src/distributions/semeru/installer';
import manifestData from '../data/semeru.json';
describe('getAvailableVersions', () => {
let spyHttpClient: jest.SpyInstance;
beforeEach(() => {
spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
spyHttpClient.mockReturnValue({
statusCode: 200,
headers: {},
result: []
});
});
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
jest.restoreAllMocks();
});
it.each([
[
{
version: '16',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'os=mac&architecture=x64&image_type=jdk&release_type=ga&jvm_impl=openj9&page_size=20&page=0'
],
[
{
version: '16',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
'os=mac&architecture=x86&image_type=jdk&release_type=ga&jvm_impl=openj9&page_size=20&page=0'
],
[
{
version: '16',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
'os=mac&architecture=x64&image_type=jre&release_type=ga&jvm_impl=openj9&page_size=20&page=0'
],
[
{
version: '16',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'os=mac&architecture=x64&image_type=jdk&release_type=ga&jvm_impl=openj9&page_size=20&page=0'
]
])(
'build correct url for %s',
async (installerOptions: JavaInstallerOptions, expectedParameters) => {
const distribution = new SemeruDistribution(installerOptions);
const baseUrl =
'https://api.adoptopenjdk.net/v3/assets/version/%5B1.0,100.0%5D';
const expectedUrl = `${baseUrl}?project=jdk&vendor=ibm&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 () => {
spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
spyHttpClient
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: manifestData as any
})
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: manifestData as any
})
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: []
});
const distribution = new SemeruDistribution({
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
const availableVersions = await distribution['getAvailableVersions']();
expect(availableVersions).not.toBeNull();
expect(availableVersions.length).toBe(manifestData.length * 2);
});
it.each([
['jdk', 'Java_IBM_Semeru_jdk'],
['jre', 'Java_IBM_Semeru_jre']
])('find right toolchain folder', (packageType: string, expected: string) => {
const distribution = new SemeruDistribution({
version: '8',
architecture: 'x64',
packageType: packageType,
checkLatest: false
});
// @ts-ignore - because it is protected
expect(distribution.toolcacheFolderName).toBe(expected);
});
});
describe('findPackageForDownload', () => {
it.each([
['8', '8.0.322+6'],
['16', '16.0.2+7'],
['16.0', '16.0.2+7'],
['16.0.2', '16.0.2+7'],
['8.x', '8.0.322+6'],
['x', '17.0.2+8']
])('version is resolved correctly %s -> %s', async (input, expected) => {
const distribution = new SemeruDistribution({
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
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 SemeruDistribution({
version: '9.0.8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(
distribution['findPackageForDownload']('9.0.8')
).rejects.toThrow(/Could not find satisfied version for SemVer */);
});
it('version is not found', async () => {
const distribution = new SemeruDistribution({
version: '7.x',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(distribution['findPackageForDownload']('7.x')).rejects.toThrow(
/Could not find satisfied version for SemVer */
);
});
it('version list is empty', async () => {
const distribution = new SemeruDistribution({
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => [];
await expect(distribution['findPackageForDownload']('8')).rejects.toThrow(
/Could not find satisfied version for SemVer */
);
});
it.each(['x64', 'x86', 'ppc64le', 'ppc64', 's390x', 'aarch64'])(
'correct Semeru `%s` architecture resolves',
async (arch: string) => {
const distribution = new SemeruDistribution({
version: '8',
architecture: arch,
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
const resolvedVersion = await distribution['findPackageForDownload']('8');
expect(resolvedVersion.version).not.toBeNull();
}
);
it.each(['zos', 'z/OS', 'z/os', 'test0987654321=', '++=++', 'myArch'])(
'incorrect Semeru `%s` architecture throws',
async (arch: string) => {
const distribution = new SemeruDistribution({
version: '8',
architecture: arch,
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => [];
await expect(distribution['findPackageForDownload']('8')).rejects.toThrow(
`Unsupported architecture for IBM Semeru: ${arch}, the following are supported: x64, x86, ppc64le, ppc64, s390x, aarch64`
);
}
);
it.each(['9-ea', '17-ea', '8-ea', '4-ea'])(
'early access version are illegal for Semeru (%s)',
async (version: string) => {
const distribution = new SemeruDistribution({
version: version,
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(
distribution['findPackageForDownload'](version)
).rejects.toThrow(
'IBM Semeru does not provide builds for early access versions'
);
}
);
it.each([
'jdk+fx',
'jre+fx',
'test',
'test2',
'jdk-fx',
'javafx',
'jdk-javafx',
'ibm',
' '
])(
'rejects incorrect `%s` Semeru package type',
async (packageType: string) => {
const distribution = new SemeruDistribution({
version: '8',
architecture: 'x64',
packageType: packageType,
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(distribution['findPackageForDownload']('8')).rejects.toThrow(
'IBM Semeru only provide `jdk` and `jre` package types'
);
}
);
it.each(['jdk', 'jre'])(
'accepts correct `%s` Semeru package type',
async (packageType: string) => {
const distribution = new SemeruDistribution({
version: '8',
architecture: 'x64',
packageType: packageType,
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData as any;
const resolvedVersion = await distribution['findPackageForDownload']('8');
await expect(resolvedVersion.version).toMatch(/8[0-9.]+/);
}
);
it('fails when long release name is used', async () => {
expect(
() =>
new SemeruDistribution({
version: 'jdk-16.0.2+7_openj9-0.27.1',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
})
).toThrow(
"The string 'jdk-16.0.2+7_openj9-0.27.1' is not valid SemVer notation for a Java version. Please check README file for code snippets and more detailed information"
);
});
});

View File

@ -1,12 +1,12 @@
import { HttpClient } from '@actions/http-client';
import {HttpClient} from '@actions/http-client';
import os from 'os';
import {
TemurinDistribution,
TemurinImplementation
} from '../../src/distributions/temurin/installer';
import { JavaInstallerOptions } from '../../src/distributions/base-models';
import {JavaInstallerOptions} from '../../src/distributions/base-models';
let manifestData = require('../data/temurin.json') as [];
import manifestData from '../data/temurin.json';
describe('getAvailableVersions', () => {
let spyHttpClient: jest.SpyInstance;
@ -28,22 +28,42 @@ describe('getAvailableVersions', () => {
it.each([
[
{ version: '16', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '16',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jdk&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{ version: '16', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{
version: '16',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot,
'os=mac&architecture=x86&image_type=jdk&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{ version: '16', architecture: 'x64', packageType: 'jre', checkLatest: false },
{
version: '16',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
TemurinImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jre&release_type=ga&jvm_impl=hotspot&page_size=20&page=0'
],
[
{ version: '16-ea', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '16-ea',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot,
'os=mac&architecture=x64&image_type=jdk&release_type=ea&jvm_impl=hotspot&page_size=20&page=0'
]
@ -55,7 +75,8 @@ describe('getAvailableVersions', () => {
expectedParameters
) => {
const distribution = new TemurinDistribution(installerOptions, impl);
const baseUrl = 'https://api.adoptium.net/v3/assets/version/%5B1.0,100.0%5D';
const baseUrl =
'https://api.adoptium.net/v3/assets/version/%5B1.0,100.0%5D';
const expectedUrl = `${baseUrl}?project=jdk&vendor=adoptium&heap_size=normal&sort_method=DEFAULT&sort_order=DESC&${expectedParameters}`;
distribution['getPlatformOption'] = () => 'mac';
@ -72,12 +93,12 @@ describe('getAvailableVersions', () => {
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: manifestData
result: manifestData as any
})
.mockReturnValueOnce({
statusCode: 200,
headers: {},
result: manifestData
result: manifestData as any
})
.mockReturnValueOnce({
statusCode: 200,
@ -86,7 +107,12 @@ describe('getAvailableVersions', () => {
});
const distribution = new TemurinDistribution(
{ version: '8', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot
);
const availableVersions = await distribution['getAvailableVersions']();
@ -101,7 +127,12 @@ describe('getAvailableVersions', () => {
'find right toolchain folder',
(impl: TemurinImplementation, packageType: string, expected: string) => {
const distribution = new TemurinDistribution(
{ version: '8', architecture: 'x64', packageType: packageType, checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: packageType,
checkLatest: false
},
impl
);
@ -109,6 +140,39 @@ describe('getAvailableVersions', () => {
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(distroArch);
const installerOptions: JavaInstallerOptions = {
version: '17',
architecture: '',
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 TemurinDistribution(
installerOptions,
TemurinImplementation.Hotspot
);
const baseUrl =
'https://api.adoptium.net/v3/assets/version/%5B1.0,100.0%5D';
const expectedUrl = `${baseUrl}?project=jdk&vendor=adoptium&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', () => {
@ -121,43 +185,63 @@ describe('findPackageForDownload', () => {
['x', '16.0.2+7']
])('version is resolved correctly %s -> %s', async (input, expected) => {
const distribution = new TemurinDistribution(
{ version: '8', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => manifestData;
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 TemurinDistribution(
{ version: '9.0.8', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '9.0.8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => manifestData;
await expect(distribution['findPackageForDownload']('9.0.8')).rejects.toThrowError(
/Could not find satisfied version for SemVer */
);
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(
distribution['findPackageForDownload']('9.0.8')
).rejects.toThrow(/Could not find satisfied version for SemVer */);
});
it('version is not found', async () => {
const distribution = new TemurinDistribution(
{ version: '7.x', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '7.x',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => manifestData;
await expect(distribution['findPackageForDownload']('7.x')).rejects.toThrowError(
distribution['getAvailableVersions'] = async () => manifestData as any;
await expect(distribution['findPackageForDownload']('7.x')).rejects.toThrow(
/Could not find satisfied version for SemVer */
);
});
it('version list is empty', async () => {
const distribution = new TemurinDistribution(
{ version: '8', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
TemurinImplementation.Hotspot
);
distribution['getAvailableVersions'] = async () => [];
await expect(distribution['findPackageForDownload']('8')).rejects.toThrowError(
await expect(distribution['findPackageForDownload']('8')).rejects.toThrow(
/Could not find satisfied version for SemVer */
);
});

View File

@ -1,10 +1,11 @@
import { HttpClient } from '@actions/http-client';
import {HttpClient} from '@actions/http-client';
import * as semver from 'semver';
import { ZuluDistribution } from '../../src/distributions/zulu/installer';
import { IZuluVersions } from '../../src/distributions/zulu/models';
import {ZuluDistribution} from '../../src/distributions/zulu/installer';
import {IZuluVersions} from '../../src/distributions/zulu/models';
import * as utils from '../../src/util';
import os from 'os';
const manifestData = require('../data/zulu-releases-default.json') as [];
import manifestData from '../data/zulu-releases-default.json';
describe('getAvailableVersions', () => {
let spyHttpClient: jest.SpyInstance;
@ -18,7 +19,10 @@ describe('getAvailableVersions', () => {
result: manifestData as IZuluVersions[]
});
spyUtilGetDownloadArchiveExtension = jest.spyOn(utils, 'getDownloadArchiveExtension');
spyUtilGetDownloadArchiveExtension = jest.spyOn(
utils,
'getDownloadArchiveExtension'
);
spyUtilGetDownloadArchiveExtension.mockReturnValue('tar.gz');
});
@ -30,28 +34,76 @@ describe('getAvailableVersions', () => {
it.each([
[
{ version: '11', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{
version: '11',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jdk&javafx=false&arch=x86&hw_bitness=32&release_status=ga'
],
[
{ version: '11-ea', architecture: 'x86', packageType: 'jdk', checkLatest: false },
{
version: '11-ea',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jdk&javafx=false&arch=x86&hw_bitness=32&release_status=ea'
],
[
{ version: '8', architecture: 'x64', packageType: 'jdk', checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: 'jdk',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jdk&javafx=false&arch=x86&hw_bitness=64&release_status=ga'
],
[
{ version: '8', architecture: 'x64', packageType: 'jre', checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: 'jre',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jre&javafx=false&arch=x86&hw_bitness=64&release_status=ga'
],
[
{ version: '8', architecture: 'x64', packageType: 'jdk+fx', checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: 'jdk+fx',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jdk&javafx=true&arch=x86&hw_bitness=64&release_status=ga&features=fx'
],
[
{ version: '8', architecture: 'x64', packageType: 'jre+fx', checkLatest: false },
{
version: '8',
architecture: 'x64',
packageType: 'jre+fx',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jre&javafx=true&arch=x86&hw_bitness=64&release_status=ga&features=fx'
],
[
{
version: '11',
architecture: 'arm64',
packageType: 'jdk',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jdk&javafx=false&arch=arm&hw_bitness=64&release_status=ga'
],
[
{
version: '11',
architecture: 'arm',
packageType: 'jdk',
checkLatest: false
},
'?os=macos&ext=tar.gz&bundle_type=jdk&javafx=false&arch=arm&hw_bitness=&release_status=ga'
]
])('build correct url for %s -> %s', async (input, parsedUrl) => {
const distribution = new ZuluDistribution(input);
@ -64,6 +116,34 @@ describe('getAvailableVersions', () => {
expect(spyHttpClient.mock.calls[0][0]).toBe(buildUrl);
});
type DistroArch = {
bitness: string;
arch: string;
};
it.each([
['amd64', {bitness: '64', arch: 'x86'}],
['arm64', {bitness: '64', arch: 'arm'}]
])(
'defaults to os.arch(): %s mapped to distro arch: %s',
async (osArch: string, distroArch: DistroArch) => {
jest.spyOn(os, 'arch').mockReturnValue(osArch);
const distribution = new ZuluDistribution({
version: '17',
architecture: '', // to get default value
packageType: 'jdk',
checkLatest: false
});
distribution['getPlatformOption'] = () => 'macos';
const buildUrl = `https://api.azul.com/zulu/download/community/v1.0/bundles/?os=macos&ext=tar.gz&bundle_type=jdk&javafx=false&arch=${distroArch.arch}&hw_bitness=${distroArch.bitness}&release_status=ga`;
await distribution['getAvailableVersions']();
expect(spyHttpClient.mock.calls).toHaveLength(1);
expect(spyHttpClient.mock.calls[0][0]).toBe(buildUrl);
}
);
it('load available versions', async () => {
const distribution = new ZuluDistribution({
version: '11',
@ -78,10 +158,10 @@ describe('getAvailableVersions', () => {
describe('getArchitectureOptions', () => {
it.each([
[{ architecture: 'x64' }, { arch: 'x86', hw_bitness: '64', abi: '' }],
[{ architecture: 'x86' }, { arch: 'x86', hw_bitness: '32', abi: '' }],
[{ architecture: 'x32' }, { arch: 'x32', hw_bitness: '', abi: '' }],
[{ architecture: 'arm' }, { arch: 'arm', hw_bitness: '', abi: '' }]
[{architecture: 'x64'}, {arch: 'x86', hw_bitness: '64', abi: ''}],
[{architecture: 'x86'}, {arch: 'x86', hw_bitness: '32', abi: ''}],
[{architecture: 'x32'}, {arch: 'x32', hw_bitness: '', abi: ''}],
[{architecture: 'arm'}, {arch: 'arm', hw_bitness: '', abi: ''}]
])('%s -> %s', (input, expected) => {
const distribution = new ZuluDistribution({
version: '11',
@ -102,7 +182,7 @@ describe('findPackageForDownload', () => {
['15', '15.0.2+7'],
['9.0.0', '9.0.0+0'],
['9.0', '9.0.1+0'],
['8.0.262', '8.0.262+19'], // validate correct choise between [8.0.262.17, 8.0.262.19, 8.0.262.18]
['8.0.262', '8.0.262+19'], // validate correct choice between [8.0.262.17, 8.0.262.19, 8.0.262.18]
['8.0.262+17', '8.0.262+17'],
['15.0.1+8', '15.0.1+8'],
['15.0.1+9', '15.0.1+9']
@ -114,7 +194,9 @@ describe('findPackageForDownload', () => {
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData;
const result = await distribution['findPackageForDownload'](distribution['version']);
const result = await distribution['findPackageForDownload'](
distribution['version']
);
expect(result.version).toBe(expected);
});
@ -139,27 +221,9 @@ describe('findPackageForDownload', () => {
packageType: 'jdk',
checkLatest: false
});
distribution['getAvailableVersions'] = async () => manifestData;
await expect(
distribution['findPackageForDownload'](distribution['version'])
).rejects.toThrowError(/Could not find satisfied version for semver */);
});
});
describe('convertVersionToSemver', () => {
it.each([
[[12], '12'],
[[12, 0], '12.0'],
[[12, 0, 2], '12.0.2'],
[[12, 0, 2, 1], '12.0.2+1'],
[[12, 0, 2, 1, 3], '12.0.2+1']
])('%s -> %s', (input: number[], expected: string) => {
const distribution = new ZuluDistribution({
version: '18',
architecture: 'x86',
packageType: 'jdk',
checkLatest: false
});
const actual = distribution['convertVersionToSemver'](input);
expect(actual).toBe(expected);
).rejects.toThrow(/Could not find satisfied version for semver */);
});
});

View File

@ -1,6 +1,7 @@
import path = require('path');
import io = require('@actions/io');
import exec = require('@actions/exec');
import * as path from 'path';
import * as io from '@actions/io';
import * as exec from '@actions/exec';
import * as gpg from '../src/gpg';
jest.mock('@actions/exec', () => {
return {
@ -11,8 +12,6 @@ jest.mock('@actions/exec', () => {
const tempDir = path.join(__dirname, 'runner', 'temp');
process.env['RUNNER_TEMP'] = tempDir;
import gpg = require('../src/gpg');
describe('gpg tests', () => {
beforeEach(async () => {
await io.mkdirP(tempDir);
@ -33,7 +32,11 @@ describe('gpg tests', () => {
expect(keyId).toBeNull();
expect(exec.exec).toHaveBeenCalledWith('gpg', expect.anything(), expect.anything());
expect(exec.exec).toHaveBeenCalledWith(
'gpg',
expect.anything(),
expect.anything()
);
});
});
@ -42,7 +45,11 @@ describe('gpg tests', () => {
const keyId = 'asdfhjkl';
await gpg.deleteKey(keyId);
expect(exec.exec).toHaveBeenCalledWith('gpg', expect.anything(), expect.anything());
expect(exec.exec).toHaveBeenCalledWith(
'gpg',
expect.anything(),
expect.anything()
);
});
});
});

View File

@ -0,0 +1,304 @@
import * as fs from 'fs';
import os from 'os';
import * as path from 'path';
import * as core from '@actions/core';
import * as io from '@actions/io';
import * as toolchains from '../src/toolchains';
import {M2_DIR, MVN_TOOLCHAINS_FILE} from '../src/constants';
const m2Dir = path.join(__dirname, M2_DIR);
const toolchainsFile = path.join(m2Dir, MVN_TOOLCHAINS_FILE);
describe('toolchains tests', () => {
let spyOSHomedir: jest.SpyInstance;
let spyInfo: jest.SpyInstance;
beforeEach(async () => {
await io.rmRF(m2Dir);
spyOSHomedir = jest.spyOn(os, 'homedir');
spyOSHomedir.mockReturnValue(__dirname);
spyInfo = jest.spyOn(core, 'info');
spyInfo.mockImplementation(() => null);
}, 300000);
afterAll(async () => {
try {
await io.rmRF(m2Dir);
} catch {
console.log('Failed to remove test directories');
}
jest.resetAllMocks();
jest.clearAllMocks();
jest.restoreAllMocks();
}, 100000);
it('creates toolchains.xml in alternate locations', async () => {
const jdkInfo = {
version: '17',
vendor: 'Eclipse Temurin',
id: 'temurin_17',
jdkHome: '/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/17.0.1-12/x64'
};
const altHome = path.join(__dirname, 'runner', 'toolchains');
const altToolchainsFile = path.join(altHome, MVN_TOOLCHAINS_FILE);
await io.rmRF(altHome); // ensure it doesn't already exist
await toolchains.createToolchainsSettings({
jdkInfo,
settingsDirectory: altHome,
overwriteSettings: true
});
expect(fs.existsSync(m2Dir)).toBe(false);
expect(fs.existsSync(toolchainsFile)).toBe(false);
expect(fs.existsSync(altHome)).toBe(true);
expect(fs.existsSync(altToolchainsFile)).toBe(true);
expect(fs.readFileSync(altToolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
)
);
await io.rmRF(altHome);
}, 100000);
it('creates toolchains.xml with minimal configuration', async () => {
const jdkInfo = {
version: '17',
vendor: 'Eclipse Temurin',
id: 'temurin_17',
jdkHome: '/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/17.0.1-12/x64'
};
const result = `<?xml version="1.0"?>
<toolchains xmlns="https://maven.apache.org/TOOLCHAINS/1.1.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/TOOLCHAINS/1.1.0 https://maven.apache.org/xsd/toolchains-1.1.0.xsd">
<toolchain>
<type>jdk</type>
<provides>
<version>17</version>
<vendor>Eclipse Temurin</vendor>
<id>temurin_17</id>
</provides>
<configuration>
<jdkHome>/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/17.0.1-12/x64</jdkHome>
</configuration>
</toolchain>
</toolchains>`;
await toolchains.createToolchainsSettings({
jdkInfo,
settingsDirectory: m2Dir,
overwriteSettings: true
});
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
)
);
expect(
toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
)
).toEqual(result);
}, 100000);
it('reuses existing toolchains.xml files', async () => {
const jdkInfo = {
version: '17',
vendor: 'Eclipse Temurin',
id: 'temurin_17',
jdkHome: '/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/17.0.1-12/x64'
};
const originalFile = `<toolchains>
<toolchain>
<type>jdk</type>
<provides>
<version>1.6</version>
<vendor>Sun</vendor>
<id>sun_1.6</id>
</provides>
<configuration>
<jdkHome>/opt/jdk/sun/1.6</jdkHome>
</configuration>
</toolchain>
</toolchains>`;
const result = `<?xml version="1.0"?>
<toolchains>
<toolchain>
<type>jdk</type>
<provides>
<version>1.6</version>
<vendor>Sun</vendor>
<id>sun_1.6</id>
</provides>
<configuration>
<jdkHome>/opt/jdk/sun/1.6</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>17</version>
<vendor>Eclipse Temurin</vendor>
<id>temurin_17</id>
</provides>
<configuration>
<jdkHome>/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/17.0.1-12/x64</jdkHome>
</configuration>
</toolchain>
</toolchains>`;
fs.mkdirSync(m2Dir, {recursive: true});
fs.writeFileSync(toolchainsFile, originalFile);
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
await toolchains.createToolchainsSettings({
jdkInfo,
settingsDirectory: m2Dir,
overwriteSettings: true
});
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
)
);
expect(
toolchains.generateToolchainDefinition(
originalFile,
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
)
).toEqual(result);
}, 100000);
it('does not overwrite existing toolchains.xml files', async () => {
const jdkInfo = {
version: '17',
vendor: 'Eclipse Temurin',
id: 'temurin_17',
jdkHome: '/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/17.0.1-12/x64'
};
const originalFile = `<toolchains>
<toolchain>
<type>jdk</type>
<provides>
<version>1.6</version>
<vendor>Sun</vendor>
<id>sun_1.6</id>
</provides>
<configuration>
<jdkHome>/opt/jdk/sun/1.6</jdkHome>
</configuration>
</toolchain>
</toolchains>`;
fs.mkdirSync(m2Dir, {recursive: true});
fs.writeFileSync(toolchainsFile, originalFile);
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
await toolchains.createToolchainsSettings({
jdkInfo,
settingsDirectory: m2Dir,
overwriteSettings: false
});
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(originalFile);
}, 100000);
it('generates valid toolchains.xml with minimal configuration', () => {
const jdkInfo = {
version: 'JAVA_VERSION',
vendor: 'JAVA_VENDOR',
id: 'VENDOR_VERSION',
jdkHome: 'JAVA_HOME'
};
const expectedToolchains = `<?xml version="1.0"?>
<toolchains xmlns="https://maven.apache.org/TOOLCHAINS/1.1.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/TOOLCHAINS/1.1.0 https://maven.apache.org/xsd/toolchains-1.1.0.xsd">
<toolchain>
<type>jdk</type>
<provides>
<version>${jdkInfo.version}</version>
<vendor>${jdkInfo.vendor}</vendor>
<id>${jdkInfo.id}</id>
</provides>
<configuration>
<jdkHome>${jdkInfo.jdkHome}</jdkHome>
</configuration>
</toolchain>
</toolchains>`;
expect(
toolchains.generateToolchainDefinition(
'',
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
)
).toEqual(expectedToolchains);
}, 100000);
it('creates toolchains.xml with correct id when none is supplied', async () => {
const version = '17';
const distributionName = 'temurin';
const id = 'temurin_17';
const jdkHome =
'/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/17.0.1-12/x64';
await toolchains.configureToolchains(
version,
distributionName,
jdkHome,
undefined
);
expect(fs.existsSync(m2Dir)).toBe(true);
expect(fs.existsSync(toolchainsFile)).toBe(true);
expect(fs.readFileSync(toolchainsFile, 'utf-8')).toEqual(
toolchains.generateToolchainDefinition(
'',
version,
distributionName,
id,
jdkHome
)
);
}, 100000);
});

View File

@ -1,4 +1,13 @@
import { isVersionSatisfies } from '../src/util';
import * as cache from '@actions/cache';
import * as core from '@actions/core';
import {
convertVersionToSemver,
isVersionSatisfies,
isCacheFeatureAvailable
} from '../src/util';
jest.mock('@actions/cache');
jest.mock('@actions/core');
describe('isVersionSatisfies', () => {
it.each([
@ -15,8 +24,59 @@ describe('isVersionSatisfies', () => {
['2.5.1+3', '2.5.1+2', false],
['15.0.0+14', '15.0.0+14.1.202003190635', false],
['15.0.0+14.1.202003190635', '15.0.0+14.1.202003190635', true]
])('%s, %s -> %s', (inputRange: string, inputVersion: string, expected: boolean) => {
const actual = isVersionSatisfies(inputRange, inputVersion);
])(
'%s, %s -> %s',
(inputRange: string, inputVersion: string, expected: boolean) => {
const actual = isVersionSatisfies(inputRange, inputVersion);
expect(actual).toBe(expected);
}
);
});
describe('isCacheFeatureAvailable', () => {
it('isCacheFeatureAvailable disabled on GHES', () => {
jest.spyOn(cache, 'isFeatureAvailable').mockImplementation(() => false);
const infoMock = jest.spyOn(core, 'warning');
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', () => {
jest.spyOn(cache, 'isFeatureAvailable').mockImplementation(() => false);
const infoMock = jest.spyOn(core, 'warning');
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', () => {
jest.spyOn(cache, 'isFeatureAvailable').mockImplementation(() => true);
expect(isCacheFeatureAvailable()).toBe(true);
});
});
describe('convertVersionToSemver', () => {
it.each([
['12', '12'],
['12.0', '12.0'],
['12.0.2', '12.0.2'],
['12.0.2.1', '12.0.2+1'],
['12.0.2.1.0', '12.0.2+1.0']
])('%s -> %s', (input: string, expected: string) => {
const actual = convertVersionToSemver(input);
expect(actual).toBe(expected);
});
});

View File

@ -24,7 +24,7 @@ fi
ACTUAL_JAVA_VERSION="$(java -version 2>&1)"
echo "Found java version: $ACTUAL_JAVA_VERSION"
GREP_RESULT=$(echo $ACTUAL_JAVA_VERSION | grep "^openjdk version \"$EXPECTED_JAVA_VERSION")
GREP_RESULT=$(echo $ACTUAL_JAVA_VERSION | grep -E "^(openjdk|java) version \"$EXPECTED_JAVA_VERSION")
if [ -z "$GREP_RESULT" ]; then
echo "::error::Unexpected version"
echo "Expected version: $EXPECTED_JAVA_VERSION"

View File

@ -5,7 +5,8 @@ author: 'GitHub'
inputs:
java-version:
description: 'The Java version to set up. Takes a whole or semver Java version. See examples of supported syntax in README file'
required: true
java-version-file:
description: 'The path to the `.java-version` file. See examples of supported syntax in README file'
distribution:
description: 'Java distribution. See the list of supported distributions in README file'
required: true
@ -14,9 +15,8 @@ inputs:
required: false
default: 'jdk'
architecture:
description: 'The architecture of the package'
description: "The architecture of the package (defaults to the action runner's architecture)"
required: false
default: 'x64'
jdkFile:
description: 'Path to where the compressed JDK is located'
required: false
@ -54,11 +54,20 @@ inputs:
$GPG_PASSPHRASE.'
required: false
cache:
description: 'Name of the build platform to cache dependencies. It can be "maven" or "gradle".'
description: 'Name of the build platform to cache dependencies. It can be "maven", "gradle" or "sbt".'
required: false
job-status:
description: 'Workaround to pass job status to post job step. This variable is not intended for manual setting'
default: ${{ job.status }}
token:
description: The token used to authenticate when fetching version manifests hosted on github.com, such as for the Microsoft Build of OpenJDK. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting.
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'
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'
required: false
outputs:
distribution:
description: 'Distribution of Java that has been installed'
@ -66,7 +75,9 @@ outputs:
description: 'Actual version of the java environment that has been installed'
path:
description: 'Path to where the java environment has been installed (same as $JAVA_HOME)'
cache-hit:
description: 'A boolean value to indicate an exact match was found for the primary key'
runs:
using: 'node12'
using: 'node16'
main: 'dist/setup/index.js'
post: 'dist/cleanup/index.js'

65405
dist/cleanup/index.js vendored

File diff suppressed because one or more lines are too long

184574
dist/setup/index.js vendored

File diff suppressed because one or more lines are too long

View File

@ -3,6 +3,10 @@
- [Eclipse Temurin](#Eclipse-Temurin)
- [Adopt](#Adopt)
- [Zulu](#Zulu)
- [Liberica](#Liberica)
- [Microsoft](#Microsoft)
- [Amazon Corretto](#Amazon-Corretto)
- [Oracle](#Oracle)
- [Installing custom Java package type](#Installing-custom-Java-package-type)
- [Installing custom Java architecture](#Installing-custom-Java-architecture)
- [Installing custom Java distribution from local file](#Installing-Java-from-local-file)
@ -11,6 +15,8 @@
- [Publishing using Apache Maven](#Publishing-using-Apache-Maven)
- [Publishing using Gradle](#Publishing-using-Gradle)
- [Hosted Tool Cache](#Hosted-Tool-Cache)
- [Modifying Maven Toolchains](#Modifying-Maven-Toolchains)
- [Java-version file](#Java-version-file)
See [action.yml](../action.yml) for more details on task inputs.
@ -20,8 +26,8 @@ Inputs `java-version` and `distribution` are mandatory and needs to be provided.
### Eclipse Temurin
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
@ -33,8 +39,8 @@ steps:
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'adopt-hotspot'
java-version: '11'
@ -44,8 +50,8 @@ steps:
### Zulu
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'zulu'
java-version: '11'
@ -56,8 +62,8 @@ steps:
### Liberica
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'liberica'
java-version: '11'
@ -68,19 +74,61 @@ steps:
### Microsoft
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'microsoft'
java-version: '11'
- run: java -cp java HelloWorldApp
```
### Using Microsoft distribution on GHES
`setup-java` comes pre-installed on the appliance with GHES if Actions is enabled. When dynamically downloading the Microsoft Build of OpenJDK distribution, `setup-java` makes a request to `actions/setup-java` to get available versions on github.com (outside of the appliance). These calls to `actions/setup-java` are made via unauthenticated requests, which are limited to [60 requests per hour per IP](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). If more requests are made within the time frame, then you will start to see rate-limit errors during downloading that looks like: `##[error]API rate limit exceeded for...`.
To get a higher rate limit, you can [generate a personal access token on github.com](https://github.com/settings/tokens/new) and pass it as the `token` input for the action:
```yaml
uses: actions/setup-java@v3
with:
token: ${{ secrets.GH_DOTCOM_TOKEN }}
distribution: 'microsoft'
java-version: '11'
```
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.
### Amazon Corretto
**NOTE:** Amazon Corretto only supports the major version specification.
```yaml
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'corretto'
java-version: '11'
- run: java -cp java HelloWorldApp
```
### Oracle
**NOTE:** Oracle Java SE Development Kit is only available for version 17 and later.
```yaml
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'oracle'
java-version: '17'
- run: java -cp java HelloWorldApp
```
## Installing custom Java package type
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: '11'
@ -93,12 +141,12 @@ steps:
```yaml
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v2
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: '11'
architecture: x86 # optional - defaults to x64
architecture: x86 # optional - default value derived from the runner machine
- run: java -cp java HelloWorldApp
```
@ -110,7 +158,7 @@ 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"
wget -O $RUNNER_TEMP/java_package.tar.gz $download_url
- uses: actions/setup-java@v2
- uses: actions/setup-java@v3
with:
distribution: 'jdkfile'
jdkFile: ${{ runner.temp }}/java_package.tar.gz
@ -120,6 +168,31 @@ steps:
- run: java -cp java HelloWorldApp
```
If your use-case requires a custom distribution (in the example, alpine-linux is used) or a version that is not provided by setup-java and you want to always install the latest version during runtime, then you can use the following code to auto-download the latest JDK, determine the semver needed for setup-java, and setup-java will take care of the installation and caching on the VM:
```yaml
steps:
- name: fetch latest temurin JDK
id: fetch_latest_jdk
run: |
major_version={{ env.JAVA_VERSION }} # Example 8 or 11 or 17
cd $RUNNER_TEMP
response=$(curl -s "https://api.github.com/repos/adoptium/temurin${major_version}-binaries/releases")
latest_jdk_download_url=$(echo "$response" | jq -r '.[0].assets[] | select(.name | contains("jdk_x64_alpine-linux") and endswith(".tar.gz")) | .browser_download_url')
curl -Ls "$latest_jdk_download_url" -o java_package.tar.gz
latest_jdk_json_url=$(jdk_download_url "$response" | jq -r '.[0].assets[] | select(.name | contains("jdk_x64_alpine-linux") and endswith(".tar.gz.json")) | .browser_download_url')
latest_semver_version=$(curl -sL $latest_jdk_json_url | jq -r 'version.semver')
echo "java_version=$latest_semver_version" >> "$GITHUB_OUTPUT"
- uses: actions/setup-java@v3
with:
distribution: 'jdkfile'
jdkFile: ${{ runner.temp }}/java_package.tar.gz
java-version: {{ steps.fetch_latest_jdk.outputs.java_version }}
architecture: x64
- run: java -cp java HelloWorldApp
```
## Testing against different Java distributions
**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.
```yaml
@ -132,9 +205,9 @@ jobs:
java: [ '8', '11' ]
name: Java ${{ matrix.Java }} (${{ matrix.distribution }}) sample
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Setup java
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with:
distribution: ${{ matrix.distribution }}
java-version: ${{ matrix.java }}
@ -152,9 +225,9 @@ jobs:
os: [ 'ubuntu-latest', 'macos-latest', 'windows-latest' ]
name: Java ${{ matrix.Java }} (${{ matrix.os }}) sample
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Setup java
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
@ -169,9 +242,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up JDK 11
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: '11'
@ -185,7 +258,7 @@ jobs:
GITHUB_TOKEN: ${{ github.token }} # GITHUB_TOKEN is the default env for the password
- name: Set up Apache Maven Central
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with: # running setup-java again overwrites the settings.xml
distribution: 'temurin'
java-version: '11'
@ -280,9 +353,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up JDK 11 for Shared Runner
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: '11'
@ -306,10 +379,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up JDK 11
uses: actions/setup-java@v2
uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: '11'
@ -331,6 +404,115 @@ 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 Adopt OpenJDK (`adopt`) are cached on the GitHub Hosted Runners.
Currently, LTS versions of Eclipse Temurin (`temurin`) are cached on the GitHub Hosted Runners.
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).
## 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.
### Installing Multiple JDKs With Toolchains
Subsequent calls to `setup-java` with distinct distribution and version parameters will continue to extend the toolchains declaration and make all specified Java versions available.
```yaml
steps:
- uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: |
8
11
- uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: 15
```
The result is a Toolchain with entries for JDKs 8, 11 and 15. You can even combine this with custom JDKs of arbitrary versions:
```yaml
- run: |
download_url="https://example.com/java/jdk/6u45-b06/jdk-6u45-linux-x64.tar.gz"
wget -O $RUNNER_TEMP/java_package.tar.gz $download_url
- uses: actions/setup-java@v3
with:
distribution: 'jdkfile'
jdkFile: ${{ runner.temp }}/java_package.tar.gz
java-version: '1.6'
architecture: x64
```
This will generate a Toolchains entry with the following values: `version: 1.6`, `vendor: jkdfile`, `id: Oracle_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.
```yaml
- run: |
download_url="https://example.com/java/jdk/6u45-b06/jdk-6u45-linux-x64.tar.gz"
wget -O $RUNNER_TEMP/java_package.tar.gz $download_url
- uses: actions/setup-java@v3
with:
distribution: 'jdkfile'
jdkFile: ${{ runner.temp }}/java_package.tar.gz
java-version: '1.6'
architecture: x64
mvn-toolchain-vendor: 'Oracle'
```
This will generate a Toolchains entry with the following values: `version: 1.6`, `vendor: Oracle`, `id: Oracle_1.6`.
In case you install multiple versions of Java at once with multi-line `java-version` input setting the `mvn-toolchain-vendor` still only accepts one value and will use this value for installed JDKs as expected when installing multiple versions of the same `distribution`.
```yaml
steps:
- uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: |
8
11
mvn-toolchain-vendor: Eclipse Temurin
```
### 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.
```yaml
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
mvn-toolchain-id: 'some_other_id'
- run: java -cp java HelloWorldApp
```
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.
```yaml
steps:
- uses: actions/setup-java@v3
with:
distribution: '<distribution>'
java-version: |
8
11
mvn-toolchain-id: |
something_else
something_other
```
## Java-version file
If the `java-version-file` input is specified, the action will try to extract the version from the file and install it.
Action is able to recognize all variants of the version description according to [jenv](https://github.com/jenv/jenv).
Valid entry options:
```
major versions: 8, 11, 16, 17
more specific versions: 1.8.0.2, 17.0, 11.0, 11.0.4, 8.0.232, 8.0.282+8
early access (EA) versions: 15-ea, 15.0.0-ea, 15.0.0-ea.2, 15.0.0+2-ea
versions with specified distribution: openjdk64-11.0.2
```
If the file contains multiple versions, only the first one will be recognized.

114
docs/contributors.md Normal file
View File

@ -0,0 +1,114 @@
# Contributors
Thank you for contributing!
We have prepared a short guide so that the process of making your contribution is as simple and clear as possible. Please check it out before you contribute!
## How can I contribute...
* [Contribute Documentation:green_book:](#contribute-documentation)
* [Contribute Code :computer:](#contribute-code)
* [Provide Support on Issues:pencil:](#provide-support-on-issues)
* [Review Pull Requests:mag:](#review-pull-requests)
## Contribute documentation
Documentation is a super important, critical part of this project. Docs are how we keep track of what we're doing, how, and why. It's how we stay on the same page about our policies and how we tell others everything they need to be able to use this project or contribute to it.
Documentation contributions of any size are welcome! Feel free to contribute even if you're just rewording a sentence to be more clear, or fixing a spelling mistake!
**How to contribute:**
Pull requests are the easiest way to contribute changes to git repos at GitHub. They are the preferred contribution method, as they offer a convenient way of commenting and amending the proposed changes.
- Please check that no one else has already created a pull request with these or similar changes
- Use a "feature branch" for your changes. That separates the changes in the pull request from your other changes and makes it easy to edit/amend commits in the pull request
- Make sure your changes are formatted properly and consistently with the rest of the documentation
- Re-read what you wrote, and run a spellchecker on it to make sure you didn't miss anything
- If your pull request is connected to an open issue, please, leave a link to this issue in the `Related issue:` section
- If you later need to add new commits to the pull request, you can simply commit the changes to the local branch and then push them. The pull request gets automatically updated
**Once you've filed the pull request:**
- Maintainers will review your pull request
- If a maintainer requests changes, first of all, try to think about this request critically and only after that implement and request another review
- If your PR gets accepted, it will soon be merged into the main branch. But your contribution will take effect only after the release of a new version of the action and updating the major tag
> Sometimes maintainers reject pull requests and that's ok! Usually, along with rejection, we supply the reason for it. Nonetheless, we still really appreciate you taking the time to do it, and we don't take that lightly :heart:
## Contribute code
We like code commits a lot! They're super handy, and they keep the project going and doing the work it needs to do to be useful to others.
Code contributions of just about any size are acceptable!
The main difference between code contributions and documentation contributions is that contributing code requires the inclusion of relevant tests for the code being added or changed. Contributions without accompanying tests will be held off until a test is added unless the maintainers consider the specific tests to be either impossible or way too much of a burden for such a contribution.
**How to contribute:**
Pull requests are the easiest way to contribute changes to git repos at GitHub. They are the preferred contribution method, as they offer a convenient way of commenting and amending the proposed changes.
- Please check that no one else has already created a pull request with these or similar changes
- Use a "feature branch" for your changes. That separates the changes in the pull request from your other changes and makes it easy to edit/amend commits in the pull request
- Make sure your changes are well formatted and that all tests are passing
- If your pull request is connected to an open issue, please, leave a link to this issue in the `Related issue:` section
- If you later need to add new commits to the pull request, you can simply commit the changes to the local branch and then push them. The pull request gets automatically updated
**Learn more about how to work with the repository:**
- To implement new features or fix bugs, you need to make changes to the `.ts` files, which are located in the `src` folder
- To comply with the code style, **you need to run the `format` script**
- To lint the code, **you need to run the `lint:fix` script**
- To transpile source code to `javascript` we use [NCC](https://github.com/vercel/ncc). **It is very important to run the `build` script after making changes**, otherwise your changes will not get into the final `javascript` build
**Learn more about how to implement tests:**
Adding or changing tests is an integral part of making a change to the code.
Unit tests are in the `__tests__` folder, and end-to-end tests are in the `workflows` folder, particularly take a look at the files with `e2e` prefix, for instance, [e2e-cache.yml](https://github.com/actions/setup-java/blob/main/.github/workflows/e2e-cache.yml).
- The contributor can add various types of tests (like unit tests or end-to-end tests), which, in his opinion, will be necessary and sufficient for testing new or changed functionality
- Tests should cover a successful execution, as well as some edge cases and possible errors
- As already mentioned, pull requests without tests will be considered more carefully by maintainers. If you are sure that in this situation the tests are not needed or cannot be implemented with a commensurate effort - please add this clarification message to your pull request
**Once you've filed the pull request:**
- CI will start automatically with some checks. Wait until the end of the execution and make sure that all checks passed successfully. If some checks fail, you can open them one by one, try to find the reason for failing and make changes to your code to resolve the problem
- Maintainers will review your pull request
- If a maintainer requests changes, first of all, try to think about his request critically and only after that implement and request another review
- If your PR gets accepted, it will soon be merged into the main branch. But your contribution will take effect only after the release of a new version of the action and updating the major tag
> Sometimes maintainers reject pull requests and that's ok! Usually, along with rejection, we supply the reason for it. Nonetheless, we still really appreciate you taking the time to do it, and we don't take that lightly :heart:
## Provide support on issues
Helping out other users with their questions is an awesome way of contributing to any community. It's not uncommon for most of the issues on open source projects to be support-related questions by users trying to understand something they ran into or find their way around a known bug.
**To help other folks out with their questions:**
- Go to the [issue tracker](https://github.com/actions/setup-java/issues)
- Read through the list until you find something that you're familiar enough with to answer to
- Respond to the issue with whatever details are needed to clarify the question, or get more details about what's going on
- Once the discussion wraps up and things are clarified, ask the original issue filer (or a maintainer) to close it for you
*Some notes on picking up support issues:*
- Avoid responding to issues you don't know you can answer accurately
- Try to refer to past issues with accepted answers as much as possible. Link to them from your replies
- Be kind and patient with users. Often, folks who have run into confusing things might be upset or impatient. This is natural. If you feel uncomfortable in conversation with them, it's better to stay away or withdraw from the issue.
> If some user is violating our code of conduct [standards](https://github.com/actions/setup-java/blob/main/CODE_OF_CONDUCT.md#our-standards), refer to the [enforcement](https://github.com/actions/setup-java/blob/main/CODE_OF_CONDUCT.md#enforcement) section of the Code of Conduct to resolve the conflict
## Review pull requests
Another great way to contribute is is to review pull request. Please, be extra kind: people who submit code/doc contributions are putting themselves in a pretty vulnerable position, and have put time and care into what they've done (even if that's not obvious to you!) Please, always respond with respect, and be understanding, but don't feel like you need to sacrifice your standards for their sake, either.
**How to review:**
- Go to the [pull requests](https://github.com/actions/setup-java/pulls)
- Make sure you're familiar with the code or documentation is updated, unless it's a minor change (spellchecking, minor formatting, etc.)
- Review changes using the GitHub functionality. You can ask a clarifying question, point out an error or suggest an alternative.
> Note: You may ask for minor changes - "nitpicks", but consider whether they are real blockers to merging or not
- Submit your review, which may include comments, an approval, or a changes request

8673
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,15 @@
{
"name": "setup-java",
"version": "2.0.0",
"version": "3.4.1",
"private": true,
"description": "setup java action",
"main": "dist/setup/index.js",
"scripts": {
"build": "ncc build -o dist/setup src/setup-java.ts && ncc build -o dist/cleanup src/cleanup-java.ts",
"format": "prettier --write \"{,!(node_modules)/**/}*.ts\"",
"format-check": "prettier --check \"{,!(node_modules)/**/}*.ts\"",
"format": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --write \"**/*.{ts,yml,yaml}\"",
"format-check": "prettier --no-error-on-unmatched-pattern --config ./.prettierrc.js --check \"**/*.{ts,yml,yaml}\"",
"lint": "eslint --config ./.eslintrc.js \"**/*.ts\"",
"lint:fix": "eslint --config ./.eslintrc.js \"**/*.ts\" --fix",
"prerelease": "npm run-script build",
"release": "git add -f dist/setup/index.js dist/cleanup/index.js",
"test": "jest"
@ -24,8 +26,8 @@
"author": "GitHub",
"license": "MIT",
"dependencies": {
"@actions/cache": "^1.0.8",
"@actions/core": "^1.2.6",
"@actions/cache": "^3.0.4",
"@actions/core": "^1.10.0",
"@actions/exec": "^1.0.4",
"@actions/glob": "^0.2.0",
"@actions/http-client": "^1.0.11",
@ -36,12 +38,18 @@
},
"devDependencies": {
"@types/jest": "^27.0.2",
"@types/node": "^12.19.13",
"@types/node": "^16.11.25",
"@types/semver": "^7.3.4",
"@zeit/ncc": "^0.20.5",
"@typescript-eslint/eslint-plugin": "^5.54.0",
"@typescript-eslint/parser": "^5.54.0",
"@vercel/ncc": "^0.33.4",
"eslint": "^8.35.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-jest": "^27.2.1",
"eslint-plugin-node": "^11.1.0",
"jest": "^27.2.5",
"jest-circus": "^27.2.5",
"prettier": "^1.19.1",
"prettier": "^2.8.4",
"ts-jest": "^27.0.5",
"typescript": "^4.2.3"
}

View File

@ -5,23 +5,25 @@ import * as io from '@actions/io';
import * as fs from 'fs';
import * as os from 'os';
import { create as xmlCreate } from 'xmlbuilder2';
import {create as xmlCreate} from 'xmlbuilder2';
import * as constants from './constants';
import * as gpg from './gpg';
import { getBooleanInput } from './util';
export const M2_DIR = '.m2';
export const SETTINGS_FILE = 'settings.xml';
import {getBooleanInput} from './util';
export async function configureAuthentication() {
const id = core.getInput(constants.INPUT_SERVER_ID);
const username = core.getInput(constants.INPUT_SERVER_USERNAME);
const password = core.getInput(constants.INPUT_SERVER_PASSWORD);
const settingsDirectory =
core.getInput(constants.INPUT_SETTINGS_PATH) || path.join(os.homedir(), M2_DIR);
const overwriteSettings = getBooleanInput(constants.INPUT_OVERWRITE_SETTINGS, true);
core.getInput(constants.INPUT_SETTINGS_PATH) ||
path.join(os.homedir(), constants.M2_DIR);
const overwriteSettings = getBooleanInput(
constants.INPUT_OVERWRITE_SETTINGS,
true
);
const gpgPrivateKey =
core.getInput(constants.INPUT_GPG_PRIVATE_KEY) || constants.INPUT_DEFAULT_GPG_PRIVATE_KEY;
core.getInput(constants.INPUT_GPG_PRIVATE_KEY) ||
constants.INPUT_DEFAULT_GPG_PRIVATE_KEY;
const gpgPassphrase =
core.getInput(constants.INPUT_GPG_PASSPHRASE) ||
(gpgPrivateKey ? constants.INPUT_DEFAULT_GPG_PASSPHRASE : undefined);
@ -54,7 +56,7 @@ export async function createAuthenticationSettings(
overwriteSettings: boolean,
gpgPassphrase: string | undefined = undefined
) {
core.info(`Creating ${SETTINGS_FILE} with server-id: ${id}`);
core.info(`Creating ${constants.MVN_SETTINGS_FILE} 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 io.mkdirP(settingsDirectory);
@ -72,7 +74,7 @@ export function generate(
password: string,
gpgPassphrase?: string | undefined
) {
const xmlObj: { [key: string]: any } = {
const xmlObj: {[key: string]: any} = {
settings: {
'@xmlns': 'http://maven.apache.org/SETTINGS/1.0.0',
'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
@ -105,8 +107,12 @@ export function generate(
});
}
async function write(directory: string, settings: string, overwriteSettings: boolean) {
const location = path.join(directory, SETTINGS_FILE);
async function write(
directory: string,
settings: string,
overwriteSettings: boolean
) {
const location = path.join(directory, constants.MVN_SETTINGS_FILE);
const settingsExists = fs.existsSync(location);
if (settingsExists && overwriteSettings) {
core.info(`Overwriting existing file ${location}`);

View File

@ -2,7 +2,7 @@
* @fileoverview this file provides methods handling dependency cache
*/
import { join } from 'path';
import {join} from 'path';
import os from 'os';
import * as cache from '@actions/cache';
import * as core from '@actions/core';
@ -13,7 +13,7 @@ const CACHE_MATCHED_KEY = 'cache-matched-key';
const CACHE_KEY_PREFIX = 'setup-java';
interface PackageManager {
id: 'maven' | 'gradle';
id: 'maven' | 'gradle' | 'sbt';
/**
* Paths of the file that specify the files to cache.
*/
@ -29,14 +29,51 @@ const supportedPackageManager: PackageManager[] = [
},
{
id: 'gradle',
path: [join(os.homedir(), '.gradle', 'caches'), join(os.homedir(), '.gradle', 'wrapper')],
path: [
join(os.homedir(), '.gradle', 'caches'),
join(os.homedir(), '.gradle', 'wrapper')
],
// https://github.com/actions/cache/blob/0638051e9af2c23d10bb70fa9beffcad6cff9ce3/examples.md#java---gradle
pattern: ['**/*.gradle*', '**/gradle-wrapper.properties', '**/versions.properties']
pattern: [
'**/*.gradle*',
'**/gradle-wrapper.properties',
'buildSrc/**/Versions.kt',
'buildSrc/**/Dependencies.kt',
'gradle/*.versions.toml',
'**/versions.properties'
]
},
{
id: 'sbt',
path: [
join(os.homedir(), '.ivy2', 'cache'),
join(os.homedir(), '.sbt'),
getCoursierCachePath(),
// Some files should not be cached to avoid resolution problems.
// In particular the resolution of snapshots (ideological gap between maven/ivy).
'!' + join(os.homedir(), '.sbt', '*.lock'),
'!' + join(os.homedir(), '**', 'ivydata-*.properties')
],
pattern: [
'**/*.sbt',
'**/project/build.properties',
'**/project/**.scala',
'**/project/**.sbt'
]
}
];
function getCoursierCachePath(): string {
if (os.type() === 'Linux') return join(os.homedir(), '.cache', 'coursier');
if (os.type() === 'Darwin')
return join(os.homedir(), 'Library', 'Caches', 'Coursier');
return join(os.homedir(), 'AppData', 'Local', 'Coursier', 'Cache');
}
function findPackageManager(id: string): PackageManager {
const packageManager = supportedPackageManager.find(packageManager => packageManager.id === id);
const packageManager = supportedPackageManager.find(
packageManager => packageManager.id === id
);
if (packageManager === undefined) {
throw new Error(`unknown package manager specified: ${id}`);
}
@ -72,13 +109,14 @@ export async function restore(id: string) {
);
}
const matchedKey = await cache.restoreCache(packageManager.path, primaryKey, [
`${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${id}`
]);
// 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);
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`);
}
}
@ -91,7 +129,7 @@ export async function save(id: string) {
const packageManager = findPackageManager(id);
const matchedKey = core.getState(CACHE_MATCHED_KEY);
// Inputs are re-evaluted before the post action, so we want the original key used for restore
// 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);
if (!primaryKey) {
@ -99,7 +137,9 @@ export async function save(id: string) {
return;
} else if (matchedKey === primaryKey) {
// no change in target directories
core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`);
core.info(
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
);
return;
}
try {
@ -125,8 +165,14 @@ export async function save(id: string) {
* @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: PackageManager, error: Error) {
if (packageManager.id !== 'gradle' || process.env['RUNNER_OS'] !== 'Windows') {
function isProbablyGradleDaemonProblem(
packageManager: PackageManager,
error: Error
) {
if (
packageManager.id !== 'gradle' ||
process.env['RUNNER_OS'] !== 'Windows'
) {
return false;
}
const message = error.message || '';

View File

@ -1,14 +1,16 @@
import * as core from '@actions/core';
import * as gpg from './gpg';
import * as constants from './constants';
import { isJobStatusSuccess } from './util';
import { save } from './cache';
import {isJobStatusSuccess} from './util';
import {save} from './cache';
async function removePrivateKeyFromKeychain() {
if (core.getInput(constants.INPUT_GPG_PRIVATE_KEY, { required: false })) {
if (core.getInput(constants.INPUT_GPG_PRIVATE_KEY, {required: false})) {
core.info('Removing private key from keychain');
try {
const keyFingerprint = core.getState(constants.STATE_GPG_PRIVATE_KEY_FINGERPRINT);
const keyFingerprint = core.getState(
constants.STATE_GPG_PRIVATE_KEY_FINGERPRINT
);
await gpg.deleteKey(keyFingerprint);
} catch (error) {
core.setFailed(`Failed to remove private key due to: ${error.message}`);

View File

@ -1,5 +1,6 @@
export const MACOS_JAVA_CONTENT_POSTFIX = 'Contents/Home';
export const INPUT_JAVA_VERSION = 'java-version';
export const INPUT_JAVA_VERSION_FILE = 'java-version-file';
export const INPUT_ARCHITECTURE = 'architecture';
export const INPUT_JAVA_PACKAGE = 'java-package';
export const INPUT_DISTRIBUTION = 'distribution';
@ -20,3 +21,11 @@ export const INPUT_CACHE = 'cache';
export const INPUT_JOB_STATUS = 'job-status';
export const STATE_GPG_PRIVATE_KEY_FINGERPRINT = 'gpg-private-key-fingerprint';
export const M2_DIR = '.m2';
export const MVN_SETTINGS_FILE = 'settings.xml';
export const MVN_TOOLCHAINS_FILE = 'toolchains.xml';
export const INPUT_MVN_TOOLCHAIN_ID = 'mvn-toolchain-id';
export const INPUT_MVN_TOOLCHAIN_VENDOR = 'mvn-toolchain-vendor';
export const DISTRIBUTIONS_ONLY_MAJOR_VERSION = ['corretto'];

View File

@ -5,10 +5,18 @@ import fs from 'fs';
import path from 'path';
import semver from 'semver';
import { JavaBase } from '../base-installer';
import { IAdoptAvailableVersions } from './models';
import { JavaDownloadRelease, JavaInstallerOptions, JavaInstallerResults } from '../base-models';
import { extractJdkFile, getDownloadArchiveExtension, isVersionSatisfies } from '../../util';
import {JavaBase} from '../base-installer';
import {IAdoptAvailableVersions} from './models';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
import {
extractJdkFile,
getDownloadArchiveExtension,
isVersionSatisfies
} from '../../util';
export enum AdoptImplementation {
Hotspot = 'Hotspot',
@ -23,7 +31,9 @@ export class AdoptDistribution extends JavaBase {
super(`Adopt-${jvmImpl}`, installerOptions);
}
protected async findPackageForDownload(version: string): Promise<JavaDownloadRelease> {
protected async findPackageForDownload(
version: string
): Promise<JavaDownloadRelease> {
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersionsWithBinaries = availableVersionsRaw
.filter(item => item.binaries.length > 0)
@ -40,9 +50,12 @@ export class AdoptDistribution extends JavaBase {
return -semver.compareBuild(a.version, b.version);
});
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
const resolvedFullVersion =
satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableOptions = availableVersionsWithBinaries.map(item => item.version).join(', ');
const availableOptions = availableVersionsWithBinaries
.map(item => item.version)
.join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
@ -54,27 +67,31 @@ export class AdoptDistribution extends JavaBase {
return resolvedFullVersion;
}
protected async downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults> {
let javaPath: string;
let extractedJavaPath: string;
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
const javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
let extension = getDownloadArchiveExtension();
const extension = getDownloadArchiveExtension();
extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
javaPath = await tc.cacheDir(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
version,
this.architecture
);
return { version: javaRelease.version, path: javaPath };
return {version: javaRelease.version, path: javaPath};
}
protected get toolcacheFolderName(): string {
@ -88,12 +105,14 @@ export class AdoptDistribution extends JavaBase {
private async getAvailableVersions(): Promise<IAdoptAvailableVersions[]> {
const platform = this.getPlatformOption();
const arch = this.architecture;
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';
console.time('adopt-retrieve-available-versions');
if (core.isDebug()) {
console.time('Retrieving available versions for Adopt took'); // eslint-disable-line no-console
}
const baseRequestArguments = [
`project=jdk`,
@ -117,7 +136,9 @@ export class AdoptDistribution extends JavaBase {
const availableVersionsUrl = `https://api.adoptopenjdk.net/v3/assets/version/${versionRange}?${requestArguments}`;
if (core.isDebug() && page_index === 0) {
// url is identical except page_index so print it once for debug
core.debug(`Gathering available versions from '${availableVersionsUrl}'`);
core.debug(
`Gathering available versions from '${availableVersionsUrl}'`
);
}
const paginationPage = (
@ -134,9 +155,11 @@ export class AdoptDistribution extends JavaBase {
if (core.isDebug()) {
core.startGroup('Print information about available versions');
console.timeEnd('adopt-retrieve-available-versions');
console.log(`Available versions: [${availableVersions.length}]`);
console.log(availableVersions.map(item => item.version_data.semver).join(', '));
console.timeEnd('Retrieving available versions for Adopt took'); // eslint-disable-line no-console
core.debug(`Available versions: [${availableVersions.length}]`);
core.debug(
availableVersions.map(item => item.version_data.semver).join(', ')
);
core.endGroup();
}

View File

@ -4,9 +4,14 @@ import * as fs from 'fs';
import semver from 'semver';
import path from 'path';
import * as httpm from '@actions/http-client';
import { getToolcachePath, getVersionFromToolcachePath, isVersionSatisfies } from '../util';
import { JavaDownloadRelease, JavaInstallerOptions, JavaInstallerResults } from './base-models';
import { MACOS_JAVA_CONTENT_POSTFIX } from '../constants';
import {getToolcachePath, isVersionSatisfies} from '../util';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from './base-models';
import {MACOS_JAVA_CONTENT_POSTFIX} from '../constants';
import os from 'os';
export abstract class JavaBase {
protected http: httpm.HttpClient;
@ -16,22 +21,29 @@ export abstract class JavaBase {
protected stable: boolean;
protected checkLatest: boolean;
constructor(protected distribution: string, installerOptions: JavaInstallerOptions) {
constructor(
protected distribution: string,
installerOptions: JavaInstallerOptions
) {
this.http = new httpm.HttpClient('actions/setup-java', undefined, {
allowRetries: true,
maxRetries: 3
});
({ version: this.version, stable: this.stable } = this.normalizeVersion(
({version: this.version, stable: this.stable} = this.normalizeVersion(
installerOptions.version
));
this.architecture = installerOptions.architecture;
this.architecture = installerOptions.architecture || os.arch();
this.packageType = installerOptions.packageType;
this.checkLatest = installerOptions.checkLatest;
}
protected abstract downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults>;
protected abstract findPackageForDownload(range: string): Promise<JavaDownloadRelease>;
protected abstract downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults>;
protected abstract findPackageForDownload(
range: string
): Promise<JavaDownloadRelease>;
public async setupJava(): Promise<JavaInstallerResults> {
let foundJava = this.findInToolcache();
@ -51,7 +63,10 @@ export abstract class JavaBase {
}
// JDK folder may contain postfix "Contents/Home" on macOS
const macOSPostfixPath = path.join(foundJava.path, MACOS_JAVA_CONTENT_POSTFIX);
const macOSPostfixPath = path.join(
foundJava.path,
MACOS_JAVA_CONTENT_POSTFIX
);
if (process.platform === 'darwin' && fs.existsSync(macOSPostfixPath)) {
foundJava.path = macOSPostfixPath;
}
@ -95,7 +110,12 @@ export abstract class JavaBase {
// 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: getToolcachePath(this.toolcacheFolderName, item, this.architecture) || '',
path:
getToolcachePath(
this.toolcacheFolderName,
item,
this.architecture
) || '',
stable: !item.includes('-ea')
};
})
@ -142,10 +162,35 @@ export abstract class JavaBase {
}
protected setJavaDefault(version: string, toolPath: string) {
const majorVersion = version.split('.')[0];
core.exportVariable('JAVA_HOME', toolPath);
core.addPath(path.join(toolPath, 'bin'));
core.setOutput('distribution', this.distribution);
core.setOutput('path', toolPath);
core.setOutput('version', version);
core.exportVariable(
`JAVA_HOME_${majorVersion}_${this.architecture.toUpperCase()}`,
toolPath
);
}
protected distributionArchitecture(): string {
// default mappings of config architectures to distribution architectures
// override if a distribution uses any different names; see liberica for an example
// node's os.arch() - which this defaults to - can return any of:
// 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x', and 'x64'
// so we need to map these to java distribution architectures
// 'amd64' is included here too b/c it's a common alias for 'x64' people might use explicitly
switch (this.architecture) {
case 'amd64':
return 'x64';
case 'ia32':
return 'x86';
case 'arm64':
return 'aarch64';
default:
return this.architecture;
}
}
}

View File

@ -0,0 +1,186 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
import {
extractJdkFile,
getDownloadArchiveExtension,
convertVersionToSemver
} from '../../util';
import {JavaBase} from '../base-installer';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
import {
ICorrettoAllAvailableVersions,
ICorrettoAvailableVersions
} from './models';
export class CorrettoDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('Corretto', installerOptions);
}
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
const javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
const extractedJavaPath = await extractJdkFile(
javaArchivePath,
getDownloadArchiveExtension()
);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
version,
this.architecture
);
return {version: javaRelease.version, path: javaPath};
}
protected async findPackageForDownload(
version: string
): Promise<JavaDownloadRelease> {
if (!this.stable) {
throw new Error('Early access versions are not supported');
}
if (version.includes('.')) {
throw new Error('Only major versions are supported');
}
const availableVersions = await this.getAvailableVersions();
const matchingVersions = availableVersions
.filter(item => item.version == version)
.map(item => {
return {
version: convertVersionToSemver(item.correttoVersion),
url: item.downloadLink
} as JavaDownloadRelease;
});
const resolvedVersion =
matchingVersions.length > 0 ? matchingVersions[0] : null;
if (!resolvedVersion) {
const availableOptions = availableVersions
.map(item => item.version)
.join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
throw new Error(
`Could not find satisfied version for SemVer '${version}'. ${availableOptionsMessage}`
);
}
return resolvedVersion;
}
private async getAvailableVersions(): Promise<ICorrettoAvailableVersions[]> {
const platform = this.getPlatformOption();
const arch = this.distributionArchitecture();
const imageType = this.packageType;
if (core.isDebug()) {
console.time('Retrieving available versions for Coretto took'); // eslint-disable-line no-console
}
const availableVersionsUrl =
'https://corretto.github.io/corretto-downloads/latest_links/indexmap_with_checksum.json';
const fetchCurrentVersions =
await this.http.getJson<ICorrettoAllAvailableVersions>(
availableVersionsUrl
);
const fetchedCurrentVersions = fetchCurrentVersions.result;
if (!fetchedCurrentVersions) {
throw Error(
`Could not fetch latest corretto versions from ${availableVersionsUrl}`
);
}
const eligibleVersions =
fetchedCurrentVersions?.[platform]?.[arch]?.[imageType];
const availableVersions =
this.getAvailableVersionsForPlatform(eligibleVersions);
if (core.isDebug()) {
core.startGroup('Print information about available versions');
console.timeEnd('Retrieving available versions for Coretto took'); // eslint-disable-line no-console
core.debug(`Available versions: [${availableVersions.length}]`);
core.debug(
availableVersions
.map(item => `${item.version}: ${item.correttoVersion}`)
.join(', ')
);
core.endGroup();
}
return availableVersions;
}
private getAvailableVersionsForPlatform(
eligibleVersions:
| ICorrettoAllAvailableVersions['os']['arch']['imageType']
| undefined
): ICorrettoAvailableVersions[] {
const availableVersions: ICorrettoAvailableVersions[] = [];
for (const version in eligibleVersions) {
const availableVersion = eligibleVersions[version];
for (const fileType in availableVersion) {
const skipNonExtractableBinaries =
fileType != getDownloadArchiveExtension();
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;
}
private getPlatformOption(): string {
// Corretto has its own platform names so we need to map them
switch (process.platform) {
case 'darwin':
return 'macos';
case 'win32':
return 'windows';
default:
return process.platform;
}
}
private getCorrettoVersion(resource: string): string {
const regex = /(\d+.+)\//;
const match = regex.exec(resource);
if (match === null) {
throw Error(`Could not parse corretto version from ${resource}`);
}
return match[1];
}
}

View File

@ -0,0 +1,25 @@
export interface ICorrettoAllAvailableVersions {
[os: string]: {
[arch: string]: {
[distributionType: string]: {
[version: string]: {
[fileType: string]: {
checksum: string;
checksum_sha256: string;
resource: string;
};
};
};
};
};
}
export interface ICorrettoAvailableVersions {
version: string;
fileType: string;
checksum: string;
checksum_sha256: string;
resource: string;
downloadLink: string;
correttoVersion: string;
}

View File

@ -1,11 +1,14 @@
import { JavaBase } from './base-installer';
import { JavaInstallerOptions } from './base-models';
import { LocalDistribution } from './local/installer';
import { ZuluDistribution } from './zulu/installer';
import { AdoptDistribution, AdoptImplementation } from './adopt/installer';
import { TemurinDistribution, TemurinImplementation } from './temurin/installer';
import { LibericaDistributions } from './liberica/installer';
import { MicrosoftDistributions } from './microsoft/installer';
import {JavaBase} from './base-installer';
import {JavaInstallerOptions} from './base-models';
import {LocalDistribution} from './local/installer';
import {ZuluDistribution} from './zulu/installer';
import {AdoptDistribution, AdoptImplementation} from './adopt/installer';
import {TemurinDistribution, TemurinImplementation} from './temurin/installer';
import {LibericaDistributions} from './liberica/installer';
import {MicrosoftDistributions} from './microsoft/installer';
import {SemeruDistribution} from './semeru/installer';
import {CorrettoDistribution} from './corretto/installer';
import {OracleDistribution} from './oracle/installer';
enum JavaDistribution {
Adopt = 'adopt',
@ -15,7 +18,10 @@ enum JavaDistribution {
Zulu = 'zulu',
Liberica = 'liberica',
JdkFile = 'jdkfile',
Microsoft = 'microsoft'
Microsoft = 'microsoft',
Semeru = 'semeru',
Corretto = 'corretto',
Oracle = 'oracle'
}
export function getJavaDistribution(
@ -28,17 +34,32 @@ export function getJavaDistribution(
return new LocalDistribution(installerOptions, jdkFile);
case JavaDistribution.Adopt:
case JavaDistribution.AdoptHotspot:
return new AdoptDistribution(installerOptions, AdoptImplementation.Hotspot);
return new AdoptDistribution(
installerOptions,
AdoptImplementation.Hotspot
);
case JavaDistribution.AdoptOpenJ9:
return new AdoptDistribution(installerOptions, AdoptImplementation.OpenJ9);
return new AdoptDistribution(
installerOptions,
AdoptImplementation.OpenJ9
);
case JavaDistribution.Temurin:
return new TemurinDistribution(installerOptions, TemurinImplementation.Hotspot);
return new TemurinDistribution(
installerOptions,
TemurinImplementation.Hotspot
);
case JavaDistribution.Zulu:
return new ZuluDistribution(installerOptions);
case JavaDistribution.Liberica:
return new LibericaDistributions(installerOptions);
case JavaDistribution.Microsoft:
return new MicrosoftDistributions(installerOptions);
case JavaDistribution.Semeru:
return new SemeruDistribution(installerOptions);
case JavaDistribution.Corretto:
return new CorrettoDistribution(installerOptions);
case JavaDistribution.Oracle:
return new OracleDistribution(installerOptions);
default:
return null;
}

View File

@ -1,23 +1,33 @@
import { JavaBase } from '../base-installer';
import { JavaDownloadRelease, JavaInstallerOptions, JavaInstallerResults } from '../base-models';
import {JavaBase} from '../base-installer';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
import semver from 'semver';
import { extractJdkFile, getDownloadArchiveExtension, isVersionSatisfies } from '../../util';
import {
extractJdkFile,
getDownloadArchiveExtension,
isVersionSatisfies
} from '../../util';
import * as core from '@actions/core';
import { ArchitectureOptions, LibericaVersion, OsVersions } from './models';
import {ArchitectureOptions, LibericaVersion, OsVersions} from './models';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
const supportedPlatform = `'linux', 'linux-musl', 'macos', 'solaris', 'windows'`;
const supportedArchitecture = `'x86', 'x64', 'armv7', 'aarch64', 'ppc64le'`;
const supportedArchitectures = `'x86', 'x64', 'armv7', 'aarch64', 'ppc64le'`;
export class LibericaDistributions extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('Liberica', installerOptions);
}
protected async downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults> {
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
@ -37,10 +47,12 @@ export class LibericaDistributions extends JavaBase {
this.architecture
);
return { version: javaRelease.version, path: javaPath };
return {version: javaRelease.version, path: javaPath};
}
protected async findPackageForDownload(range: string): Promise<JavaDownloadRelease> {
protected async findPackageForDownload(
range: string
): Promise<JavaDownloadRelease> {
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersions = availableVersionsRaw.map(item => ({
@ -53,7 +65,9 @@ export class LibericaDistributions extends JavaBase {
.sort((a, b) => -semver.compareBuild(a.version, b.version))[0];
if (!satisfiedVersion) {
const availableOptions = availableVersions.map(item => item.version).join(', ');
const availableOptions = availableVersions
.map(item => item.version)
.join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
@ -66,20 +80,21 @@ export class LibericaDistributions extends JavaBase {
}
private async getAvailableVersions(): Promise<LibericaVersion[]> {
console.time('liberica-retrieve-available-versions');
if (core.isDebug()) {
console.time('Retrieving available versions for Liberica took'); // eslint-disable-line no-console
}
const url = this.prepareAvailableVersionsUrl();
if (core.isDebug()) {
core.debug(`Gathering available versions from '${url}'`);
}
core.debug(`Gathering available versions from '${url}'`);
const availableVersions = (await this.http.getJson<LibericaVersion[]>(url)).result ?? [];
const availableVersions =
(await this.http.getJson<LibericaVersion[]>(url)).result ?? [];
if (core.isDebug()) {
core.startGroup('Print information about available versions');
console.timeEnd('liberica-retrieve-available-versions');
console.log(`Available versions: [${availableVersions.length}]`);
console.log(availableVersions.map(item => item.version));
console.timeEnd('Retrieving available versions for Liberica took'); // eslint-disable-line no-console
core.debug(`Available versions: [${availableVersions.length}]`);
core.debug(availableVersions.map(item => item.version).join(', '));
core.endGroup();
}
@ -93,7 +108,8 @@ export class LibericaDistributions extends JavaBase {
...this.getArchitectureOptions(),
'build-type': this.stable ? 'all' : 'ea',
'installation-type': 'archive',
fields: 'downloadUrl,version,featureVersion,interimVersion,updateVersion,buildVersion'
fields:
'downloadUrl,version,featureVersion,interimVersion,updateVersion,buildVersion'
};
const searchParams = new URLSearchParams(urlOptions).toString();
@ -110,25 +126,28 @@ export class LibericaDistributions extends JavaBase {
}
private getArchitectureOptions(): ArchitectureOptions {
switch (this.architecture) {
const arch = this.distributionArchitecture();
switch (arch) {
case 'x86':
return { bitness: '32', arch: 'x86' };
return {bitness: '32', arch: 'x86'};
case 'x64':
return { bitness: '64', arch: 'x86' };
return {bitness: '64', arch: 'x86'};
case 'armv7':
return { bitness: '32', arch: 'arm' };
return {bitness: '32', arch: 'arm'};
case 'aarch64':
return { bitness: '64', arch: 'arm' };
return {bitness: '64', arch: 'arm'};
case 'ppc64le':
return { bitness: '64', arch: 'ppc' };
return {bitness: '64', arch: 'ppc'};
default:
throw new Error(
`Architecture '${this.architecture}' is not supported. Supported architectures: ${supportedArchitecture}`
`Architecture '${this.architecture}' is not supported. Supported architectures: ${supportedArchitectures}`
);
}
}
private getPlatformOption(platform: NodeJS.Platform = process.platform): OsVersions {
private getPlatformOption(
platform: NodeJS.Platform = process.platform
): OsVersions {
switch (platform) {
case 'darwin':
return 'macos';
@ -147,11 +166,24 @@ export class LibericaDistributions extends JavaBase {
}
private convertVersionToSemver(version: LibericaVersion): string {
let { buildVersion, featureVersion, interimVersion, updateVersion } = version;
const mainVersion = [featureVersion, interimVersion, updateVersion].join('.');
const {buildVersion, featureVersion, interimVersion, updateVersion} =
version;
const mainVersion = [featureVersion, interimVersion, updateVersion].join(
'.'
);
if (buildVersion != 0) {
return `${mainVersion}+${buildVersion}`;
}
return mainVersion;
}
protected distributionArchitecture(): string {
const arch = super.distributionArchitecture();
switch (arch) {
case 'arm':
return 'armv7';
default:
return arch;
}
}
}

View File

@ -3,7 +3,12 @@
export type Bitness = '32' | '64';
export type ArchType = 'arm' | 'ppc' | 'sparc' | 'x86';
export type OsVersions = 'linux' | 'linux-musl' | 'macos' | 'solaris' | 'windows';
export type OsVersions =
| 'linux'
| 'linux-musl'
| 'macos'
| 'solaris'
| 'windows';
export interface ArchitectureOptions {
bitness: Bitness;

View File

@ -3,15 +3,21 @@ import * as core from '@actions/core';
import fs from 'fs';
import path from 'path';
import semver from 'semver';
import { JavaBase } from '../base-installer';
import { JavaInstallerOptions, JavaDownloadRelease, JavaInstallerResults } from '../base-models';
import { extractJdkFile } from '../../util';
import { MACOS_JAVA_CONTENT_POSTFIX } from '../../constants';
import {JavaBase} from '../base-installer';
import {
JavaInstallerOptions,
JavaDownloadRelease,
JavaInstallerResults
} from '../base-models';
import {extractJdkFile} from '../../util';
import {MACOS_JAVA_CONTENT_POSTFIX} from '../../constants';
export class LocalDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions, private jdkFile?: string) {
constructor(
installerOptions: JavaInstallerOptions,
private jdkFile?: string
) {
super('jdkfile', installerOptions);
}
@ -21,7 +27,9 @@ export class LocalDistribution extends JavaBase {
if (foundJava) {
core.info(`Resolved Java ${foundJava.version} from tool-cache`);
} else {
core.info(`Java ${this.version} was not found in tool-cache. Trying to unpack JDK file...`);
core.info(
`Java ${this.version} was not found in tool-cache. Trying to unpack JDK file...`
);
if (!this.jdkFile) {
throw new Error("'jdkFile' is not specified");
}
@ -39,38 +47,47 @@ export class LocalDistribution extends JavaBase {
const archivePath = path.join(extractedJavaPath, archiveName);
const javaVersion = this.version;
let javaPath = await tc.cacheDir(
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaVersion),
this.architecture
);
// for different Java distributions, postfix can exist or not so need to check both cases
if (
process.platform === 'darwin' &&
fs.existsSync(path.join(javaPath, MACOS_JAVA_CONTENT_POSTFIX))
) {
javaPath = path.join(javaPath, MACOS_JAVA_CONTENT_POSTFIX);
}
foundJava = {
version: javaVersion,
path: javaPath
};
}
// JDK folder may contain postfix "Contents/Home" on macOS
const macOSPostfixPath = path.join(
foundJava.path,
MACOS_JAVA_CONTENT_POSTFIX
);
if (process.platform === 'darwin' && fs.existsSync(macOSPostfixPath)) {
foundJava.path = macOSPostfixPath;
}
core.info(`Setting Java ${foundJava.version} as default`);
this.setJavaDefault(foundJava.version, foundJava.path);
return foundJava;
}
protected async findPackageForDownload(version: string): Promise<JavaDownloadRelease> {
throw new Error('This method should not be implemented in local file provider');
protected async findPackageForDownload(
version: string // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<JavaDownloadRelease> {
throw new Error(
'This method should not be implemented in local file provider'
);
}
protected async downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults> {
throw new Error('This method should not be implemented in local file provider');
protected async downloadTool(
javaRelease: JavaDownloadRelease // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<JavaInstallerResults> {
throw new Error(
'This method should not be implemented in local file provider'
);
}
}

View File

@ -1,19 +1,25 @@
import { JavaBase } from '../base-installer';
import { JavaDownloadRelease, JavaInstallerOptions, JavaInstallerResults } from '../base-models';
import semver from 'semver';
import { extractJdkFile, getDownloadArchiveExtension, isVersionSatisfies } from '../../util';
import {JavaBase} from '../base-installer';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
import {extractJdkFile, getDownloadArchiveExtension} from '../../util';
import * as core from '@actions/core';
import { MicrosoftVersion, PlatformOptions } from './models';
import * as tc from '@actions/tool-cache';
import {OutgoingHttpHeaders} from 'http';
import fs from 'fs';
import path from 'path';
import {ITypedResponse} from '@actions/http-client/interfaces';
export class MicrosoftDistributions extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('Microsoft', installerOptions);
}
protected async downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults> {
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
@ -33,11 +39,14 @@ export class MicrosoftDistributions extends JavaBase {
this.architecture
);
return { version: javaRelease.version, path: javaPath };
return {version: javaRelease.version, path: javaPath};
}
protected async findPackageForDownload(range: string): Promise<JavaDownloadRelease> {
if (this.architecture !== 'x64' && this.architecture !== 'aarch64') {
protected async findPackageForDownload(
range: string
): Promise<JavaDownloadRelease> {
const arch = this.distributionArchitecture();
if (arch !== 'x64' && arch !== 'aarch64') {
throw new Error(`Unsupported architecture: ${this.architecture}`);
}
@ -46,79 +55,82 @@ export class MicrosoftDistributions extends JavaBase {
}
if (this.packageType !== 'jdk') {
throw new Error('Microsoft Build of OpenJDK provides only the `jdk` package type');
}
const availableVersionsRaw = await this.getAvailableVersions();
const opts = this.getPlatformOption();
const availableVersions = availableVersionsRaw.map(item => ({
url: `https://aka.ms/download-jdk/microsoft-jdk-${item.version.join('.')}-${opts.os}-${
this.architecture
}.${opts.archive}`,
version: this.convertVersionToSemver(item)
}));
const satisfiedVersion = availableVersions
.filter(item => isVersionSatisfies(range, item.version))
.sort((a, b) => -semver.compareBuild(a.version, b.version))[0];
if (!satisfiedVersion) {
const availableOptions = availableVersions.map(item => item.version).join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
throw new Error(
`Could not find satisfied version for SemVer ${range}. ${availableOptionsMessage}`
'Microsoft Build of OpenJDK provides only the `jdk` package type'
);
}
return satisfiedVersion;
const manifest = await this.getAvailableVersions();
if (!manifest) {
throw new Error('Could not load manifest for Microsoft Build of OpenJDK');
}
const foundRelease = await tc.findFromManifest(range, true, manifest, arch);
if (!foundRelease) {
throw new Error(
`Could not find satisfied version for SemVer ${range}.\nAvailable versions: ${manifest
.map(item => item.version)
.join(', ')}`
);
}
return {
url: foundRelease.files[0].download_url,
version: foundRelease.version
};
}
private async getAvailableVersions(): Promise<MicrosoftVersion[]> {
private async getAvailableVersions(): Promise<tc.IToolRelease[] | null> {
// TODO get these dynamically!
// We will need Microsoft to add an endpoint where we can query for versions.
const jdkVersions = [
{
version: [17, 0, 1, 12, 1]
},
{
version: [16, 0, 2, 7, 1]
const token = core.getInput('token');
const auth = !token ? undefined : `token ${token}`;
const owner = 'actions';
const repository = 'setup-java';
const branch = 'main';
const filePath =
'src/distributions/microsoft/microsoft-openjdk-versions.json';
let releases: tc.IToolRelease[] | null = null;
const fileUrl = `https://api.github.com/repos/${owner}/${repository}/contents/${filePath}?ref=${branch}`;
const headers: OutgoingHttpHeaders = {
authorization: auth,
accept: 'application/vnd.github.VERSION.raw'
};
let response: ITypedResponse<tc.IToolRelease[]> | null = null;
if (core.isDebug()) {
console.time('Retrieving available versions for Microsoft took'); // eslint-disable-line no-console
}
try {
response = await this.http.getJson<tc.IToolRelease[]>(fileUrl, headers);
if (!response.result) {
return null;
}
];
// M1 is only supported for Java 16 & 17
if (process.platform !== 'darwin' || this.architecture !== 'aarch64') {
jdkVersions.push({
version: [11, 0, 13, 8, 1]
});
} catch (err) {
core.debug(
`Http request for microsoft-openjdk-versions.json failed with status code: ${response?.statusCode}`
);
return null;
}
return jdkVersions;
}
private getPlatformOption(
platform: NodeJS.Platform = process.platform /* for testing */
): PlatformOptions {
switch (platform) {
case 'darwin':
return { archive: 'tar.gz', os: 'macos' };
case 'win32':
return { archive: 'zip', os: 'windows' };
case 'linux':
return { archive: 'tar.gz', os: 'linux' };
default:
throw new Error(
`Platform '${platform}' is not supported. Supported platforms: 'darwin', 'linux', 'win32'`
);
if (response.result) {
releases = response.result;
}
}
private convertVersionToSemver(version: MicrosoftVersion): string {
const major = version.version[0];
const minor = version.version[1];
const patch = version.version[2];
return `${major}.${minor}.${patch}`;
if (core.isDebug() && releases) {
core.startGroup('Print information about available versions');
console.timeEnd('Retrieving available versions for Microsoft took'); // eslint-disable-line no-console
core.debug(`Available versions: [${releases.length}]`);
core.debug(releases.map(item => item.version).join(', '));
core.endGroup();
}
return releases;
}
}

View File

@ -0,0 +1,477 @@
[
{
"version": "17.0.7",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.7-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.7-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.7-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.7-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.7-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.7-linux-aarch64.tar.gz"
}
]
},
{
"version": "17.0.6",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.6-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.6-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.6-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.6-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.6-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.6-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.6-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.6-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.6-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.6-linux-aarch64.tar.gz"
}
]
},
{
"version": "17.0.5",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.5-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.5-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.5-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.5-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.5-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.5-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.5-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.5-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.5-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.5-linux-aarch64.tar.gz"
}
]
},
{
"version": "17.0.4",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.4-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.4-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.4-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.4-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.4-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.4-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.4-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.4-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.4-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.4-linux-aarch64.tar.gz"
}
]
},
{
"version": "17.0.3",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.3-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.3-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.3-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.3-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.3-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.3-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.3-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.3-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.3-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.3-linux-aarch64.tar.gz"
}
]
},
{
"version": "17.0.1+12.1",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-17.0.1.12.1-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-windows-x64.zip"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-17.0.1.12.1-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-17.0.1.12.1-linux-aarch64.tar.gz"
}
]
},
{
"version": "16.0.2+7.1",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-16.0.2.7.1-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-windows-x64.zip"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-16.0.2.7.1-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-16.0.2.7.1-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.19",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.19-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.19-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.19-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.19-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.19-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.19-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.18",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.18-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.18-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.18-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.18-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.18-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.18-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.18-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.18-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.18-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.18-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.17",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.17-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.17-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.17-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.17-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.17-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.17-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.17-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.17-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.17-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.17-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.16",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.16-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.16-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.16-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.16-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.16-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.16-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.16-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.16-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.16-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.16-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.15",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.15-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.15-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.15-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.15-macos-aarch64.tar.gz",
"arch": "aarch64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-macos-aarch64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.15-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.15-linux-aarch64.tar.gz"
}
]
},
{
"version": "11.0.13+8.1",
"stable": true,
"release_url": "https://aka.ms/download-jdk",
"files": [
{
"filename": "microsoft-jdk-11.0.13.8.1-macos-x64.tar.gz",
"arch": "x64",
"platform": "darwin",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-macos-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.13.8.1-linux-x64.tar.gz",
"arch": "x64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-linux-x64.tar.gz"
},
{
"filename": "microsoft-jdk-11.0.13.8.1-windows-x64.zip",
"arch": "x64",
"platform": "win32",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-windows-x64.zip"
},
{
"filename": "microsoft-jdk-11.0.13.8.1-linux-aarch64.tar.gz",
"arch": "aarch64",
"platform": "linux",
"download_url": "https://aka.ms/download-jdk/microsoft-jdk-11.0.13.8.1-linux-aarch64.tar.gz"
}
]
}
]

View File

@ -1,12 +1,3 @@
/* eslint @typescript-eslint/no-unused-vars: "off" -- There is a bug with this rule, it's not working properly with types */
type OsVersions = 'linux' | 'macos' | 'windows';
type ArchiveType = 'tar.gz' | 'zip';
export interface PlatformOptions {
archive: ArchiveType;
os: OsVersions;
}
export interface MicrosoftVersion {
downloadUrl?: string;
version: Array<number>;
}

View File

@ -0,0 +1,126 @@
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
import {JavaBase} from '../base-installer';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
import {extractJdkFile, getDownloadArchiveExtension} from '../../util';
import {HttpCodes} from '@actions/http-client';
const ORACLE_DL_BASE = 'https://download.oracle.com/java';
export class OracleDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('Oracle', installerOptions);
}
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
const javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
const extension = getDownloadArchiveExtension();
const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
version,
this.architecture
);
return {version: javaRelease.version, path: javaPath};
}
protected async findPackageForDownload(
range: string
): Promise<JavaDownloadRelease> {
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 = getDownloadArchiveExtension();
const isOnlyMajorProvided = !range.includes('.');
const major = isOnlyMajorProvided ? range : range.split('.')[0];
const possibleUrls: string[] = [];
/**
* 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}`
);
}
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 === HttpCodes.OK) {
return {url, version: range};
}
if (response.message.statusCode !== HttpCodes.NotFound) {
throw new Error(
`Http request for Oracle JDK failed with status code: ${response.message.statusCode}`
);
}
}
throw new Error(`Could not find Oracle JDK for SemVer ${range}`);
}
public getPlatform(platform: NodeJS.Platform = process.platform): OsVersions {
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'`
);
}
}
}

View File

@ -0,0 +1 @@
export type OsVersions = 'linux' | 'macos' | 'windows';

View File

@ -0,0 +1,201 @@
import {JavaBase} from '../base-installer';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
import semver from 'semver';
import {
extractJdkFile,
getDownloadArchiveExtension,
isVersionSatisfies
} from '../../util';
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
import {ISemeruAvailableVersions} from './models';
const supportedArchitectures = [
'x64',
'x86',
'ppc64le',
'ppc64',
's390x',
'aarch64'
];
export class SemeruDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('IBM_Semeru', installerOptions);
}
protected async findPackageForDownload(
version: string
): Promise<JavaDownloadRelease> {
if (!supportedArchitectures.includes(this.architecture)) {
throw new Error(
`Unsupported architecture for IBM Semeru: ${
this.architecture
}, 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
} as JavaDownloadRelease;
});
const satisfiedVersions = availableVersionsWithBinaries
.filter(item => isVersionSatisfies(version, item.version))
.sort((a, b) => {
return -semver.compareBuild(a.version, b.version);
});
const resolvedFullVersion =
satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableOptions = availableVersionsWithBinaries
.map(item => item.version)
.join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
throw new Error(
`Could not find satisfied version for SemVer '${version}'. ${availableOptionsMessage}`
);
}
return resolvedFullVersion;
}
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
const javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
const extension = getDownloadArchiveExtension();
const extractedJavaPath: string = await extractJdkFile(
javaArchivePath,
extension
);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
const javaPath: string = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
version,
this.architecture
);
return {version: javaRelease.version, path: javaPath};
}
protected get toolcacheFolderName(): string {
return super.toolcacheFolderName;
}
public async getAvailableVersions(): Promise<ISemeruAvailableVersions[]> {
const platform = this.getPlatformOption();
const arch = this.architecture;
const imageType = this.packageType;
const versionRange = encodeURI('[1.0,100.0]'); // retrieve all available versions
const releaseType = this.stable ? 'ga' : 'ea';
if (core.isDebug()) {
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('&');
// need to iterate through all pages to retrieve the list of all versions
// Adoptium API doesn't provide way to retrieve the count of pages to iterate so infinity loop
let page_index = 0;
const availableVersions: ISemeruAvailableVersions[] = [];
while (true) {
const requestArguments = `${baseRequestArguments}&page_size=20&page=${page_index}`;
const availableVersionsUrl = `https://api.adoptopenjdk.net/v3/assets/version/${versionRange}?${requestArguments}`;
if (core.isDebug() && page_index === 0) {
// url is identical except page_index so print it once for debug
core.debug(
`Gathering available versions from '${availableVersionsUrl}'`
);
}
const paginationPage = (
await this.http.getJson<ISemeruAvailableVersions[]>(
availableVersionsUrl
)
).result;
if (paginationPage === null || paginationPage.length === 0) {
// break infinity loop because we have reached end of pagination
break;
}
availableVersions.push(...paginationPage);
page_index++;
}
if (core.isDebug()) {
core.startGroup('Print information about available versions');
console.timeEnd('Retrieving available versions for Semeru took'); // eslint-disable-line no-console
core.debug(`Available versions: [${availableVersions.length}]`);
core.debug(
availableVersions.map(item => item.version_data.semver).join(', ')
);
core.endGroup();
}
return availableVersions;
}
private getPlatformOption(): string {
// 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;
}
}
}

View File

@ -0,0 +1,36 @@
export interface ISemeruAvailableVersions {
binaries: [
{
architecture: string;
heap_size: string;
image_type: string;
jvm_impl: string;
os: string;
package: {
checksum: string;
checksum_link: string;
download_count: number;
link: string;
metadata_link: string;
name: string;
size: string;
};
project: string;
scm_ref: string;
updated_at: string;
}
];
id: string;
release_link: string;
release_name: string;
release_type: string;
vendor: string;
version_data: {
build: number;
major: number;
minor: number;
openjdk_version: string;
security: string;
semver: string;
};
}

View File

@ -5,10 +5,18 @@ import fs from 'fs';
import path from 'path';
import semver from 'semver';
import { JavaBase } from '../base-installer';
import { ITemurinAvailableVersions } from './models';
import { JavaDownloadRelease, JavaInstallerOptions, JavaInstallerResults } from '../base-models';
import { extractJdkFile, getDownloadArchiveExtension, isVersionSatisfies } from '../../util';
import {JavaBase} from '../base-installer';
import {ITemurinAvailableVersions} from './models';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
import {
extractJdkFile,
getDownloadArchiveExtension,
isVersionSatisfies
} from '../../util';
export enum TemurinImplementation {
Hotspot = 'Hotspot'
@ -22,7 +30,9 @@ export class TemurinDistribution extends JavaBase {
super(`Temurin-${jvmImpl}`, installerOptions);
}
protected async findPackageForDownload(version: string): Promise<JavaDownloadRelease> {
protected async findPackageForDownload(
version: string
): Promise<JavaDownloadRelease> {
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersionsWithBinaries = availableVersionsRaw
.filter(item => item.binaries.length > 0)
@ -43,9 +53,12 @@ export class TemurinDistribution extends JavaBase {
return -semver.compareBuild(a.version, b.version);
});
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
const resolvedFullVersion =
satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableOptions = availableVersionsWithBinaries.map(item => item.version).join(', ');
const availableOptions = availableVersionsWithBinaries
.map(item => item.version)
.join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
@ -57,27 +70,31 @@ export class TemurinDistribution extends JavaBase {
return resolvedFullVersion;
}
protected async downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults> {
let javaPath: string;
let extractedJavaPath: string;
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
const javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
let extension = getDownloadArchiveExtension();
const extension = getDownloadArchiveExtension();
extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const version = this.getToolcacheVersionName(javaRelease.version);
javaPath = await tc.cacheDir(archivePath, this.toolcacheFolderName, version, this.architecture);
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
version,
this.architecture
);
return { version: javaRelease.version, path: javaPath };
return {version: javaRelease.version, path: javaPath};
}
protected get toolcacheFolderName(): string {
@ -86,12 +103,14 @@ export class TemurinDistribution extends JavaBase {
private async getAvailableVersions(): Promise<ITemurinAvailableVersions[]> {
const platform = this.getPlatformOption();
const arch = this.architecture;
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';
console.time('temurin-retrieve-available-versions');
if (core.isDebug()) {
console.time('Retrieving available versions for Temurin took'); // eslint-disable-line no-console
}
const baseRequestArguments = [
`project=jdk`,
@ -115,11 +134,15 @@ export class TemurinDistribution extends JavaBase {
const availableVersionsUrl = `https://api.adoptium.net/v3/assets/version/${versionRange}?${requestArguments}`;
if (core.isDebug() && page_index === 0) {
// url is identical except page_index so print it once for debug
core.debug(`Gathering available versions from '${availableVersionsUrl}'`);
core.debug(
`Gathering available versions from '${availableVersionsUrl}'`
);
}
const paginationPage = (
await this.http.getJson<ITemurinAvailableVersions[]>(availableVersionsUrl)
await this.http.getJson<ITemurinAvailableVersions[]>(
availableVersionsUrl
)
).result;
if (paginationPage === null || paginationPage.length === 0) {
// break infinity loop because we have reached end of pagination
@ -132,9 +155,11 @@ export class TemurinDistribution extends JavaBase {
if (core.isDebug()) {
core.startGroup('Print information about available versions');
console.timeEnd('temurin-retrieve-available-versions');
console.log(`Available versions: [${availableVersions.length}]`);
console.log(availableVersions.map(item => item.version_data.semver).join(', '));
console.timeEnd('Retrieving available versions for Temurin took'); // eslint-disable-line no-console
core.debug(`Available versions: [${availableVersions.length}]`);
core.debug(
availableVersions.map(item => item.version_data.semver).join(', ')
);
core.endGroup();
}

View File

@ -5,23 +5,34 @@ import path from 'path';
import fs from 'fs';
import semver from 'semver';
import { JavaBase } from '../base-installer';
import { IZuluVersions } from './models';
import { extractJdkFile, getDownloadArchiveExtension, isVersionSatisfies } from '../../util';
import { JavaDownloadRelease, JavaInstallerOptions, JavaInstallerResults } from '../base-models';
import {JavaBase} from '../base-installer';
import {IZuluVersions} from './models';
import {
extractJdkFile,
getDownloadArchiveExtension,
convertVersionToSemver,
isVersionSatisfies
} from '../../util';
import {
JavaDownloadRelease,
JavaInstallerOptions,
JavaInstallerResults
} from '../base-models';
export class ZuluDistribution extends JavaBase {
constructor(installerOptions: JavaInstallerOptions) {
super('Zulu', installerOptions);
}
protected async findPackageForDownload(version: string): Promise<JavaDownloadRelease> {
protected async findPackageForDownload(
version: string
): Promise<JavaDownloadRelease> {
const availableVersionsRaw = await this.getAvailableVersions();
const availableVersions = availableVersionsRaw.map(item => {
return {
version: this.convertVersionToSemver(item.jdk_version),
version: convertVersionToSemver(item.jdk_version),
url: item.url,
zuluVersion: this.convertVersionToSemver(item.zulu_version)
zuluVersion: convertVersionToSemver(item.zulu_version)
};
});
@ -42,9 +53,12 @@ export class ZuluDistribution extends JavaBase {
} as JavaDownloadRelease;
});
const resolvedFullVersion = satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
const resolvedFullVersion =
satisfiedVersions.length > 0 ? satisfiedVersions[0] : null;
if (!resolvedFullVersion) {
const availableOptions = availableVersions.map(item => item.version).join(', ');
const availableOptions = availableVersions
.map(item => item.version)
.join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
@ -56,18 +70,18 @@ export class ZuluDistribution extends JavaBase {
return resolvedFullVersion;
}
protected async downloadTool(javaRelease: JavaDownloadRelease): Promise<JavaInstallerResults> {
let extractedJavaPath: string;
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
const javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
let extension = getDownloadArchiveExtension();
const extension = getDownloadArchiveExtension();
extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
@ -79,18 +93,21 @@ export class ZuluDistribution extends JavaBase {
this.architecture
);
return { version: javaRelease.version, path: javaPath };
return {version: javaRelease.version, path: javaPath};
}
private async getAvailableVersions(): Promise<IZuluVersions[]> {
const { arch, hw_bitness, abi } = this.getArchitectureOptions();
const {arch, hw_bitness, abi} = this.getArchitectureOptions();
const [bundleType, features] = this.packageType.split('+');
const platform = this.getPlatformOption();
const extension = getDownloadArchiveExtension();
const javafx = features?.includes('fx') ?? false;
const releaseStatus = this.stable ? 'ga' : 'ea';
console.time('azul-retrieve-available-versions');
if (core.isDebug()) {
console.time('Retrieving available versions for Zulu took'); // eslint-disable-line no-console
}
const requestArguments = [
`os=${platform}`,
`ext=${extension}`,
@ -106,18 +123,20 @@ export class ZuluDistribution extends JavaBase {
.join('&');
const availableVersionsUrl = `https://api.azul.com/zulu/download/community/v1.0/bundles/?${requestArguments}`;
if (core.isDebug()) {
core.debug(`Gathering available versions from '${availableVersionsUrl}'`);
}
core.debug(`Gathering available versions from '${availableVersionsUrl}'`);
const availableVersions =
(await this.http.getJson<Array<IZuluVersions>>(availableVersionsUrl)).result ?? [];
(await this.http.getJson<Array<IZuluVersions>>(availableVersionsUrl))
.result ?? [];
if (core.isDebug()) {
core.startGroup('Print information about available versions');
console.timeEnd('azul-retrieve-available-versions');
console.log(`Available versions: [${availableVersions.length}]`);
console.log(availableVersions.map(item => item.jdk_version.join('.')).join(', '));
console.timeEnd('Retrieving available versions for Zulu took'); // eslint-disable-line no-console
core.debug(`Available versions: [${availableVersions.length}]`);
core.debug(
availableVersions.map(item => item.jdk_version.join('.')).join(', ')
);
core.endGroup();
}
@ -129,12 +148,17 @@ export class ZuluDistribution extends JavaBase {
hw_bitness: string;
abi: string;
} {
if (this.architecture == 'x64') {
return { arch: 'x86', hw_bitness: '64', abi: '' };
} else if (this.architecture == 'x86') {
return { arch: 'x86', hw_bitness: '32', abi: '' };
} else {
return { arch: this.architecture, hw_bitness: '', abi: '' };
const arch = this.distributionArchitecture();
switch (arch) {
case 'x64':
return {arch: 'x86', hw_bitness: '64', abi: ''};
case 'x86':
return {arch: 'x86', hw_bitness: '32', abi: ''};
case 'aarch64':
case 'arm64':
return {arch: 'arm', hw_bitness: '64', abi: ''};
default:
return {arch: arch, hw_bitness: '', abi: ''};
}
}
@ -149,15 +173,4 @@ export class ZuluDistribution extends JavaBase {
return process.platform;
}
}
// Azul API returns jdk_version as array of digits like [11, 0, 2, 1]
private convertVersionToSemver(version_array: number[]) {
const mainVersion = version_array.slice(0, 3).join('.');
if (version_array.length > 3) {
// intentionally ignore more than 4 numbers because it is invalid semver
return `${mainVersion}+${version_array[3]}`;
}
return mainVersion;
}
}

View File

@ -3,7 +3,7 @@ import * as path from 'path';
import * as io from '@actions/io';
import * as exec from '@actions/exec';
import * as util from './util';
import { ExecOptions } from '@actions/exec/lib/interfaces';
import {ExecOptions} from '@actions/exec/lib/interfaces';
export const PRIVATE_KEY_FILE = path.join(util.getTempDir(), 'private-key.asc');
@ -28,7 +28,13 @@ export async function importKey(privateKey: string) {
await exec.exec(
'gpg',
['--batch', '--import-options', 'import-show', '--import', PRIVATE_KEY_FILE],
[
'--batch',
'--import-options',
'import-show',
'--import',
PRIVATE_KEY_FILE
],
options
);
@ -39,7 +45,11 @@ export async function importKey(privateKey: string) {
}
export async function deleteKey(keyFingerprint: string) {
await exec.exec('gpg', ['--batch', '--yes', '--delete-secret-and-public-key', keyFingerprint], {
silent: true
});
await exec.exec(
'gpg',
['--batch', '--yes', '--delete-secret-and-public-key', keyFingerprint],
{
silent: true
}
);
}

View File

@ -1,48 +1,78 @@
import fs from 'fs';
import * as core from '@actions/core';
import * as auth from './auth';
import { getBooleanInput } from './util';
import {
getBooleanInput,
isCacheFeatureAvailable,
getVersionFromFileContent
} from './util';
import * as toolchains from './toolchains';
import * as constants from './constants';
import { restore } from './cache';
import {restore} from './cache';
import * as path from 'path';
import { getJavaDistribution } from './distributions/distribution-factory';
import { JavaInstallerOptions } from './distributions/base-models';
import {getJavaDistribution} from './distributions/distribution-factory';
import {JavaInstallerOptions} from './distributions/base-models';
async function run() {
try {
const version = core.getInput(constants.INPUT_JAVA_VERSION, { required: true });
const distributionName = core.getInput(constants.INPUT_DISTRIBUTION, { required: true });
const versions = core.getMultilineInput(constants.INPUT_JAVA_VERSION);
const distributionName = core.getInput(constants.INPUT_DISTRIBUTION, {
required: true
});
const versionFile = core.getInput(constants.INPUT_JAVA_VERSION_FILE);
const architecture = core.getInput(constants.INPUT_ARCHITECTURE);
const packageType = core.getInput(constants.INPUT_JAVA_PACKAGE);
const jdkFile = core.getInput(constants.INPUT_JDK_FILE);
const cache = core.getInput(constants.INPUT_CACHE);
const checkLatest = getBooleanInput(constants.INPUT_CHECK_LATEST, false);
let toolchainIds = core.getMultilineInput(constants.INPUT_MVN_TOOLCHAIN_ID);
const installerOptions: JavaInstallerOptions = {
architecture,
packageType,
version,
checkLatest
};
core.startGroup('Installed distributions');
const distribution = getJavaDistribution(distributionName, installerOptions, jdkFile);
if (!distribution) {
throw new Error(`No supported distribution was found for input ${distributionName}`);
if (versions.length !== toolchainIds.length) {
toolchainIds = [];
}
const result = await distribution.setupJava();
if (!versions.length && !versionFile) {
throw new Error('java-version or java-version-file input expected');
}
core.info('');
core.info('Java configuration:');
core.info(` Distribution: ${distributionName}`);
core.info(` Version: ${result.version}`);
core.info(` Path: ${result.path}`);
core.info('');
const installerInputsOptions: installerInputsOptions = {
architecture,
packageType,
checkLatest,
distributionName,
jdkFile,
toolchainIds
};
if (!versions.length) {
core.debug(
'java-version input is empty, looking for java-version-file input'
);
const content = fs.readFileSync(versionFile).toString().trim();
const version = getVersionFromFileContent(content, distributionName);
core.debug(`Parsed version from file '${version}'`);
if (!version) {
throw new Error(
`No supported version was found in file ${versionFile}`
);
}
await installVersion(version, installerInputsOptions);
}
for (const [index, version] of versions.entries()) {
await installVersion(version, installerInputsOptions, index);
}
core.endGroup();
const matchersPath = path.join(__dirname, '..', '..', '.github');
core.info(`##[add-matcher]${path.join(matchersPath, 'java.json')}`);
await auth.configureAuthentication();
if (cache) {
if (cache && isCacheFeatureAvailable()) {
await restore(cache);
}
} catch (error) {
@ -51,3 +81,60 @@ async function run() {
}
run();
async function installVersion(
version: string,
options: installerInputsOptions,
toolchainId = 0
) {
const {
distributionName,
jdkFile,
architecture,
packageType,
checkLatest,
toolchainIds
} = options;
const installerOptions: JavaInstallerOptions = {
architecture,
packageType,
checkLatest,
version
};
const distribution = getJavaDistribution(
distributionName,
installerOptions,
jdkFile
);
if (!distribution) {
throw new Error(
`No supported distribution was found for input ${distributionName}`
);
}
const result = await distribution.setupJava();
await toolchains.configureToolchains(
version,
distributionName,
result.path,
toolchainIds[toolchainId]
);
core.info('');
core.info('Java configuration:');
core.info(` Distribution: ${distributionName}`);
core.info(` Version: ${result.version}`);
core.info(` Path: ${result.path}`);
core.info('');
}
interface installerInputsOptions {
architecture: string;
packageType: string;
checkLatest: boolean;
distributionName: string;
jdkFile: string;
toolchainIds: Array<string>;
}

169
src/toolchains.ts Normal file
View File

@ -0,0 +1,169 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as core from '@actions/core';
import * as io from '@actions/io';
import * as constants from './constants';
import {getBooleanInput} from './util';
import {create as xmlCreate} from 'xmlbuilder2';
interface JdkInfo {
version: string;
vendor: string;
id: string;
jdkHome: string;
}
export async function configureToolchains(
version: string,
distributionName: string,
jdkHome: string,
toolchainId?: string
) {
const vendor =
core.getInput(constants.INPUT_MVN_TOOLCHAIN_VENDOR) || distributionName;
const id = toolchainId || `${vendor}_${version}`;
const settingsDirectory =
core.getInput(constants.INPUT_SETTINGS_PATH) ||
path.join(os.homedir(), constants.M2_DIR);
const overwriteSettings = getBooleanInput(
constants.INPUT_OVERWRITE_SETTINGS,
true
);
await createToolchainsSettings({
jdkInfo: {
version,
vendor,
id,
jdkHome
},
settingsDirectory,
overwriteSettings
});
}
export async function createToolchainsSettings({
jdkInfo,
settingsDirectory,
overwriteSettings
}: {
jdkInfo: JdkInfo;
settingsDirectory: string;
overwriteSettings: boolean;
}) {
core.info(
`Creating ${constants.MVN_TOOLCHAINS_FILE} 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 io.mkdirP(settingsDirectory);
const originalToolchains = await readExistingToolchainsFile(
settingsDirectory
);
const updatedToolchains = generateToolchainDefinition(
originalToolchains,
jdkInfo.version,
jdkInfo.vendor,
jdkInfo.id,
jdkInfo.jdkHome
);
await writeToolchainsFileToDisk(
settingsDirectory,
updatedToolchains,
overwriteSettings
);
}
// only exported for testing purposes
export function generateToolchainDefinition(
original: string,
version: string,
vendor: string,
id: string,
jdkHome: string
) {
let xmlObj;
if (original?.length) {
xmlObj = xmlCreate(original)
.root()
.ele({
toolchain: {
type: 'jdk',
provides: {
version: `${version}`,
vendor: `${vendor}`,
id: `${id}`
},
configuration: {
jdkHome: `${jdkHome}`
}
}
});
} else
xmlObj = xmlCreate({
toolchains: {
'@xmlns': 'https://maven.apache.org/TOOLCHAINS/1.1.0',
'@xmlns:xsi': 'https://www.w3.org/2001/XMLSchema-instance',
'@xsi:schemaLocation':
'https://maven.apache.org/TOOLCHAINS/1.1.0 https://maven.apache.org/xsd/toolchains-1.1.0.xsd',
toolchain: [
{
type: 'jdk',
provides: {
version: `${version}`,
vendor: `${vendor}`,
id: `${id}`
},
configuration: {
jdkHome: `${jdkHome}`
}
}
]
}
});
return xmlObj.end({
format: 'xml',
wellFormed: false,
headless: false,
prettyPrint: true,
width: 80
});
}
async function readExistingToolchainsFile(directory: string) {
const location = path.join(directory, constants.MVN_TOOLCHAINS_FILE);
if (fs.existsSync(location)) {
return fs.readFileSync(location, {
encoding: 'utf-8',
flag: 'r'
});
}
return '';
}
async function writeToolchainsFileToDisk(
directory: string,
settings: string,
overwriteSettings: boolean
) {
const location = path.join(directory, constants.MVN_TOOLCHAINS_FILE);
const settingsExists = fs.existsSync(location);
if (settingsExists && overwriteSettings) {
core.info(`Overwriting existing file ${location}`);
} else if (!settingsExists) {
core.info(`Writing to ${location}`);
} else {
core.info(
`Skipping generation of ${location} because file already exists and overwriting is not enabled`
);
return;
}
return fs.writeFileSync(location, settings, {
encoding: 'utf-8',
flag: 'w'
});
}

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