Unverified Commit 46c56d6f authored by mahabaleshwars's avatar mahabaleshwars Committed by GitHub
Browse files

Add GitHub Token Support for GraalVM and Refactor Code (#849)

* Code updated to let code accept github token and refactored the code.

* github token accept through environment variable

* fix test error

* audit fix commit

* update package-lock.json

* Update GraalVM Tests

* Lint Issue Resolve

* Update Test case for Windows

* update with enhance code and test
parent 66b94576
Loading
Loading
Loading
Loading
+876 −108

File changed.

Preview size limit exceeded, changes collapsed.

+2 −2
Changes for dist/cleanup/index.js: 2 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -94747,8 +94747,8 @@ function convertVersionToSemver(version) {
}
exports.convertVersionToSemver = convertVersionToSemver;
function getGitHubHttpHeaders() {
    const token = core.getInput('token');
    const auth = !token ? undefined : `token ${token}`;
    const resolvedToken = core.getInput('token') || process.env.GITHUB_TOKEN;
    const auth = !resolvedToken ? undefined : `token ${resolvedToken}`;
    const headers = {
        accept: 'application/vnd.github.VERSION.raw'
    };
+91 −49
Changes for dist/setup/index.js: 91 added lines, 49 removed lines.
Original line number Diff line number Diff line
@@ -130592,37 +130592,56 @@ const tc = __importStar(__nccwpck_require__(27784));
const fs_1 = __importDefault(__nccwpck_require__(57147));
const path_1 = __importDefault(__nccwpck_require__(71017));
const base_installer_1 = __nccwpck_require__(59741);
const util_1 = __nccwpck_require__(92629);
const http_client_1 = __nccwpck_require__(96255);
const util_1 = __nccwpck_require__(92629);
const GRAALVM_DL_BASE = 'https://download.oracle.com/graalvm';
const IS_WINDOWS = process.platform === 'win32';
const GRAALVM_PLATFORM = IS_WINDOWS ? 'windows' : process.platform;
const GRAALVM_MIN_VERSION = 17;
const SUPPORTED_ARCHITECTURES = ['x64', 'aarch64'];
class GraalVMDistribution extends base_installer_1.JavaBase {
    constructor(installerOptions) {
        super('GraalVM', installerOptions);
    }
    downloadTool(javaRelease) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                core.info(`Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`);
                let javaArchivePath = yield tc.downloadTool(javaRelease.url);
                core.info(`Extracting Java archive...`);
                const extension = (0, util_1.getDownloadArchiveExtension)();
            if (process.platform === 'win32') {
                if (IS_WINDOWS) {
                    javaArchivePath = (0, util_1.renameWinArchive)(javaArchivePath);
                }
                const extractedJavaPath = yield (0, util_1.extractJdkFile)(javaArchivePath, extension);
            const archiveName = fs_1.default.readdirSync(extractedJavaPath)[0];
            const archivePath = path_1.default.join(extractedJavaPath, archiveName);
                // Add validation for extracted path
                if (!fs_1.default.existsSync(extractedJavaPath)) {
                    throw new Error(`Extraction failed: path ${extractedJavaPath} does not exist`);
                }
                const dirContents = fs_1.default.readdirSync(extractedJavaPath);
                if (dirContents.length === 0) {
                    throw new Error('Extraction failed: no files found in extracted directory');
                }
                const archivePath = path_1.default.join(extractedJavaPath, dirContents[0]);
                const version = this.getToolcacheVersionName(javaRelease.version);
                const javaPath = yield tc.cacheDir(archivePath, this.toolcacheFolderName, version, this.architecture);
                return { version: javaRelease.version, path: javaPath };
            }
            catch (error) {
                core.error(`Failed to download and extract GraalVM: ${error}`);
                throw error;
            }
        });
    }
    findPackageForDownload(range) {
        return __awaiter(this, void 0, void 0, function* () {
            // Add input validation
            if (!range || typeof range !== 'string') {
                throw new Error('Version range is required and must be a string');
            }
            const arch = this.distributionArchitecture();
            if (arch !== 'x64' && arch !== 'aarch64') {
                throw new Error(`Unsupported architecture: ${this.architecture}`);
            if (!SUPPORTED_ARCHITECTURES.includes(arch)) {
                throw new Error(`Unsupported architecture: ${this.architecture}. Supported architectures are: ${SUPPORTED_ARCHITECTURES.join(', ')}`);
            }
            if (!this.stable) {
                return this.findEABuildDownloadUrl(`${range}-ea`);
@@ -130632,81 +130651,104 @@ class GraalVMDistribution extends base_installer_1.JavaBase {
            }
            const platform = this.getPlatform();
            const extension = (0, util_1.getDownloadArchiveExtension)();
            let major;
            let fileUrl;
            if (range.includes('.')) {
                major = range.split('.')[0];
                fileUrl = `${GRAALVM_DL_BASE}/${major}/archive/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`;
            }
            else {
                major = range;
                fileUrl = `${GRAALVM_DL_BASE}/${range}/latest/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`;
            const major = range.includes('.') ? range.split('.')[0] : range;
            const majorVersion = parseInt(major);
            if (isNaN(majorVersion)) {
                throw new Error(`Invalid version format: ${range}`);
            }
            if (parseInt(major) < 17) {
                throw new Error('GraalVM is only supported for JDK 17 and later');
            if (majorVersion < GRAALVM_MIN_VERSION) {
                throw new Error(`GraalVM is only supported for JDK ${GRAALVM_MIN_VERSION} and later. Requested version: ${major}`);
            }
            const fileUrl = this.constructFileUrl(range, major, platform, arch, extension);
            const response = yield this.http.head(fileUrl);
            if (response.message.statusCode === http_client_1.HttpCodes.NotFound) {
                throw new Error(`Could not find GraalVM for SemVer ${range}`);
            }
            if (response.message.statusCode !== http_client_1.HttpCodes.OK) {
                throw new Error(`Http request for GraalVM failed with status code: ${response.message.statusCode}`);
            }
            this.handleHttpResponse(response, range);
            return { url: fileUrl, version: range };
        });
    }
    constructFileUrl(range, major, platform, arch, extension) {
        return range.includes('.')
            ? `${GRAALVM_DL_BASE}/${major}/archive/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`
            : `${GRAALVM_DL_BASE}/${range}/latest/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`;
    }
    handleHttpResponse(response, range) {
        const statusCode = response.message.statusCode;
        if (statusCode === http_client_1.HttpCodes.NotFound) {
            throw new Error(`Could not find GraalVM for SemVer ${range}. Please check if this version is available at ${GRAALVM_DL_BASE}`);
        }
        if (statusCode === http_client_1.HttpCodes.Unauthorized ||
            statusCode === http_client_1.HttpCodes.Forbidden) {
            throw new Error(`Access denied when downloading GraalVM. Status code: ${statusCode}. Please check your credentials or permissions.`);
        }
        if (statusCode !== http_client_1.HttpCodes.OK) {
            throw new Error(`HTTP request for GraalVM failed with status code: ${statusCode} (${response.message.statusMessage || 'Unknown error'})`);
        }
    }
    findEABuildDownloadUrl(javaEaVersion) {
        return __awaiter(this, void 0, void 0, function* () {
            core.debug(`Searching for EA build: ${javaEaVersion}`);
            const versions = yield this.fetchEAJson(javaEaVersion);
            core.debug(`Found ${versions.length} EA versions`);
            const latestVersion = versions.find(v => v.latest);
            if (!latestVersion) {
                core.error(`Available versions: ${versions.map(v => v.version).join(', ')}`);
                throw new Error(`Unable to find latest version for '${javaEaVersion}'`);
            }
            core.debug(`Latest version found: ${latestVersion.version}`);
            const arch = this.distributionArchitecture();
            const file = latestVersion.files.find(f => f.arch === arch && f.platform === GRAALVM_PLATFORM);
            if (!file || !file.filename.startsWith('graalvm-jdk-')) {
                throw new Error(`Unable to find file metadata for '${javaEaVersion}'`);
            if (!file) {
                core.error(`Available files for architecture ${arch}: ${JSON.stringify(latestVersion.files)}`);
                throw new Error(`Unable to find file for architecture '${arch}' and platform '${GRAALVM_PLATFORM}'`);
            }
            if (!file.filename.startsWith('graalvm-jdk-')) {
                throw new Error(`Invalid filename format: ${file.filename}. Expected to start with 'graalvm-jdk-'`);
            }
            const downloadUrl = `${latestVersion.download_base_url}${file.filename}`;
            core.debug(`Download URL: ${downloadUrl}`);
            return {
                url: `${latestVersion.download_base_url}${file.filename}`,
                url: downloadUrl,
                version: latestVersion.version
            };
        });
    }
    fetchEAJson(javaEaVersion) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const owner = 'graalvm';
            const repository = 'oracle-graalvm-ea-builds';
            const branch = 'main';
            const filePath = `versions/${javaEaVersion}.json`;
            const url = `https://api.github.com/repos/${owner}/${repository}/contents/${filePath}?ref=${branch}`;
            const url = `https://api.github.com/repos/graalvm/oracle-graalvm-ea-builds/contents/versions/${javaEaVersion}.json?ref=main`;
            const headers = (0, util_1.getGitHubHttpHeaders)();
            core.debug(`Trying to fetch available version info for GraalVM EA builds from '${url}'`);
            let fetchedJson;
            try {
                fetchedJson = (yield this.http.getJson(url, headers))
                    .result;
                const response = yield this.http.getJson(url, headers);
                if (!response.result) {
                    throw new Error(`No GraalVM EA build found for version '${javaEaVersion}'. Please check if the version is correct.`);
                }
            catch (err) {
                throw Error(`Fetching version info for GraalVM EA builds from '${url}' failed with the error: ${err.message}`);
                return response.result;
            }
            catch (error) {
                if (error instanceof Error) {
                    // Check if it's a 404 error (file not found)
                    if ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('404')) {
                        throw new Error(`GraalVM EA version '${javaEaVersion}' not found. Please verify the version exists in the EA builds repository.`);
                    }
                    // Re-throw with more context
                    throw new Error(`Failed to fetch GraalVM EA version information for '${javaEaVersion}': ${error.message}`);
                }
            if (fetchedJson === null) {
                throw Error(`No GraalVM EA build found. Are you sure java-version: '${javaEaVersion}' is correct?`);
                // If it's not an Error instance, throw a generic error
                throw new Error(`Failed to fetch GraalVM EA version information for '${javaEaVersion}'`);
            }
            return fetchedJson;
        });
    }
    getPlatform(platform = process.platform) {
        switch (platform) {
            case 'darwin':
                return 'macos';
            case 'win32':
                return 'windows';
            case 'linux':
                return 'linux';
            default:
        const platformMap = {
            darwin: 'macos',
            win32: 'windows',
            linux: 'linux'
        };
        const result = platformMap[platform];
        if (!result) {
            throw new Error(`Platform '${platform}' is not supported. Supported platforms: 'linux', 'macos', 'windows'`);
        }
        return result;
    }
}
exports.GraalVMDistribution = GraalVMDistribution;
@@ -132849,8 +132891,8 @@ function convertVersionToSemver(version) {
}
exports.convertVersionToSemver = convertVersionToSemver;
function getGitHubHttpHeaders() {
    const token = core.getInput('token');
    const auth = !token ? undefined : `token ${token}`;
    const resolvedToken = core.getInput('token') || process.env.GITHUB_TOKEN;
    const auth = !resolvedToken ? undefined : `token ${resolvedToken}`;
    const headers = {
        accept: 'application/vnd.github.VERSION.raw'
    };
+64 −80

File changed.

Preview size limit exceeded, changes collapsed.

+157 −55
Changes for src/distributions/graalvm/installer.ts: 157 added lines, 55 removed lines.
Original line number Diff line number Diff line
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 {HttpCodes} from '@actions/http-client';
import {GraalVMEAVersion} from './models';
import {
  JavaDownloadRelease,
  JavaInstallerOptions,
@@ -16,12 +16,14 @@ import {
  getGitHubHttpHeaders,
  renameWinArchive
} from '../../util';
import {HttpCodes} from '@actions/http-client';
import {GraalVMEAVersion} from './models';

const GRAALVM_DL_BASE = 'https://download.oracle.com/graalvm';
const IS_WINDOWS = process.platform === 'win32';
const GRAALVM_PLATFORM = IS_WINDOWS ? 'windows' : process.platform;
const GRAALVM_MIN_VERSION = 17;
const SUPPORTED_ARCHITECTURES = ['x64', 'aarch64'] as const;
type SupportedArchitecture = (typeof SUPPORTED_ARCHITECTURES)[number];
type OsVersions = 'linux' | 'macos' | 'windows';

export class GraalVMDistribution extends JavaBase {
  constructor(installerOptions: JavaInstallerOptions) {
@@ -31,6 +33,7 @@ export class GraalVMDistribution extends JavaBase {
  protected async downloadTool(
    javaRelease: JavaDownloadRelease
  ): Promise<JavaInstallerResults> {
    try {
      core.info(
        `Downloading Java ${javaRelease.version} (${this.distribution}) from ${javaRelease.url} ...`
      );
@@ -38,13 +41,30 @@ export class GraalVMDistribution extends JavaBase {

      core.info(`Extracting Java archive...`);
      const extension = getDownloadArchiveExtension();
    if (process.platform === 'win32') {
      if (IS_WINDOWS) {
        javaArchivePath = renameWinArchive(javaArchivePath);
      }
    const extractedJavaPath = await extractJdkFile(javaArchivePath, extension);

    const archiveName = fs.readdirSync(extractedJavaPath)[0];
    const archivePath = path.join(extractedJavaPath, archiveName);
      const extractedJavaPath = await extractJdkFile(
        javaArchivePath,
        extension
      );

      // Add validation for extracted path
      if (!fs.existsSync(extractedJavaPath)) {
        throw new Error(
          `Extraction failed: path ${extractedJavaPath} does not exist`
        );
      }

      const dirContents = fs.readdirSync(extractedJavaPath);
      if (dirContents.length === 0) {
        throw new Error(
          'Extraction failed: no files found in extracted directory'
        );
      }

      const archivePath = path.join(extractedJavaPath, dirContents[0]);
      const version = this.getToolcacheVersionName(javaRelease.version);

      const javaPath = await tc.cacheDir(
@@ -55,14 +75,25 @@ export class GraalVMDistribution extends JavaBase {
      );

      return {version: javaRelease.version, path: javaPath};
    } catch (error) {
      core.error(`Failed to download and extract GraalVM: ${error}`);
      throw error;
    }
  }

  protected async findPackageForDownload(
    range: string
  ): Promise<JavaDownloadRelease> {
    // Add input validation
    if (!range || typeof range !== 'string') {
      throw new Error('Version range is required and must be a string');
    }

    const arch = this.distributionArchitecture();
    if (arch !== 'x64' && arch !== 'aarch64') {
      throw new Error(`Unsupported architecture: ${this.architecture}`);
    if (!SUPPORTED_ARCHITECTURES.includes(arch as SupportedArchitecture)) {
      throw new Error(
        `Unsupported architecture: ${this.architecture}. Supported architectures are: ${SUPPORTED_ARCHITECTURES.join(', ')}`
      );
    }

    if (!this.stable) {
@@ -75,52 +106,113 @@ export class GraalVMDistribution extends JavaBase {

    const platform = this.getPlatform();
    const extension = getDownloadArchiveExtension();
    let major;
    let fileUrl;
    if (range.includes('.')) {
      major = range.split('.')[0];
      fileUrl = `${GRAALVM_DL_BASE}/${major}/archive/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`;
    } else {
      major = range;
      fileUrl = `${GRAALVM_DL_BASE}/${range}/latest/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`;
    const major = range.includes('.') ? range.split('.')[0] : range;
    const majorVersion = parseInt(major);

    if (isNaN(majorVersion)) {
      throw new Error(`Invalid version format: ${range}`);
    }

    if (parseInt(major) < 17) {
      throw new Error('GraalVM is only supported for JDK 17 and later');
    if (majorVersion < GRAALVM_MIN_VERSION) {
      throw new Error(
        `GraalVM is only supported for JDK ${GRAALVM_MIN_VERSION} and later. Requested version: ${major}`
      );
    }

    const fileUrl = this.constructFileUrl(
      range,
      major,
      platform,
      arch,
      extension
    );

    const response = await this.http.head(fileUrl);
    this.handleHttpResponse(response, range);

    if (response.message.statusCode === HttpCodes.NotFound) {
      throw new Error(`Could not find GraalVM for SemVer ${range}`);
    return {url: fileUrl, version: range};
  }

  private constructFileUrl(
    range: string,
    major: string,
    platform: string,
    arch: string,
    extension: string
  ): string {
    return range.includes('.')
      ? `${GRAALVM_DL_BASE}/${major}/archive/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`
      : `${GRAALVM_DL_BASE}/${range}/latest/graalvm-jdk-${range}_${platform}-${arch}_bin.${extension}`;
  }

    if (response.message.statusCode !== HttpCodes.OK) {
  private handleHttpResponse(response: any, range: string): void {
    const statusCode = response.message.statusCode;

    if (statusCode === HttpCodes.NotFound) {
      throw new Error(
        `Http request for GraalVM failed with status code: ${response.message.statusCode}`
        `Could not find GraalVM for SemVer ${range}. Please check if this version is available at ${GRAALVM_DL_BASE}`
      );
    }

    return {url: fileUrl, version: range};
    if (
      statusCode === HttpCodes.Unauthorized ||
      statusCode === HttpCodes.Forbidden
    ) {
      throw new Error(
        `Access denied when downloading GraalVM. Status code: ${statusCode}. Please check your credentials or permissions.`
      );
    }

    if (statusCode !== HttpCodes.OK) {
      throw new Error(
        `HTTP request for GraalVM failed with status code: ${statusCode} (${response.message.statusMessage || 'Unknown error'})`
      );
    }
  }

  private async findEABuildDownloadUrl(
    javaEaVersion: string
  ): Promise<JavaDownloadRelease> {
    core.debug(`Searching for EA build: ${javaEaVersion}`);

    const versions = await this.fetchEAJson(javaEaVersion);
    core.debug(`Found ${versions.length} EA versions`);

    const latestVersion = versions.find(v => v.latest);
    if (!latestVersion) {
      core.error(
        `Available versions: ${versions.map(v => v.version).join(', ')}`
      );
      throw new Error(`Unable to find latest version for '${javaEaVersion}'`);
    }

    core.debug(`Latest version found: ${latestVersion.version}`);

    const arch = this.distributionArchitecture();
    const file = latestVersion.files.find(
      f => f.arch === arch && f.platform === GRAALVM_PLATFORM
    );
    if (!file || !file.filename.startsWith('graalvm-jdk-')) {
      throw new Error(`Unable to find file metadata for '${javaEaVersion}'`);

    if (!file) {
      core.error(
        `Available files for architecture ${arch}: ${JSON.stringify(latestVersion.files)}`
      );
      throw new Error(
        `Unable to find file for architecture '${arch}' and platform '${GRAALVM_PLATFORM}'`
      );
    }

    if (!file.filename.startsWith('graalvm-jdk-')) {
      throw new Error(
        `Invalid filename format: ${file.filename}. Expected to start with 'graalvm-jdk-'`
      );
    }

    const downloadUrl = `${latestVersion.download_base_url}${file.filename}`;
    core.debug(`Download URL: ${downloadUrl}`);

    return {
      url: `${latestVersion.download_base_url}${file.filename}`,
      url: downloadUrl,
      version: latestVersion.version
    };
  }
@@ -128,49 +220,59 @@ export class GraalVMDistribution extends JavaBase {
  private async fetchEAJson(
    javaEaVersion: string
  ): Promise<GraalVMEAVersion[]> {
    const owner = 'graalvm';
    const repository = 'oracle-graalvm-ea-builds';
    const branch = 'main';
    const filePath = `versions/${javaEaVersion}.json`;

    const url = `https://api.github.com/repos/${owner}/${repository}/contents/${filePath}?ref=${branch}`;

    const url = `https://api.github.com/repos/graalvm/oracle-graalvm-ea-builds/contents/versions/${javaEaVersion}.json?ref=main`;
    const headers = getGitHubHttpHeaders();

    core.debug(
      `Trying to fetch available version info for GraalVM EA builds from '${url}'`
    );
    let fetchedJson;

    try {
      fetchedJson = (await this.http.getJson<GraalVMEAVersion[]>(url, headers))
        .result;
    } catch (err) {
      throw Error(
        `Fetching version info for GraalVM EA builds from '${url}' failed with the error: ${
          (err as Error).message
        }`
      const response = await this.http.getJson<GraalVMEAVersion[]>(
        url,
        headers
      );

      if (!response.result) {
        throw new Error(
          `No GraalVM EA build found for version '${javaEaVersion}'. Please check if the version is correct.`
        );
      }
    if (fetchedJson === null) {
      throw Error(
        `No GraalVM EA build found. Are you sure java-version: '${javaEaVersion}' is correct?`

      return response.result;
    } catch (error) {
      if (error instanceof Error) {
        // Check if it's a 404 error (file not found)
        if (error.message?.includes('404')) {
          throw new Error(
            `GraalVM EA version '${javaEaVersion}' not found. Please verify the version exists in the EA builds repository.`
          );
        }
        // Re-throw with more context
        throw new Error(
          `Failed to fetch GraalVM EA version information for '${javaEaVersion}': ${error.message}`
        );
      }
      // If it's not an Error instance, throw a generic error
      throw new Error(
        `Failed to fetch GraalVM EA version information for '${javaEaVersion}'`
      );
    }
    return fetchedJson;
  }

  public getPlatform(platform: NodeJS.Platform = process.platform): OsVersions {
    switch (platform) {
      case 'darwin':
        return 'macos';
      case 'win32':
        return 'windows';
      case 'linux':
        return 'linux';
      default:
    const platformMap: Record<string, OsVersions> = {
      darwin: 'macos',
      win32: 'windows',
      linux: 'linux'
    };

    const result = platformMap[platform];
    if (!result) {
      throw new Error(
        `Platform '${platform}' is not supported. Supported platforms: 'linux', 'macos', 'windows'`
      );
    }
    return result;
  }
}
Loading