Add and configure ESLint and update configuration for Prettier (#458)

* Add ESLint config and update Prettier

* Update test files

* Rebuild action

* Update docs

* Update licenses

* Update tsconfig

* Rebuild action

* Update tsconfig.json

* Fix console.time calls

* Rebuild action

* Rebuild action on Linux
This commit is contained in:
Ivan
2023-03-09 14:49:35 +02:00
committed by GitHub
parent ea15b3b99c
commit 0de5c66fc0
55 changed files with 4402 additions and 1317 deletions

View File

@ -5,20 +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';
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(), constants.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);
@ -69,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',
@ -102,7 +107,11 @@ export function generate(
});
}
async function write(directory: string, settings: string, overwriteSettings: boolean) {
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) {

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';
@ -29,7 +29,10 @@ 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*',
@ -50,18 +53,25 @@ const supportedPackageManager: PackageManager[] = [
'!' + join(os.homedir(), '.sbt', '*.lock'),
'!' + join(os.homedir(), '**', 'ivydata-*.properties')
],
pattern: ['**/*.sbt', '**/project/build.properties', '**/project/**.{scala,sbt}']
pattern: [
'**/*.sbt',
'**/project/build.properties',
'**/project/**.{scala,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');
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}`);
}
@ -125,7 +135,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 {
@ -151,8 +163,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

@ -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 {
@ -94,7 +111,7 @@ export class AdoptDistribution extends JavaBase {
const releaseType = this.stable ? 'ga' : 'ea';
if (core.isDebug()) {
console.time('adopt-retrieve-available-versions');
console.time('Retrieving available versions for Adopt took'); // eslint-disable-line no-console
}
const baseRequestArguments = [
@ -119,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 = (
@ -136,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,13 @@ import * as fs from 'fs';
import semver from 'semver';
import path from 'path';
import * as httpm from '@actions/http-client';
import { getToolcachePath, 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 {
@ -17,13 +21,16 @@ 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 || os.arch();
@ -31,8 +38,12 @@ export abstract class JavaBase {
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();
@ -52,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;
}
@ -96,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')
};
})
@ -149,7 +168,10 @@ export abstract class JavaBase {
core.setOutput('distribution', this.distribution);
core.setOutput('path', toolPath);
core.setOutput('version', version);
core.exportVariable(`JAVA_HOME_${majorVersion}_${this.architecture.toUpperCase()}`, toolPath);
core.exportVariable(
`JAVA_HOME_${majorVersion}_${this.architecture.toUpperCase()}`,
toolPath
);
}
protected distributionArchitecture(): string {

View File

@ -2,17 +2,26 @@ import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import fs from 'fs';
import path from 'path';
import { extractJdkFile, getDownloadArchiveExtension } from '../../util';
import { JavaBase } from '../base-installer';
import { JavaDownloadRelease, JavaInstallerOptions, JavaInstallerResults } from '../base-models';
import { ICorrettoAllAvailableVersions, ICorrettoAvailableVersions } from './models';
import {extractJdkFile, getDownloadArchiveExtension} 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> {
protected async downloadTool(
javaRelease: JavaDownloadRelease
): Promise<JavaInstallerResults> {
core.info(
`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
);
@ -20,7 +29,10 @@ export class CorrettoDistribution extends JavaBase {
core.info(`Extracting Java archive...`);
const extractedJavaPath = await extractJdkFile(javaArchivePath, getDownloadArchiveExtension());
const extractedJavaPath = await extractJdkFile(
javaArchivePath,
getDownloadArchiveExtension()
);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
@ -33,10 +45,12 @@ export class CorrettoDistribution extends JavaBase {
this.architecture
);
return { version: javaRelease.version, path: javaPath };
return {version: javaRelease.version, path: javaPath};
}
protected async findPackageForDownload(version: string): Promise<JavaDownloadRelease> {
protected async findPackageForDownload(
version: string
): Promise<JavaDownloadRelease> {
if (!this.stable) {
throw new Error('Early access versions are not supported');
}
@ -53,9 +67,12 @@ export class CorrettoDistribution extends JavaBase {
} as JavaDownloadRelease;
});
const resolvedVersion = matchingVersions.length > 0 ? matchingVersions[0] : null;
const resolvedVersion =
matchingVersions.length > 0 ? matchingVersions[0] : null;
if (!resolvedVersion) {
const availableOptions = availableVersions.map(item => item.version).join(', ');
const availableOptions = availableVersions
.map(item => item.version)
.join(', ');
const availableOptionsMessage = availableOptions
? `\nAvailable versions: ${availableOptions}`
: '';
@ -72,43 +89,61 @@ export class CorrettoDistribution extends JavaBase {
const imageType = this.packageType;
if (core.isDebug()) {
console.time('corretto-retrieve-available-versions');
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 fetchCurrentVersions =
await this.http.getJson<ICorrettoAllAvailableVersions>(
availableVersionsUrl
);
const fetchedCurrentVersions = fetchCurrentVersions.result;
if (!fetchedCurrentVersions) {
throw Error(`Could not fetch latest corretto versions from ${availableVersionsUrl}`);
throw Error(
`Could not fetch latest corretto versions from ${availableVersionsUrl}`
);
}
const eligibleVersions = fetchedCurrentVersions?.[platform]?.[arch]?.[imageType];
const availableVersions = this.getAvailableVersionsForPlatform(eligibleVersions);
const eligibleVersions =
fetchedCurrentVersions?.[platform]?.[arch]?.[imageType];
const availableVersions =
this.getAvailableVersionsForPlatform(eligibleVersions);
if (core.isDebug()) {
this.printAvailableVersions(availableVersions);
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
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();
const skipNonExtractableBinaries =
fileType != getDownloadArchiveExtension();
if (skipNonExtractableBinaries) {
continue;
}
const availableVersionDetails = availableVersion[fileType];
const correttoVersion = this.getCorrettoVersion(availableVersionDetails.resource);
const correttoVersion = this.getCorrettoVersion(
availableVersionDetails.resource
);
availableVersions.push({
checksum: availableVersionDetails.checksum,
@ -124,16 +159,6 @@ export class CorrettoDistribution extends JavaBase {
return availableVersions;
}
private printAvailableVersions(availableVersions: ICorrettoAvailableVersions[]) {
core.startGroup('Print information about available versions');
console.timeEnd('corretto-retrieve-available-versions');
console.log(`Available versions: [${availableVersions.length}]`);
console.log(
availableVersions.map(item => `${item.version}: ${item.correttoVersion}`).join(', ')
);
core.endGroup();
}
private getPlatformOption(): string {
// Corretto has its own platform names so we need to map them
switch (process.platform) {

View File

@ -1,13 +1,13 @@
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 { CorrettoDistribution } from './corretto/installer';
import { OracleDistribution } from './oracle/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 {CorrettoDistribution} from './corretto/installer';
import {OracleDistribution} from './oracle/installer';
enum JavaDistribution {
Adopt = 'adopt',
@ -32,11 +32,20 @@ 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:

View File

@ -1,9 +1,17 @@
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';
@ -17,7 +25,9 @@ export class LibericaDistributions extends JavaBase {
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}`
: '';
@ -67,21 +81,20 @@ export class LibericaDistributions extends JavaBase {
private async getAvailableVersions(): Promise<LibericaVersion[]> {
if (core.isDebug()) {
console.time('liberica-retrieve-available-versions');
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();
}
@ -95,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();
@ -115,15 +129,15 @@ export class LibericaDistributions extends JavaBase {
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: ${supportedArchitectures}`
@ -131,7 +145,9 @@ export class LibericaDistributions extends JavaBase {
}
}
private getPlatformOption(platform: NodeJS.Platform = process.platform): OsVersions {
private getPlatformOption(
platform: NodeJS.Platform = process.platform
): OsVersions {
switch (platform) {
case 'darwin':
return 'macos';
@ -150,8 +166,11 @@ 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}`;
}
@ -159,7 +178,7 @@ export class LibericaDistributions extends JavaBase {
}
protected distributionArchitecture(): string {
let arch = super.distributionArchitecture();
const arch = super.distributionArchitecture();
switch (arch) {
case 'arm':
return 'armv7';

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");
}
@ -66,11 +74,19 @@ export class LocalDistribution extends JavaBase {
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 { extractJdkFile, getDownloadArchiveExtension } 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 * as tc from '@actions/tool-cache';
import { OutgoingHttpHeaders } from 'http';
import {OutgoingHttpHeaders} from 'http';
import fs from 'fs';
import path from 'path';
import { ITypedResponse } from '@actions/http-client/interfaces';
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,10 +39,12 @@ 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> {
protected async findPackageForDownload(
range: string
): Promise<JavaDownloadRelease> {
const arch = this.distributionArchitecture();
if (arch !== 'x64' && arch !== 'aarch64') {
throw new Error(`Unsupported architecture: ${this.architecture}`);
@ -47,7 +55,9 @@ export class MicrosoftDistributions extends JavaBase {
}
if (this.packageType !== 'jdk') {
throw new Error('Microsoft Build of OpenJDK provides only the `jdk` package type');
throw new Error(
'Microsoft Build of OpenJDK provides only the `jdk` package type'
);
}
const manifest = await this.getAvailableVersions();
@ -66,7 +76,10 @@ export class MicrosoftDistributions extends JavaBase {
);
}
return { url: foundRelease.files[0].download_url, version: foundRelease.version };
return {
url: foundRelease.files[0].download_url,
version: foundRelease.version
};
}
private async getAvailableVersions(): Promise<tc.IToolRelease[] | null> {
@ -77,7 +90,8 @@ export class MicrosoftDistributions extends JavaBase {
const owner = 'actions';
const repository = 'setup-java';
const branch = 'main';
const filePath = 'src/distributions/microsoft/microsoft-openjdk-versions.json';
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}`;
@ -89,6 +103,10 @@ export class MicrosoftDistributions extends JavaBase {
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) {
@ -105,6 +123,14 @@ export class MicrosoftDistributions extends JavaBase {
releases = response.result;
}
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

@ -1,2 +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';

View File

@ -4,10 +4,14 @@ 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';
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';
@ -16,32 +20,36 @@ export class OracleDistribution extends JavaBase {
super('Oracle', 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} ...`
);
const javaArchivePath = await tc.downloadTool(javaRelease.url);
core.info(`Extracting Java archive...`);
let extension = getDownloadArchiveExtension();
const extension = getDownloadArchiveExtension();
let 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);
let javaPath = await tc.cacheDir(
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
version,
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 arch = this.distributionArchitecture();
if (arch !== 'x64' && arch !== 'aarch64') {
throw new Error(`Unsupported architecture: ${this.architecture}`);
@ -83,7 +91,7 @@ export class OracleDistribution extends JavaBase {
);
}
return { url: fileUrl, version: range };
return {url: fileUrl, version: range};
}
public getPlatform(platform: NodeJS.Platform = process.platform): OsVersions {

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 {
@ -92,7 +109,7 @@ export class TemurinDistribution extends JavaBase {
const releaseType = this.stable ? 'ga' : 'ea';
if (core.isDebug()) {
console.time('temurin-retrieve-available-versions');
console.time('Retrieving available versions for Temurin took'); // eslint-disable-line no-console
}
const baseRequestArguments = [
@ -117,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
@ -134,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,17 +5,27 @@ 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,
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 {
@ -42,9 +52,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 +69,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,11 +92,11 @@ 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();
@ -91,8 +104,9 @@ export class ZuluDistribution extends JavaBase {
const releaseStatus = this.stable ? 'ga' : 'ea';
if (core.isDebug()) {
console.time('azul-retrieve-available-versions');
console.time('Retrieving available versions for Zulu took'); // eslint-disable-line no-console
}
const requestArguments = [
`os=${platform}`,
`ext=${extension}`,
@ -108,18 +122,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();
}
@ -134,14 +150,14 @@ export class ZuluDistribution extends JavaBase {
const arch = this.distributionArchitecture();
switch (arch) {
case 'x64':
return { arch: 'x86', hw_bitness: '64', abi: '' };
return {arch: 'x86', hw_bitness: '64', abi: ''};
case 'x86':
return { arch: 'x86', hw_bitness: '32', abi: '' };
return {arch: 'x86', hw_bitness: '32', abi: ''};
case 'aarch64':
case 'arm64':
return { arch: 'arm', hw_bitness: '64', abi: '' };
return {arch: 'arm', hw_bitness: '64', abi: ''};
default:
return { arch: arch, hw_bitness: '', abi: '' };
return {arch: arch, hw_bitness: '', abi: ''};
}
}

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,18 +1,24 @@
import fs from 'fs';
import * as core from '@actions/core';
import * as auth from './auth';
import { getBooleanInput, isCacheFeatureAvailable, getVersionFromFileContent } 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 versions = core.getMultilineInput(constants.INPUT_JAVA_VERSION);
const distributionName = core.getInput(constants.INPUT_DISTRIBUTION, { required: true });
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);
@ -41,17 +47,18 @@ async function run() {
};
if (!versions.length) {
core.debug('java-version input is empty, looking for java-version-file input');
const content = fs
.readFileSync(versionFile)
.toString()
.trim();
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}`);
throw new Error(
`No supported version was found in file ${versionFile}`
);
}
await installVersion(version, installerInputsOptions);
@ -75,7 +82,11 @@ async function run() {
run();
async function installVersion(version: string, options: installerInputsOptions, toolchainId = 0) {
async function installVersion(
version: string,
options: installerInputsOptions,
toolchainId = 0
) {
const {
distributionName,
jdkFile,
@ -92,9 +103,15 @@ async function installVersion(version: string, options: installerInputsOptions,
version
};
const distribution = getJavaDistribution(distributionName, installerOptions, jdkFile);
const distribution = getJavaDistribution(
distributionName,
installerOptions,
jdkFile
);
if (!distribution) {
throw new Error(`No supported distribution was found for input ${distributionName}`);
throw new Error(
`No supported distribution was found for input ${distributionName}`
);
}
const result = await distribution.setupJava();

View File

@ -5,8 +5,8 @@ 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';
import {getBooleanInput} from './util';
import {create as xmlCreate} from 'xmlbuilder2';
interface JdkInfo {
version: string;
@ -21,11 +21,16 @@ export async function configureToolchains(
jdkHome: string,
toolchainId?: string
) {
const vendor = core.getInput(constants.INPUT_MVN_TOOLCHAIN_VENDOR) || distributionName;
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);
core.getInput(constants.INPUT_SETTINGS_PATH) ||
path.join(os.homedir(), constants.M2_DIR);
const overwriteSettings = getBooleanInput(
constants.INPUT_OVERWRITE_SETTINGS,
true
);
await createToolchainsSettings({
jdkInfo: {
@ -54,7 +59,9 @@ export async function createToolchainsSettings({
// 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 originalToolchains = await readExistingToolchainsFile(
settingsDirectory
);
const updatedToolchains = generateToolchainDefinition(
originalToolchains,
jdkInfo.version,
@ -62,7 +69,11 @@ export async function createToolchainsSettings({
jdkInfo.id,
jdkInfo.jdkHome
);
await writeToolchainsFileToDisk(settingsDirectory, updatedToolchains, overwriteSettings);
await writeToolchainsFileToDisk(
settingsDirectory,
updatedToolchains,
overwriteSettings
);
}
// only exported for testing purposes

View File

@ -6,16 +6,18 @@ import * as cache from '@actions/cache';
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
import { INPUT_JOB_STATUS, DISTRIBUTIONS_ONLY_MAJOR_VERSION } from './constants';
import {INPUT_JOB_STATUS, DISTRIBUTIONS_ONLY_MAJOR_VERSION} from './constants';
export function getTempDir() {
let tempDirectory = process.env['RUNNER_TEMP'] || os.tmpdir();
const tempDirectory = process.env['RUNNER_TEMP'] || os.tmpdir();
return tempDirectory;
}
export function getBooleanInput(inputName: string, defaultValue: boolean = false) {
return (core.getInput(inputName) || String(defaultValue)).toUpperCase() === 'TRUE';
export function getBooleanInput(inputName: string, defaultValue = false) {
return (
(core.getInput(inputName) || String(defaultValue)).toUpperCase() === 'TRUE'
);
}
export function getVersionFromToolcachePath(toolPath: string) {
@ -28,7 +30,9 @@ export function getVersionFromToolcachePath(toolPath: string) {
export async function extractJdkFile(toolPath: string, extension?: string) {
if (!extension) {
extension = toolPath.endsWith('.tar.gz') ? 'tar.gz' : path.extname(toolPath);
extension = toolPath.endsWith('.tar.gz')
? 'tar.gz'
: path.extname(toolPath);
if (extension.startsWith('.')) {
extension = extension.substring(1);
}
@ -63,7 +67,11 @@ export function isVersionSatisfies(range: string, version: string): boolean {
return semver.satisfies(version, range);
}
export function getToolcachePath(toolName: string, version: string, architecture: string) {
export function getToolcachePath(
toolName: string,
version: string,
architecture: string
) {
const toolcacheRoot = process.env['RUNNER_TOOL_CACHE'] ?? '';
const fullPath = path.join(toolcacheRoot, toolName, version, architecture);
if (fs.existsSync(fullPath)) {
@ -80,7 +88,9 @@ export function isJobStatusSuccess() {
}
export function isGhes(): boolean {
const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
const ghUrl = new URL(
process.env['GITHUB_SERVER_URL'] || 'https://github.com'
);
return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM';
}
@ -96,7 +106,9 @@ export function isCacheFeatureAvailable(): boolean {
return false;
}
core.warning('The runner was not able to contact the cache service. Caching will be skipped');
core.warning(
'The runner was not able to contact the cache service. Caching will be skipped'
);
return false;
}
@ -104,7 +116,7 @@ export function getVersionFromFileContent(
content: string,
distributionName: string
): string | null {
const javaVersionRegExp = /(?<version>(?<=(^|\s|\-))(\d+\S*))(\s|$)/;
const javaVersionRegExp = /(?<version>(?<=(^|\s|-))(\d+\S*))(\s|$)/;
const fileContent = content.match(javaVersionRegExp)?.groups?.version
? (content.match(javaVersionRegExp)?.groups?.version as string)
: '';
@ -117,7 +129,9 @@ export function getVersionFromFileContent(
const tentativeVersion = avoidOldNotation(fileContent);
const rawVersion = tentativeVersion.split('-')[0];
let version = semver.validRange(rawVersion) ? tentativeVersion : semver.coerce(tentativeVersion);
let version = semver.validRange(rawVersion)
? tentativeVersion
: semver.coerce(tentativeVersion);
core.debug(`Range version from file is '${version}'`);