From 82496765f3aab08efd12141e61453ca4da26ceb9 Mon Sep 17 00:00:00 2001 From: Hideki Igarashi Date: Wed, 1 Dec 2021 23:15:29 +0900 Subject: [PATCH 01/18] Add tests for parseNodeVersionFile --- __tests__/installer.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/__tests__/installer.test.ts b/__tests__/installer.test.ts index f3eb8db..68767c0 100644 --- a/__tests__/installer.test.ts +++ b/__tests__/installer.test.ts @@ -7,6 +7,7 @@ import fs from 'fs'; import cp from 'child_process'; import osm = require('os'); import path from 'path'; +import each from 'jest-each'; import * as main from '../src/main'; import * as auth from '../src/authutil'; @@ -941,3 +942,21 @@ describe('setup-node', () => { ); }); }); + +describe('helper methods', () => { + describe('parseNodeVersionFile', () => { + each` + contents | expected + ${'12'} | ${'12'} + ${'12.3'} | ${'12.3'} + ${'12.3.4'} | ${'12.3.4'} + ${'v12.3.4'} | ${'12.3.4'} + ${'lts/erbium'} | ${'lts/erbium'} + ${'lts/*'} | ${'lts/*'} + ${''} | ${''} + ${'unknown format'} | ${'unknown format'} + `.it('parses "$contents"', ({contents, expected}) => { + expect(im.parseNodeVersionFile(contents)).toBe(expected); + }); + }); +}); From dbb64ac1d11fcab72e6fdc427c82d553fab565dc Mon Sep 17 00:00:00 2001 From: Hideki Igarashi Date: Thu, 2 Dec 2021 00:44:59 +0900 Subject: [PATCH 02/18] Add support for asdf format as Node.js version file --- .github/workflows/versions.yml | 3 ++- __tests__/data/.tool-versions | 1 + __tests__/installer.test.ts | 20 +++++++++++--------- action.yml | 2 +- dist/setup/index.js | 12 ++++++++---- docs/advanced-usage.md | 2 +- src/installer.ts | 12 ++++++++---- 7 files changed, 32 insertions(+), 20 deletions(-) create mode 100644 __tests__/data/.tool-versions diff --git a/.github/workflows/versions.yml b/.github/workflows/versions.yml index 3d8067b..926945c 100644 --- a/.github/workflows/versions.yml +++ b/.github/workflows/versions.yml @@ -84,12 +84,13 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] + node-version-file: [.nvmrc, .tool-versions] steps: - uses: actions/checkout@v3 - name: Setup node from node version file uses: ./ with: - node-version-file: '__tests__/data/.nvmrc' + node-version-file: '__tests__/data/${{ matrix.node-version-file }}' - name: Verify node run: __tests__/verify-node.sh 14 diff --git a/__tests__/data/.tool-versions b/__tests__/data/.tool-versions new file mode 100644 index 0000000..317343f --- /dev/null +++ b/__tests__/data/.tool-versions @@ -0,0 +1 @@ +nodejs 14.0.0 diff --git a/__tests__/installer.test.ts b/__tests__/installer.test.ts index 68767c0..f480947 100644 --- a/__tests__/installer.test.ts +++ b/__tests__/installer.test.ts @@ -946,15 +946,17 @@ describe('setup-node', () => { describe('helper methods', () => { describe('parseNodeVersionFile', () => { each` - contents | expected - ${'12'} | ${'12'} - ${'12.3'} | ${'12.3'} - ${'12.3.4'} | ${'12.3.4'} - ${'v12.3.4'} | ${'12.3.4'} - ${'lts/erbium'} | ${'lts/erbium'} - ${'lts/*'} | ${'lts/*'} - ${''} | ${''} - ${'unknown format'} | ${'unknown format'} + contents | expected + ${'12'} | ${'12'} + ${'12.3'} | ${'12.3'} + ${'12.3.4'} | ${'12.3.4'} + ${'v12.3.4'} | ${'12.3.4'} + ${'lts/erbium'} | ${'lts/erbium'} + ${'lts/*'} | ${'lts/*'} + ${'nodejs 12.3.4'} | ${'12.3.4'} + ${'ruby 2.3.4\nnodejs 12.3.4\npython 3.4.5'} | ${'12.3.4'} + ${''} | ${''} + ${'unknown format'} | ${'unknown format'} `.it('parses "$contents"', ({contents, expected}) => { expect(im.parseNodeVersionFile(contents)).toBe(expected); }); diff --git a/action.yml b/action.yml index 7bed73d..b4838e8 100644 --- a/action.yml +++ b/action.yml @@ -8,7 +8,7 @@ inputs: node-version: description: 'Version Spec of the version to use. Examples: 12.x, 10.15.1, >=10.15.0.' node-version-file: - description: 'File containing the version Spec of the version to use. Examples: .nvmrc, .node-version.' + description: 'File containing the version Spec of the version to use. Examples: .nvmrc, .node-version, .tool-versions.' architecture: description: 'Target architecture for Node to use. Examples: x86, x64. Will use system architecture by default.' check-latest: diff --git a/dist/setup/index.js b/dist/setup/index.js index fcafff7..2171253 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -70963,11 +70963,15 @@ function translateArchToDistUrl(arch) { } } function parseNodeVersionFile(contents) { - let nodeVersion = contents.trim(); - if (/^v\d/.test(nodeVersion)) { - nodeVersion = nodeVersion.substring(1); + var _a; + const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); + const nodeVersion = (_a = found === null || found === void 0 ? void 0 : found.groups) === null || _a === void 0 ? void 0 : _a.version; + if (nodeVersion) { + return nodeVersion; } - return nodeVersion; + // In the case of an unknown format, + // return as is and evaluate the version separately. + return contents.trim(); } exports.parseNodeVersionFile = parseNodeVersionFile; function isLatestSyntax(versionSpec) { diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md index 36c1ec8..cc068b3 100644 --- a/docs/advanced-usage.md +++ b/docs/advanced-usage.md @@ -56,7 +56,7 @@ steps: ## Node version file -The `node-version-file` input accepts a path to a file containing the version of Node.js to be used by a project, for example `.nvmrc` or `.node-version`. If both the `node-version` and the `node-version-file` inputs are provided then the `node-version` input is used. +The `node-version-file` input accepts a path to a file containing the version of Node.js to be used by a project, for example `.nvmrc`, `.node-version` or `.tool-versions`. If both the `node-version` and the `node-version-file` inputs are provided then the `node-version` input is used. See [supported version syntax](https://github.com/actions/setup-node#supported-version-syntax) > The action will search for the node version file relative to the repository root. diff --git a/src/installer.ts b/src/installer.ts index cd4619e..14429f4 100644 --- a/src/installer.ts +++ b/src/installer.ts @@ -487,12 +487,16 @@ function translateArchToDistUrl(arch: string): string { } export function parseNodeVersionFile(contents: string): string { - let nodeVersion = contents.trim(); + const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); + const nodeVersion = found?.groups?.version; - if (/^v\d/.test(nodeVersion)) { - nodeVersion = nodeVersion.substring(1); + if (nodeVersion) { + return nodeVersion; } - return nodeVersion; + + // In the case of an unknown format, + // return as is and evaluate the version separately. + return contents.trim(); } function isLatestSyntax(versionSpec): boolean { From 24301fe9fb18dd4b6b8e81b02d2f78ba73fd73c9 Mon Sep 17 00:00:00 2001 From: James Ottaway Date: Mon, 27 Jun 2022 09:28:13 +1000 Subject: [PATCH 03/18] docs: Include warning when configuring token to install private packages The distinction between `secrets.GITHUB_TOKEN` and `secrets.NPM_TOKEN` cost myself and a colleague numerous hours when we were trying to fix a GitHub Actions workflow which needed to install a private package from a different repository from our GitHub organisation. Given the issue dedicated to this point is closed, we should include a warning here to make it more clear why `secrets.GITHUB_TOKEN` will not work when passed to `npm ci`, in the presence of private packages from other GitHub Package repositories. --- docs/advanced-usage.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md index 36c1ec8..e51f8ab 100644 --- a/docs/advanced-usage.md +++ b/docs/advanced-usage.md @@ -247,3 +247,5 @@ steps: # `npm rebuild` will run all those post-install scripts for us. - run: npm rebuild && npm run prepare --if-present ``` + +NOTE: As per https://github.com/actions/setup-node/issues/49 you cannot use `secrets.GITHUB_TOKEN` to access private GitHub Packages within the same organisation. From 3ac35dad40f9a0c4bd67c2056da725c9c35f73a4 Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Thu, 30 Jun 2022 21:55:32 +0200 Subject: [PATCH 04/18] This PR adds `node-version` to the action output. This is present in e.g. setup-python https://github.com/actions/setup-python/blob/main/action.yml closes #150 --- action.yml | 2 ++ src/main.ts | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/action.yml b/action.yml index 7bed73d..a5e4877 100644 --- a/action.yml +++ b/action.yml @@ -30,6 +30,8 @@ inputs: outputs: cache-hit: description: 'A boolean value to indicate if a cache was hit.' + node-version: + description: 'The installed node version.' runs: using: 'node16' main: 'dist/setup/index.js' diff --git a/src/main.ts b/src/main.ts index 3c5661b..106de77 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,5 @@ import * as core from '@actions/core'; +import * as exec from '@actions/exec'; import * as installer from './installer'; import fs from 'fs'; import * as auth from './authutil'; @@ -39,6 +40,17 @@ export async function run() { await installer.getNode(version, stable, checkLatest, auth, arch); } + // Output version of node is being used + let installedVersion = ''; + await exec.exec('node', ['--version'], { + listeners: { + stdout: data => { + installedVersion += data.toString(); + } + } + }); + core.setOutput('node-version', installedVersion); + const registryUrl: string = core.getInput('registry-url'); const alwaysAuth: string = core.getInput('always-auth'); if (registryUrl) { From 0d7418813cbf1ba6305bfa852ba2eb2a44d52697 Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Fri, 1 Jul 2022 00:28:26 +0200 Subject: [PATCH 05/18] run build&format --- dist/cache-save/index.js | 376 +++++----- dist/setup/index.js | 1471 +++++++++++++++++++------------------- 2 files changed, 929 insertions(+), 918 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 219ef59..a55d232 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59827,74 +59827,74 @@ exports.fromPromise = function (fn) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(2186)); -const cache = __importStar(__nccwpck_require__(7799)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const constants_1 = __nccwpck_require__(9042); -const cache_utils_1 = __nccwpck_require__(1678); -// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in -// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to -// throw an uncaught exception. Instead of failing this action, just warn. -process.on('uncaughtException', e => { - const warningPrefix = '[warning]'; - core.info(`${warningPrefix}${e.message}`); -}); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - const cacheLock = core.getInput('cache'); - yield cachePackages(cacheLock); - } - catch (error) { - core.setFailed(error.message); - } - }); -} -exports.run = run; -const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const state = core.getState(constants_1.State.CacheMatchedKey); - const primaryKey = core.getState(constants_1.State.CachePrimaryKey); - const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); - if (!packageManagerInfo) { - core.debug(`Caching for '${packageManager}' is not supported`); - return; - } - const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); - if (!fs_1.default.existsSync(cachePath)) { - throw new Error(`Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}`); - } - if (primaryKey === state) { - core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`); - return; - } - const cacheId = yield cache.saveCache([cachePath], primaryKey); - if (cacheId == -1) { - return; - } - core.info(`Cache saved with the key: ${primaryKey}`); -}); -run(); + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const cache = __importStar(__nccwpck_require__(7799)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const constants_1 = __nccwpck_require__(9042); +const cache_utils_1 = __nccwpck_require__(1678); +// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in +// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to +// throw an uncaught exception. Instead of failing this action, just warn. +process.on('uncaughtException', e => { + const warningPrefix = '[warning]'; + core.info(`${warningPrefix}${e.message}`); +}); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + const cacheLock = core.getInput('cache'); + yield cachePackages(cacheLock); + } + catch (error) { + core.setFailed(error.message); + } + }); +} +exports.run = run; +const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { + const state = core.getState(constants_1.State.CacheMatchedKey); + const primaryKey = core.getState(constants_1.State.CachePrimaryKey); + const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); + if (!packageManagerInfo) { + core.debug(`Caching for '${packageManager}' is not supported`); + return; + } + const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); + if (!fs_1.default.existsSync(cachePath)) { + throw new Error(`Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}`); + } + if (primaryKey === state) { + core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`); + return; + } + const cacheId = yield cache.saveCache([cachePath], primaryKey); + if (cacheId == -1) { + return; + } + core.info(`Cache saved with the key: ${primaryKey}`); +}); +run(); /***/ }), @@ -59903,109 +59903,109 @@ run(); /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(2186)); -const exec = __importStar(__nccwpck_require__(1514)); -const cache = __importStar(__nccwpck_require__(7799)); -exports.supportedPackageManagers = { - npm: { - lockFilePatterns: ['package-lock.json', 'yarn.lock'], - getCacheFolderCommand: 'npm config get cache' - }, - pnpm: { - lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path' - }, - yarn1: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn cache dir' - }, - yarn2: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn config get cacheFolder' - } -}; -exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { - let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); - if (exitCode) { - stderr = !stderr.trim() - ? `The '${toolCommand}' command failed with exit code: ${exitCode}` - : stderr; - throw new Error(stderr); - } - return stdout.trim(); -}); -const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); - if (!stdOut) { - throw new Error(`Could not retrieve version of ${packageManager}`); - } - return stdOut; -}); -exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { - if (packageManager === 'npm') { - return exports.supportedPackageManagers.npm; - } - else if (packageManager === 'pnpm') { - return exports.supportedPackageManagers.pnpm; - } - else if (packageManager === 'yarn') { - const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); - core.debug(`Consumed yarn version is ${yarnVersion}`); - if (yarnVersion.startsWith('1.')) { - return exports.supportedPackageManagers.yarn1; - } - else { - return exports.supportedPackageManagers.yarn2; - } - } - else { - return null; - } -}); -exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); - if (!stdOut) { - throw new Error(`Could not get cache folder path for ${packageManager}`); - } - core.debug(`${packageManager} path is ${stdOut}`); - return stdOut; -}); -function isGhes() { - const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; -} -exports.isGhes = isGhes; -function isCacheFeatureAvailable() { - if (!cache.isFeatureAvailable()) { - if (isGhes()) { - throw new Error('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); - } - else { - core.warning('The runner was not able to contact the cache service. Caching will be skipped'); - } - return false; - } - return true; -} -exports.isCacheFeatureAvailable = isCacheFeatureAvailable; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const cache = __importStar(__nccwpck_require__(7799)); +exports.supportedPackageManagers = { + npm: { + lockFilePatterns: ['package-lock.json', 'yarn.lock'], + getCacheFolderCommand: 'npm config get cache' + }, + pnpm: { + lockFilePatterns: ['pnpm-lock.yaml'], + getCacheFolderCommand: 'pnpm store path' + }, + yarn1: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn cache dir' + }, + yarn2: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn config get cacheFolder' + } +}; +exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { + let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); + if (exitCode) { + stderr = !stderr.trim() + ? `The '${toolCommand}' command failed with exit code: ${exitCode}` + : stderr; + throw new Error(stderr); + } + return stdout.trim(); +}); +const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); + if (!stdOut) { + throw new Error(`Could not retrieve version of ${packageManager}`); + } + return stdOut; +}); +exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { + if (packageManager === 'npm') { + return exports.supportedPackageManagers.npm; + } + else if (packageManager === 'pnpm') { + return exports.supportedPackageManagers.pnpm; + } + else if (packageManager === 'yarn') { + const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); + core.debug(`Consumed yarn version is ${yarnVersion}`); + if (yarnVersion.startsWith('1.')) { + return exports.supportedPackageManagers.yarn1; + } + else { + return exports.supportedPackageManagers.yarn2; + } + } + else { + return null; + } +}); +exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); + if (!stdOut) { + throw new Error(`Could not get cache folder path for ${packageManager}`); + } + core.debug(`${packageManager} path is ${stdOut}`); + return stdOut; +}); +function isGhes() { + const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +exports.isGhes = isGhes; +function isCacheFeatureAvailable() { + if (!cache.isFeatureAvailable()) { + if (isGhes()) { + throw new Error('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); + } + else { + core.warning('The runner was not able to contact the cache service. Caching will be skipped'); + } + return false; + } + return true; +} +exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ }), @@ -60014,23 +60014,23 @@ exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var LockType; -(function (LockType) { - LockType["Npm"] = "npm"; - LockType["Pnpm"] = "pnpm"; - LockType["Yarn"] = "yarn"; -})(LockType = exports.LockType || (exports.LockType = {})); -var State; -(function (State) { - State["CachePrimaryKey"] = "CACHE_KEY"; - State["CacheMatchedKey"] = "CACHE_RESULT"; -})(State = exports.State || (exports.State = {})); -var Outputs; -(function (Outputs) { - Outputs["CacheHit"] = "cache-hit"; -})(Outputs = exports.Outputs || (exports.Outputs = {})); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var LockType; +(function (LockType) { + LockType["Npm"] = "npm"; + LockType["Pnpm"] = "pnpm"; + LockType["Yarn"] = "yarn"; +})(LockType = exports.LockType || (exports.LockType = {})); +var State; +(function (State) { + State["CachePrimaryKey"] = "CACHE_KEY"; + State["CacheMatchedKey"] = "CACHE_RESULT"; +})(State = exports.State || (exports.State = {})); +var Outputs; +(function (Outputs) { + Outputs["CacheHit"] = "cache-hit"; +})(Outputs = exports.Outputs || (exports.Outputs = {})); /***/ }), diff --git a/dist/setup/index.js b/dist/setup/index.js index 1b24939..6806461 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71113,62 +71113,62 @@ function wrappy (fn, cb) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs = __importStar(__nccwpck_require__(7147)); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const core = __importStar(__nccwpck_require__(2186)); -const github = __importStar(__nccwpck_require__(5438)); -function configAuthentication(registryUrl, alwaysAuth) { - const npmrc = path.resolve(process.env['RUNNER_TEMP'] || process.cwd(), '.npmrc'); - if (!registryUrl.endsWith('/')) { - registryUrl += '/'; - } - writeRegistryToFile(registryUrl, npmrc, alwaysAuth); -} -exports.configAuthentication = configAuthentication; -function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) { - let scope = core.getInput('scope'); - if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) { - scope = github.context.repo.owner; - } - if (scope && scope[0] != '@') { - scope = '@' + scope; - } - if (scope) { - scope = scope.toLowerCase(); - } - core.debug(`Setting auth in ${fileLocation}`); - let newContents = ''; - if (fs.existsSync(fileLocation)) { - const curContents = fs.readFileSync(fileLocation, 'utf8'); - curContents.split(os.EOL).forEach((line) => { - // Add current contents unless they are setting the registry - if (!line.toLowerCase().startsWith('registry')) { - newContents += line + os.EOL; - } - }); - } - // Remove http: or https: from front of registry. - const authString = registryUrl.replace(/(^\w+:|^)/, '') + ':_authToken=${NODE_AUTH_TOKEN}'; - const registryString = scope - ? `${scope}:registry=${registryUrl}` - : `registry=${registryUrl}`; - const alwaysAuthString = `always-auth=${alwaysAuth}`; - newContents += `${authString}${os.EOL}${registryString}${os.EOL}${alwaysAuthString}`; - fs.writeFileSync(fileLocation, newContents); - core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation); - // Export empty node_auth_token if didn't exist so npm doesn't complain about not being able to find it - core.exportVariable('NODE_AUTH_TOKEN', process.env.NODE_AUTH_TOKEN || 'XXXXX-XXXXX-XXXXX-XXXXX'); -} + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fs = __importStar(__nccwpck_require__(7147)); +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +function configAuthentication(registryUrl, alwaysAuth) { + const npmrc = path.resolve(process.env['RUNNER_TEMP'] || process.cwd(), '.npmrc'); + if (!registryUrl.endsWith('/')) { + registryUrl += '/'; + } + writeRegistryToFile(registryUrl, npmrc, alwaysAuth); +} +exports.configAuthentication = configAuthentication; +function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) { + let scope = core.getInput('scope'); + if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) { + scope = github.context.repo.owner; + } + if (scope && scope[0] != '@') { + scope = '@' + scope; + } + if (scope) { + scope = scope.toLowerCase(); + } + core.debug(`Setting auth in ${fileLocation}`); + let newContents = ''; + if (fs.existsSync(fileLocation)) { + const curContents = fs.readFileSync(fileLocation, 'utf8'); + curContents.split(os.EOL).forEach((line) => { + // Add current contents unless they are setting the registry + if (!line.toLowerCase().startsWith('registry')) { + newContents += line + os.EOL; + } + }); + } + // Remove http: or https: from front of registry. + const authString = registryUrl.replace(/(^\w+:|^)/, '') + ':_authToken=${NODE_AUTH_TOKEN}'; + const registryString = scope + ? `${scope}:registry=${registryUrl}` + : `registry=${registryUrl}`; + const alwaysAuthString = `always-auth=${alwaysAuth}`; + newContents += `${authString}${os.EOL}${registryString}${os.EOL}${alwaysAuthString}`; + fs.writeFileSync(fileLocation, newContents); + core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation); + // Export empty node_auth_token if didn't exist so npm doesn't complain about not being able to find it + core.exportVariable('NODE_AUTH_TOKEN', process.env.NODE_AUTH_TOKEN || 'XXXXX-XXXXX-XXXXX-XXXXX'); +} /***/ }), @@ -71177,70 +71177,70 @@ function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const cache = __importStar(__nccwpck_require__(7799)); -const core = __importStar(__nccwpck_require__(2186)); -const glob = __importStar(__nccwpck_require__(8090)); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const constants_1 = __nccwpck_require__(9042); -const cache_utils_1 = __nccwpck_require__(1678); -exports.restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { - const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); - if (!packageManagerInfo) { - throw new Error(`Caching for '${packageManager}' is not supported`); - } - const platform = process.env.RUNNER_OS; - const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); - const lockFilePath = cacheDependencyPath - ? cacheDependencyPath - : findLockFile(packageManagerInfo); - const fileHash = yield glob.hashFiles(lockFilePath); - if (!fileHash) { - throw new Error('Some specified paths were not resolved, unable to cache dependencies.'); - } - const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; - core.debug(`primary key is ${primaryKey}`); - core.saveState(constants_1.State.CachePrimaryKey, primaryKey); - const cacheKey = yield cache.restoreCache([cachePath], primaryKey); - core.setOutput('cache-hit', Boolean(cacheKey)); - if (!cacheKey) { - core.info(`${packageManager} cache is not found`); - return; - } - core.saveState(constants_1.State.CacheMatchedKey, cacheKey); - core.info(`Cache restored from key: ${cacheKey}`); -}); -const findLockFile = (packageManager) => { - let lockFiles = packageManager.lockFilePatterns; - const workspace = process.env.GITHUB_WORKSPACE; - const rootContent = fs_1.default.readdirSync(workspace); - const lockFile = lockFiles.find(item => rootContent.includes(item)); - if (!lockFile) { - throw new Error(`Dependencies lock file is not found in ${workspace}. Supported file patterns: ${lockFiles.toString()}`); - } - return path_1.default.join(workspace, lockFile); -}; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const cache = __importStar(__nccwpck_require__(7799)); +const core = __importStar(__nccwpck_require__(2186)); +const glob = __importStar(__nccwpck_require__(8090)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const constants_1 = __nccwpck_require__(9042); +const cache_utils_1 = __nccwpck_require__(1678); +exports.restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { + const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); + if (!packageManagerInfo) { + throw new Error(`Caching for '${packageManager}' is not supported`); + } + const platform = process.env.RUNNER_OS; + const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); + const lockFilePath = cacheDependencyPath + ? cacheDependencyPath + : findLockFile(packageManagerInfo); + const fileHash = yield glob.hashFiles(lockFilePath); + if (!fileHash) { + throw new Error('Some specified paths were not resolved, unable to cache dependencies.'); + } + const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; + core.debug(`primary key is ${primaryKey}`); + core.saveState(constants_1.State.CachePrimaryKey, primaryKey); + const cacheKey = yield cache.restoreCache([cachePath], primaryKey); + core.setOutput('cache-hit', Boolean(cacheKey)); + if (!cacheKey) { + core.info(`${packageManager} cache is not found`); + return; + } + core.saveState(constants_1.State.CacheMatchedKey, cacheKey); + core.info(`Cache restored from key: ${cacheKey}`); +}); +const findLockFile = (packageManager) => { + let lockFiles = packageManager.lockFilePatterns; + const workspace = process.env.GITHUB_WORKSPACE; + const rootContent = fs_1.default.readdirSync(workspace); + const lockFile = lockFiles.find(item => rootContent.includes(item)); + if (!lockFile) { + throw new Error(`Dependencies lock file is not found in ${workspace}. Supported file patterns: ${lockFiles.toString()}`); + } + return path_1.default.join(workspace, lockFile); +}; /***/ }), @@ -71249,109 +71249,109 @@ const findLockFile = (packageManager) => { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(2186)); -const exec = __importStar(__nccwpck_require__(1514)); -const cache = __importStar(__nccwpck_require__(7799)); -exports.supportedPackageManagers = { - npm: { - lockFilePatterns: ['package-lock.json', 'yarn.lock'], - getCacheFolderCommand: 'npm config get cache' - }, - pnpm: { - lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path' - }, - yarn1: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn cache dir' - }, - yarn2: { - lockFilePatterns: ['yarn.lock'], - getCacheFolderCommand: 'yarn config get cacheFolder' - } -}; -exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { - let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); - if (exitCode) { - stderr = !stderr.trim() - ? `The '${toolCommand}' command failed with exit code: ${exitCode}` - : stderr; - throw new Error(stderr); - } - return stdout.trim(); -}); -const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); - if (!stdOut) { - throw new Error(`Could not retrieve version of ${packageManager}`); - } - return stdOut; -}); -exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { - if (packageManager === 'npm') { - return exports.supportedPackageManagers.npm; - } - else if (packageManager === 'pnpm') { - return exports.supportedPackageManagers.pnpm; - } - else if (packageManager === 'yarn') { - const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); - core.debug(`Consumed yarn version is ${yarnVersion}`); - if (yarnVersion.startsWith('1.')) { - return exports.supportedPackageManagers.yarn1; - } - else { - return exports.supportedPackageManagers.yarn2; - } - } - else { - return null; - } -}); -exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { - const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); - if (!stdOut) { - throw new Error(`Could not get cache folder path for ${packageManager}`); - } - core.debug(`${packageManager} path is ${stdOut}`); - return stdOut; -}); -function isGhes() { - const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; -} -exports.isGhes = isGhes; -function isCacheFeatureAvailable() { - if (!cache.isFeatureAvailable()) { - if (isGhes()) { - throw new Error('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); - } - else { - core.warning('The runner was not able to contact the cache service. Caching will be skipped'); - } - return false; - } - return true; -} -exports.isCacheFeatureAvailable = isCacheFeatureAvailable; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const cache = __importStar(__nccwpck_require__(7799)); +exports.supportedPackageManagers = { + npm: { + lockFilePatterns: ['package-lock.json', 'yarn.lock'], + getCacheFolderCommand: 'npm config get cache' + }, + pnpm: { + lockFilePatterns: ['pnpm-lock.yaml'], + getCacheFolderCommand: 'pnpm store path' + }, + yarn1: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn cache dir' + }, + yarn2: { + lockFilePatterns: ['yarn.lock'], + getCacheFolderCommand: 'yarn config get cacheFolder' + } +}; +exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { + let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); + if (exitCode) { + stderr = !stderr.trim() + ? `The '${toolCommand}' command failed with exit code: ${exitCode}` + : stderr; + throw new Error(stderr); + } + return stdout.trim(); +}); +const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); + if (!stdOut) { + throw new Error(`Could not retrieve version of ${packageManager}`); + } + return stdOut; +}); +exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { + if (packageManager === 'npm') { + return exports.supportedPackageManagers.npm; + } + else if (packageManager === 'pnpm') { + return exports.supportedPackageManagers.pnpm; + } + else if (packageManager === 'yarn') { + const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); + core.debug(`Consumed yarn version is ${yarnVersion}`); + if (yarnVersion.startsWith('1.')) { + return exports.supportedPackageManagers.yarn1; + } + else { + return exports.supportedPackageManagers.yarn2; + } + } + else { + return null; + } +}); +exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { + const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); + if (!stdOut) { + throw new Error(`Could not get cache folder path for ${packageManager}`); + } + core.debug(`${packageManager} path is ${stdOut}`); + return stdOut; +}); +function isGhes() { + const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +exports.isGhes = isGhes; +function isCacheFeatureAvailable() { + if (!cache.isFeatureAvailable()) { + if (isGhes()) { + throw new Error('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); + } + else { + core.warning('The runner was not able to contact the cache service. Caching will be skipped'); + } + return false; + } + return true; +} +exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ }), @@ -71360,23 +71360,23 @@ exports.isCacheFeatureAvailable = isCacheFeatureAvailable; /***/ ((__unused_webpack_module, exports) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var LockType; -(function (LockType) { - LockType["Npm"] = "npm"; - LockType["Pnpm"] = "pnpm"; - LockType["Yarn"] = "yarn"; -})(LockType = exports.LockType || (exports.LockType = {})); -var State; -(function (State) { - State["CachePrimaryKey"] = "CACHE_KEY"; - State["CacheMatchedKey"] = "CACHE_RESULT"; -})(State = exports.State || (exports.State = {})); -var Outputs; -(function (Outputs) { - Outputs["CacheHit"] = "cache-hit"; -})(Outputs = exports.Outputs || (exports.Outputs = {})); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var LockType; +(function (LockType) { + LockType["Npm"] = "npm"; + LockType["Pnpm"] = "pnpm"; + LockType["Yarn"] = "yarn"; +})(LockType = exports.LockType || (exports.LockType = {})); +var State; +(function (State) { + State["CachePrimaryKey"] = "CACHE_KEY"; + State["CacheMatchedKey"] = "CACHE_RESULT"; +})(State = exports.State || (exports.State = {})); +var Outputs; +(function (Outputs) { + Outputs["CacheHit"] = "cache-hit"; +})(Outputs = exports.Outputs || (exports.Outputs = {})); /***/ }), @@ -71385,399 +71385,399 @@ var Outputs; /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const os = __nccwpck_require__(2037); -const assert = __importStar(__nccwpck_require__(9491)); -const core = __importStar(__nccwpck_require__(2186)); -const hc = __importStar(__nccwpck_require__(9925)); -const io = __importStar(__nccwpck_require__(7436)); -const tc = __importStar(__nccwpck_require__(7784)); -const path = __importStar(__nccwpck_require__(1017)); -const semver = __importStar(__nccwpck_require__(5911)); -const fs = __nccwpck_require__(7147); -function getNode(versionSpec, stable, checkLatest, auth, arch = os.arch()) { - return __awaiter(this, void 0, void 0, function* () { - // Store manifest data to avoid multiple calls - let manifest; - let nodeVersions; - let osPlat = os.platform(); - let osArch = translateArchToDistUrl(arch); - if (isLtsAlias(versionSpec)) { - core.info('Attempt to resolve LTS alias from manifest...'); - // No try-catch since it's not possible to resolve LTS alias without manifest - manifest = yield getManifest(auth); - versionSpec = resolveLtsAliasFromManifest(versionSpec, stable, manifest); - } - if (isLatestSyntax(versionSpec)) { - nodeVersions = yield getVersionsFromDist(); - versionSpec = yield queryDistForMatch(versionSpec, arch, nodeVersions); - core.info(`getting latest node version...`); - } - if (checkLatest) { - core.info('Attempt to resolve the latest version from manifest...'); - const resolvedVersion = yield resolveVersionFromManifest(versionSpec, stable, auth, osArch, manifest); - if (resolvedVersion) { - versionSpec = resolvedVersion; - core.info(`Resolved as '${versionSpec}'`); - } - else { - core.info(`Failed to resolve version ${versionSpec} from manifest`); - } - } - // check cache - let toolPath; - toolPath = tc.find('node', versionSpec, osArch); - // If not found in cache, download - if (toolPath) { - core.info(`Found in cache @ ${toolPath}`); - } - else { - core.info(`Attempting to download ${versionSpec}...`); - let downloadPath = ''; - let info = null; - // - // Try download from internal distribution (popular versions only) - // - try { - info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest); - if (info) { - core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); - downloadPath = yield tc.downloadTool(info.downloadUrl, undefined, auth); - } - else { - core.info('Not found in manifest. Falling back to download directly from Node'); - } - } - catch (err) { - // Rate limit? - if (err instanceof tc.HTTPError && - (err.httpStatusCode === 403 || err.httpStatusCode === 429)) { - core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`); - } - else { - core.info(err.message); - } - core.debug(err.stack); - core.info('Falling back to download directly from Node'); - } - // - // Download from nodejs.org - // - if (!downloadPath) { - info = yield getInfoFromDist(versionSpec, arch, nodeVersions); - if (!info) { - throw new Error(`Unable to find Node version '${versionSpec}' for platform ${osPlat} and architecture ${osArch}.`); - } - core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); - try { - downloadPath = yield tc.downloadTool(info.downloadUrl); - } - catch (err) { - if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { - return yield acquireNodeFromFallbackLocation(info.resolvedVersion, info.arch); - } - throw err; - } - } - // - // Extract - // - core.info('Extracting ...'); - let extPath; - info = info || {}; // satisfy compiler, never null when reaches here - if (osPlat == 'win32') { - let _7zPath = path.join(__dirname, '../..', 'externals', '7zr.exe'); - extPath = yield tc.extract7z(downloadPath, undefined, _7zPath); - // 7z extracts to folder matching file name - let nestedPath = path.join(extPath, path.basename(info.fileName, '.7z')); - if (fs.existsSync(nestedPath)) { - extPath = nestedPath; - } - } - else { - extPath = yield tc.extractTar(downloadPath, undefined, [ - 'xz', - '--strip', - '1' - ]); - } - // - // Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded - // - core.info('Adding to the cache ...'); - toolPath = yield tc.cacheDir(extPath, 'node', info.resolvedVersion, info.arch); - core.info('Done'); - } - // - // a tool installer initimately knows details about the layout of that tool - // for example, node binary is in the bin folder after the extract on Mac/Linux. - // layouts could change by version, by platform etc... but that's the tool installers job - // - if (osPlat != 'win32') { - toolPath = path.join(toolPath, 'bin'); - } - // - // prepend the tools path. instructs the agent to prepend for future tasks - core.addPath(toolPath); - }); -} -exports.getNode = getNode; -function isLtsAlias(versionSpec) { - return versionSpec.startsWith('lts/'); -} -function getManifest(auth) { - core.debug('Getting manifest from actions/node-versions@main'); - return tc.getManifestFromRepo('actions', 'node-versions', auth, 'main'); -} -function resolveLtsAliasFromManifest(versionSpec, stable, manifest) { - var _a; - const alias = (_a = versionSpec.split('lts/')[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); - if (!alias) { - throw new Error(`Unable to parse LTS alias for Node version '${versionSpec}'`); - } - core.debug(`LTS alias '${alias}' for Node version '${versionSpec}'`); - // Supported formats are `lts/`, `lts/*`, and `lts/-n`. Where asterisk means highest possible LTS and -n means the nth-highest. - const n = Number(alias); - const aliases = Object.fromEntries(manifest - .filter(x => x.lts && x.stable === stable) - .map(x => [x.lts.toLowerCase(), x]) - .reverse()); - const numbered = Object.values(aliases); - const release = alias === '*' - ? numbered[numbered.length - 1] - : n < 0 - ? numbered[numbered.length - 1 + n] - : aliases[alias]; - if (!release) { - throw new Error(`Unable to find LTS release '${alias}' for Node version '${versionSpec}'.`); - } - core.debug(`Found LTS release '${release.version}' for Node version '${versionSpec}'`); - return release.version.split('.')[0]; -} -function getInfoFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os.arch()), manifest) { - return __awaiter(this, void 0, void 0, function* () { - let info = null; - if (!manifest) { - core.debug('No manifest cached'); - manifest = yield getManifest(auth); - } - const rel = yield tc.findFromManifest(versionSpec, stable, manifest, osArch); - if (rel && rel.files.length > 0) { - info = {}; - info.resolvedVersion = rel.version; - info.arch = rel.files[0].arch; - info.downloadUrl = rel.files[0].download_url; - info.fileName = rel.files[0].filename; - } - return info; - }); -} -function getInfoFromDist(versionSpec, arch = os.arch(), nodeVersions) { - return __awaiter(this, void 0, void 0, function* () { - let osPlat = os.platform(); - let osArch = translateArchToDistUrl(arch); - let version = yield queryDistForMatch(versionSpec, arch, nodeVersions); - if (!version) { - return null; - } - // - // Download - a tool installer intimately knows how to get the tool (and construct urls) - // - version = semver.clean(version) || ''; - let fileName = osPlat == 'win32' - ? `node-v${version}-win-${osArch}` - : `node-v${version}-${osPlat}-${osArch}`; - let urlFileName = osPlat == 'win32' ? `${fileName}.7z` : `${fileName}.tar.gz`; - let url = `https://nodejs.org/dist/v${version}/${urlFileName}`; - return { - downloadUrl: url, - resolvedVersion: version, - arch: arch, - fileName: fileName - }; - }); -} -function resolveVersionFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os.arch()), manifest) { - return __awaiter(this, void 0, void 0, function* () { - try { - const info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest); - return info === null || info === void 0 ? void 0 : info.resolvedVersion; - } - catch (err) { - core.info('Unable to resolve version from manifest...'); - core.debug(err.message); - } - }); -} -// TODO - should we just export this from @actions/tool-cache? Lifted directly from there -function evaluateVersions(versions, versionSpec) { - let version = ''; - core.debug(`evaluating ${versions.length} versions`); - versions = versions.sort((a, b) => { - if (semver.gt(a, b)) { - return 1; - } - return -1; - }); - for (let i = versions.length - 1; i >= 0; i--) { - const potential = versions[i]; - const satisfied = semver.satisfies(potential, versionSpec); - if (satisfied) { - version = potential; - break; - } - } - if (version) { - core.debug(`matched: ${version}`); - } - else { - core.debug('match not found'); - } - return version; -} -function queryDistForMatch(versionSpec, arch = os.arch(), nodeVersions) { - return __awaiter(this, void 0, void 0, function* () { - let osPlat = os.platform(); - let osArch = translateArchToDistUrl(arch); - // node offers a json list of versions - let dataFileName; - switch (osPlat) { - case 'linux': - dataFileName = `linux-${osArch}`; - break; - case 'darwin': - dataFileName = `osx-${osArch}-tar`; - break; - case 'win32': - dataFileName = `win-${osArch}-exe`; - break; - default: - throw new Error(`Unexpected OS '${osPlat}'`); - } - if (!nodeVersions) { - core.debug('No dist manifest cached'); - nodeVersions = yield getVersionsFromDist(); - } - let versions = []; - if (isLatestSyntax(versionSpec)) { - core.info(`getting latest node version...`); - return nodeVersions[0].version; - } - nodeVersions.forEach((nodeVersion) => { - // ensure this version supports your os and platform - if (nodeVersion.files.indexOf(dataFileName) >= 0) { - versions.push(nodeVersion.version); - } - }); - // get the latest version that matches the version spec - let version = evaluateVersions(versions, versionSpec); - return version; - }); -} -function getVersionsFromDist() { - return __awaiter(this, void 0, void 0, function* () { - let dataUrl = 'https://nodejs.org/dist/index.json'; - let httpClient = new hc.HttpClient('setup-node', [], { - allowRetries: true, - maxRetries: 3 - }); - let response = yield httpClient.getJson(dataUrl); - return response.result || []; - }); -} -exports.getVersionsFromDist = getVersionsFromDist; -// For non LTS versions of Node, the files we need (for Windows) are sometimes located -// in a different folder than they normally are for other versions. -// Normally the format is similar to: https://nodejs.org/dist/v5.10.1/node-v5.10.1-win-x64.7z -// In this case, there will be two files located at: -// /dist/v5.10.1/win-x64/node.exe -// /dist/v5.10.1/win-x64/node.lib -// If this is not the structure, there may also be two files located at: -// /dist/v0.12.18/node.exe -// /dist/v0.12.18/node.lib -// This method attempts to download and cache the resources from these alternative locations. -// Note also that the files are normally zipped but in this case they are just an exe -// and lib file in a folder, not zipped. -function acquireNodeFromFallbackLocation(version, arch = os.arch()) { - return __awaiter(this, void 0, void 0, function* () { - let osPlat = os.platform(); - let osArch = translateArchToDistUrl(arch); - // Create temporary folder to download in to - const tempDownloadFolder = 'temp_' + Math.floor(Math.random() * 2000000000); - const tempDirectory = process.env['RUNNER_TEMP'] || ''; - assert.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); - const tempDir = path.join(tempDirectory, tempDownloadFolder); - yield io.mkdirP(tempDir); - let exeUrl; - let libUrl; - try { - exeUrl = `https://nodejs.org/dist/v${version}/win-${osArch}/node.exe`; - libUrl = `https://nodejs.org/dist/v${version}/win-${osArch}/node.lib`; - core.info(`Downloading only node binary from ${exeUrl}`); - const exePath = yield tc.downloadTool(exeUrl); - yield io.cp(exePath, path.join(tempDir, 'node.exe')); - const libPath = yield tc.downloadTool(libUrl); - yield io.cp(libPath, path.join(tempDir, 'node.lib')); - } - catch (err) { - if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { - exeUrl = `https://nodejs.org/dist/v${version}/node.exe`; - libUrl = `https://nodejs.org/dist/v${version}/node.lib`; - const exePath = yield tc.downloadTool(exeUrl); - yield io.cp(exePath, path.join(tempDir, 'node.exe')); - const libPath = yield tc.downloadTool(libUrl); - yield io.cp(libPath, path.join(tempDir, 'node.lib')); - } - else { - throw err; - } - } - let toolPath = yield tc.cacheDir(tempDir, 'node', version, arch); - core.addPath(toolPath); - return toolPath; - }); -} -// os.arch does not always match the relative download url, e.g. -// os.arch == 'arm' != node-v12.13.1-linux-armv7l.tar.gz -// All other currently supported architectures match, e.g.: -// os.arch = arm64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-arm64.tar.gz -// os.arch = x64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-x64.tar.gz -function translateArchToDistUrl(arch) { - switch (arch) { - case 'arm': - return 'armv7l'; - default: - return arch; - } -} -function parseNodeVersionFile(contents) { - let nodeVersion = contents.trim(); - if (/^v\d/.test(nodeVersion)) { - nodeVersion = nodeVersion.substring(1); - } - return nodeVersion; -} -exports.parseNodeVersionFile = parseNodeVersionFile; -function isLatestSyntax(versionSpec) { - return ['current', 'latest', 'node'].includes(versionSpec); -} + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const os = __nccwpck_require__(2037); +const assert = __importStar(__nccwpck_require__(9491)); +const core = __importStar(__nccwpck_require__(2186)); +const hc = __importStar(__nccwpck_require__(9925)); +const io = __importStar(__nccwpck_require__(7436)); +const tc = __importStar(__nccwpck_require__(7784)); +const path = __importStar(__nccwpck_require__(1017)); +const semver = __importStar(__nccwpck_require__(5911)); +const fs = __nccwpck_require__(7147); +function getNode(versionSpec, stable, checkLatest, auth, arch = os.arch()) { + return __awaiter(this, void 0, void 0, function* () { + // Store manifest data to avoid multiple calls + let manifest; + let nodeVersions; + let osPlat = os.platform(); + let osArch = translateArchToDistUrl(arch); + if (isLtsAlias(versionSpec)) { + core.info('Attempt to resolve LTS alias from manifest...'); + // No try-catch since it's not possible to resolve LTS alias without manifest + manifest = yield getManifest(auth); + versionSpec = resolveLtsAliasFromManifest(versionSpec, stable, manifest); + } + if (isLatestSyntax(versionSpec)) { + nodeVersions = yield getVersionsFromDist(); + versionSpec = yield queryDistForMatch(versionSpec, arch, nodeVersions); + core.info(`getting latest node version...`); + } + if (checkLatest) { + core.info('Attempt to resolve the latest version from manifest...'); + const resolvedVersion = yield resolveVersionFromManifest(versionSpec, stable, auth, osArch, manifest); + if (resolvedVersion) { + versionSpec = resolvedVersion; + core.info(`Resolved as '${versionSpec}'`); + } + else { + core.info(`Failed to resolve version ${versionSpec} from manifest`); + } + } + // check cache + let toolPath; + toolPath = tc.find('node', versionSpec, osArch); + // If not found in cache, download + if (toolPath) { + core.info(`Found in cache @ ${toolPath}`); + } + else { + core.info(`Attempting to download ${versionSpec}...`); + let downloadPath = ''; + let info = null; + // + // Try download from internal distribution (popular versions only) + // + try { + info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest); + if (info) { + core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); + downloadPath = yield tc.downloadTool(info.downloadUrl, undefined, auth); + } + else { + core.info('Not found in manifest. Falling back to download directly from Node'); + } + } + catch (err) { + // Rate limit? + if (err instanceof tc.HTTPError && + (err.httpStatusCode === 403 || err.httpStatusCode === 429)) { + core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`); + } + else { + core.info(err.message); + } + core.debug(err.stack); + core.info('Falling back to download directly from Node'); + } + // + // Download from nodejs.org + // + if (!downloadPath) { + info = yield getInfoFromDist(versionSpec, arch, nodeVersions); + if (!info) { + throw new Error(`Unable to find Node version '${versionSpec}' for platform ${osPlat} and architecture ${osArch}.`); + } + core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); + try { + downloadPath = yield tc.downloadTool(info.downloadUrl); + } + catch (err) { + if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { + return yield acquireNodeFromFallbackLocation(info.resolvedVersion, info.arch); + } + throw err; + } + } + // + // Extract + // + core.info('Extracting ...'); + let extPath; + info = info || {}; // satisfy compiler, never null when reaches here + if (osPlat == 'win32') { + let _7zPath = path.join(__dirname, '../..', 'externals', '7zr.exe'); + extPath = yield tc.extract7z(downloadPath, undefined, _7zPath); + // 7z extracts to folder matching file name + let nestedPath = path.join(extPath, path.basename(info.fileName, '.7z')); + if (fs.existsSync(nestedPath)) { + extPath = nestedPath; + } + } + else { + extPath = yield tc.extractTar(downloadPath, undefined, [ + 'xz', + '--strip', + '1' + ]); + } + // + // Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded + // + core.info('Adding to the cache ...'); + toolPath = yield tc.cacheDir(extPath, 'node', info.resolvedVersion, info.arch); + core.info('Done'); + } + // + // a tool installer initimately knows details about the layout of that tool + // for example, node binary is in the bin folder after the extract on Mac/Linux. + // layouts could change by version, by platform etc... but that's the tool installers job + // + if (osPlat != 'win32') { + toolPath = path.join(toolPath, 'bin'); + } + // + // prepend the tools path. instructs the agent to prepend for future tasks + core.addPath(toolPath); + }); +} +exports.getNode = getNode; +function isLtsAlias(versionSpec) { + return versionSpec.startsWith('lts/'); +} +function getManifest(auth) { + core.debug('Getting manifest from actions/node-versions@main'); + return tc.getManifestFromRepo('actions', 'node-versions', auth, 'main'); +} +function resolveLtsAliasFromManifest(versionSpec, stable, manifest) { + var _a; + const alias = (_a = versionSpec.split('lts/')[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + if (!alias) { + throw new Error(`Unable to parse LTS alias for Node version '${versionSpec}'`); + } + core.debug(`LTS alias '${alias}' for Node version '${versionSpec}'`); + // Supported formats are `lts/`, `lts/*`, and `lts/-n`. Where asterisk means highest possible LTS and -n means the nth-highest. + const n = Number(alias); + const aliases = Object.fromEntries(manifest + .filter(x => x.lts && x.stable === stable) + .map(x => [x.lts.toLowerCase(), x]) + .reverse()); + const numbered = Object.values(aliases); + const release = alias === '*' + ? numbered[numbered.length - 1] + : n < 0 + ? numbered[numbered.length - 1 + n] + : aliases[alias]; + if (!release) { + throw new Error(`Unable to find LTS release '${alias}' for Node version '${versionSpec}'.`); + } + core.debug(`Found LTS release '${release.version}' for Node version '${versionSpec}'`); + return release.version.split('.')[0]; +} +function getInfoFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os.arch()), manifest) { + return __awaiter(this, void 0, void 0, function* () { + let info = null; + if (!manifest) { + core.debug('No manifest cached'); + manifest = yield getManifest(auth); + } + const rel = yield tc.findFromManifest(versionSpec, stable, manifest, osArch); + if (rel && rel.files.length > 0) { + info = {}; + info.resolvedVersion = rel.version; + info.arch = rel.files[0].arch; + info.downloadUrl = rel.files[0].download_url; + info.fileName = rel.files[0].filename; + } + return info; + }); +} +function getInfoFromDist(versionSpec, arch = os.arch(), nodeVersions) { + return __awaiter(this, void 0, void 0, function* () { + let osPlat = os.platform(); + let osArch = translateArchToDistUrl(arch); + let version = yield queryDistForMatch(versionSpec, arch, nodeVersions); + if (!version) { + return null; + } + // + // Download - a tool installer intimately knows how to get the tool (and construct urls) + // + version = semver.clean(version) || ''; + let fileName = osPlat == 'win32' + ? `node-v${version}-win-${osArch}` + : `node-v${version}-${osPlat}-${osArch}`; + let urlFileName = osPlat == 'win32' ? `${fileName}.7z` : `${fileName}.tar.gz`; + let url = `https://nodejs.org/dist/v${version}/${urlFileName}`; + return { + downloadUrl: url, + resolvedVersion: version, + arch: arch, + fileName: fileName + }; + }); +} +function resolveVersionFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os.arch()), manifest) { + return __awaiter(this, void 0, void 0, function* () { + try { + const info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest); + return info === null || info === void 0 ? void 0 : info.resolvedVersion; + } + catch (err) { + core.info('Unable to resolve version from manifest...'); + core.debug(err.message); + } + }); +} +// TODO - should we just export this from @actions/tool-cache? Lifted directly from there +function evaluateVersions(versions, versionSpec) { + let version = ''; + core.debug(`evaluating ${versions.length} versions`); + versions = versions.sort((a, b) => { + if (semver.gt(a, b)) { + return 1; + } + return -1; + }); + for (let i = versions.length - 1; i >= 0; i--) { + const potential = versions[i]; + const satisfied = semver.satisfies(potential, versionSpec); + if (satisfied) { + version = potential; + break; + } + } + if (version) { + core.debug(`matched: ${version}`); + } + else { + core.debug('match not found'); + } + return version; +} +function queryDistForMatch(versionSpec, arch = os.arch(), nodeVersions) { + return __awaiter(this, void 0, void 0, function* () { + let osPlat = os.platform(); + let osArch = translateArchToDistUrl(arch); + // node offers a json list of versions + let dataFileName; + switch (osPlat) { + case 'linux': + dataFileName = `linux-${osArch}`; + break; + case 'darwin': + dataFileName = `osx-${osArch}-tar`; + break; + case 'win32': + dataFileName = `win-${osArch}-exe`; + break; + default: + throw new Error(`Unexpected OS '${osPlat}'`); + } + if (!nodeVersions) { + core.debug('No dist manifest cached'); + nodeVersions = yield getVersionsFromDist(); + } + let versions = []; + if (isLatestSyntax(versionSpec)) { + core.info(`getting latest node version...`); + return nodeVersions[0].version; + } + nodeVersions.forEach((nodeVersion) => { + // ensure this version supports your os and platform + if (nodeVersion.files.indexOf(dataFileName) >= 0) { + versions.push(nodeVersion.version); + } + }); + // get the latest version that matches the version spec + let version = evaluateVersions(versions, versionSpec); + return version; + }); +} +function getVersionsFromDist() { + return __awaiter(this, void 0, void 0, function* () { + let dataUrl = 'https://nodejs.org/dist/index.json'; + let httpClient = new hc.HttpClient('setup-node', [], { + allowRetries: true, + maxRetries: 3 + }); + let response = yield httpClient.getJson(dataUrl); + return response.result || []; + }); +} +exports.getVersionsFromDist = getVersionsFromDist; +// For non LTS versions of Node, the files we need (for Windows) are sometimes located +// in a different folder than they normally are for other versions. +// Normally the format is similar to: https://nodejs.org/dist/v5.10.1/node-v5.10.1-win-x64.7z +// In this case, there will be two files located at: +// /dist/v5.10.1/win-x64/node.exe +// /dist/v5.10.1/win-x64/node.lib +// If this is not the structure, there may also be two files located at: +// /dist/v0.12.18/node.exe +// /dist/v0.12.18/node.lib +// This method attempts to download and cache the resources from these alternative locations. +// Note also that the files are normally zipped but in this case they are just an exe +// and lib file in a folder, not zipped. +function acquireNodeFromFallbackLocation(version, arch = os.arch()) { + return __awaiter(this, void 0, void 0, function* () { + let osPlat = os.platform(); + let osArch = translateArchToDistUrl(arch); + // Create temporary folder to download in to + const tempDownloadFolder = 'temp_' + Math.floor(Math.random() * 2000000000); + const tempDirectory = process.env['RUNNER_TEMP'] || ''; + assert.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); + const tempDir = path.join(tempDirectory, tempDownloadFolder); + yield io.mkdirP(tempDir); + let exeUrl; + let libUrl; + try { + exeUrl = `https://nodejs.org/dist/v${version}/win-${osArch}/node.exe`; + libUrl = `https://nodejs.org/dist/v${version}/win-${osArch}/node.lib`; + core.info(`Downloading only node binary from ${exeUrl}`); + const exePath = yield tc.downloadTool(exeUrl); + yield io.cp(exePath, path.join(tempDir, 'node.exe')); + const libPath = yield tc.downloadTool(libUrl); + yield io.cp(libPath, path.join(tempDir, 'node.lib')); + } + catch (err) { + if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { + exeUrl = `https://nodejs.org/dist/v${version}/node.exe`; + libUrl = `https://nodejs.org/dist/v${version}/node.lib`; + const exePath = yield tc.downloadTool(exeUrl); + yield io.cp(exePath, path.join(tempDir, 'node.exe')); + const libPath = yield tc.downloadTool(libUrl); + yield io.cp(libPath, path.join(tempDir, 'node.lib')); + } + else { + throw err; + } + } + let toolPath = yield tc.cacheDir(tempDir, 'node', version, arch); + core.addPath(toolPath); + return toolPath; + }); +} +// os.arch does not always match the relative download url, e.g. +// os.arch == 'arm' != node-v12.13.1-linux-armv7l.tar.gz +// All other currently supported architectures match, e.g.: +// os.arch = arm64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-arm64.tar.gz +// os.arch = x64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-x64.tar.gz +function translateArchToDistUrl(arch) { + switch (arch) { + case 'arm': + return 'armv7l'; + default: + return arch; + } +} +function parseNodeVersionFile(contents) { + let nodeVersion = contents.trim(); + if (/^v\d/.test(nodeVersion)) { + nodeVersion = nodeVersion.substring(1); + } + return nodeVersion; +} +exports.parseNodeVersionFile = parseNodeVersionFile; +function isLatestSyntax(versionSpec) { + return ['current', 'latest', 'node'].includes(versionSpec); +} /***/ }), @@ -71786,99 +71786,110 @@ function isLatestSyntax(versionSpec) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(2186)); -const installer = __importStar(__nccwpck_require__(2574)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const auth = __importStar(__nccwpck_require__(7573)); -const path = __importStar(__nccwpck_require__(1017)); -const cache_restore_1 = __nccwpck_require__(9517); -const cache_utils_1 = __nccwpck_require__(1678); -const os = __nccwpck_require__(2037); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - // - // Version is optional. If supplied, install / use from the tool cache - // If not supplied then task is still used to setup proxy, auth, etc... - // - let version = resolveVersionInput(); - let arch = core.getInput('architecture'); - const cache = core.getInput('cache'); - // if architecture supplied but node-version is not - // if we don't throw a warning, the already installed x64 node will be used which is not probably what user meant. - if (arch && !version) { - core.warning('`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed. To fix this, provide `architecture` in combination with `node-version`'); - } - if (!arch) { - arch = os.arch(); - } - if (version) { - let token = core.getInput('token'); - let auth = !token || cache_utils_1.isGhes() ? undefined : `token ${token}`; - let stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE'; - const checkLatest = (core.getInput('check-latest') || 'false').toUpperCase() === 'TRUE'; - yield installer.getNode(version, stable, checkLatest, auth, arch); - } - const registryUrl = core.getInput('registry-url'); - const alwaysAuth = core.getInput('always-auth'); - if (registryUrl) { - auth.configAuthentication(registryUrl, alwaysAuth); - } - if (cache && cache_utils_1.isCacheFeatureAvailable()) { - const cacheDependencyPath = core.getInput('cache-dependency-path'); - yield cache_restore_1.restoreCache(cache, cacheDependencyPath); - } - const matchersPath = path.join(__dirname, '../..', '.github'); - core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`); - core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}`); - core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-compact.json')}`); - } - catch (err) { - core.setFailed(err.message); - } - }); -} -exports.run = run; -function resolveVersionInput() { - let version = core.getInput('node-version'); - const versionFileInput = core.getInput('node-version-file'); - if (version && versionFileInput) { - core.warning('Both node-version and node-version-file inputs are specified, only node-version will be used'); - } - if (version) { - return version; - } - if (versionFileInput) { - const versionFilePath = path.join(process.env.GITHUB_WORKSPACE, versionFileInput); - if (!fs_1.default.existsSync(versionFilePath)) { - throw new Error(`The specified node version file at: ${versionFilePath} does not exist`); - } - version = installer.parseNodeVersionFile(fs_1.default.readFileSync(versionFilePath, 'utf8')); - core.info(`Resolved ${versionFileInput} as ${version}`); - } - return version; -} + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const installer = __importStar(__nccwpck_require__(2574)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const auth = __importStar(__nccwpck_require__(7573)); +const path = __importStar(__nccwpck_require__(1017)); +const cache_restore_1 = __nccwpck_require__(9517); +const cache_utils_1 = __nccwpck_require__(1678); +const os = __nccwpck_require__(2037); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + // + // Version is optional. If supplied, install / use from the tool cache + // If not supplied then task is still used to setup proxy, auth, etc... + // + let version = resolveVersionInput(); + let arch = core.getInput('architecture'); + const cache = core.getInput('cache'); + // if architecture supplied but node-version is not + // if we don't throw a warning, the already installed x64 node will be used which is not probably what user meant. + if (arch && !version) { + core.warning('`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed. To fix this, provide `architecture` in combination with `node-version`'); + } + if (!arch) { + arch = os.arch(); + } + if (version) { + let token = core.getInput('token'); + let auth = !token || cache_utils_1.isGhes() ? undefined : `token ${token}`; + let stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE'; + const checkLatest = (core.getInput('check-latest') || 'false').toUpperCase() === 'TRUE'; + yield installer.getNode(version, stable, checkLatest, auth, arch); + } + // Output version of node is being used + let installedVersion = ''; + yield exec.exec('node', ['--version'], { + listeners: { + stdout: data => { + installedVersion += data.toString(); + } + } + }); + core.setOutput('node-version', installedVersion); + const registryUrl = core.getInput('registry-url'); + const alwaysAuth = core.getInput('always-auth'); + if (registryUrl) { + auth.configAuthentication(registryUrl, alwaysAuth); + } + if (cache && cache_utils_1.isCacheFeatureAvailable()) { + const cacheDependencyPath = core.getInput('cache-dependency-path'); + yield cache_restore_1.restoreCache(cache, cacheDependencyPath); + } + const matchersPath = path.join(__dirname, '../..', '.github'); + core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`); + core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}`); + core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-compact.json')}`); + } + catch (err) { + core.setFailed(err.message); + } + }); +} +exports.run = run; +function resolveVersionInput() { + let version = core.getInput('node-version'); + const versionFileInput = core.getInput('node-version-file'); + if (version && versionFileInput) { + core.warning('Both node-version and node-version-file inputs are specified, only node-version will be used'); + } + if (version) { + return version; + } + if (versionFileInput) { + const versionFilePath = path.join(process.env.GITHUB_WORKSPACE, versionFileInput); + if (!fs_1.default.existsSync(versionFilePath)) { + throw new Error(`The specified node version file at: ${versionFilePath} does not exist`); + } + version = installer.parseNodeVersionFile(fs_1.default.readFileSync(versionFilePath, 'utf8')); + core.info(`Resolved ${versionFileInput} as ${version}`); + } + return version; +} /***/ }), @@ -72134,10 +72145,10 @@ var __webpack_exports__ = {}; (() => { "use strict"; var exports = __webpack_exports__; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const main_1 = __nccwpck_require__(399); -main_1.run(); + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const main_1 = __nccwpck_require__(399); +main_1.run(); })(); From adeb189fd81b8c395752ae907500af8b50ad46b6 Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Fri, 1 Jul 2022 00:46:13 +0200 Subject: [PATCH 06/18] apply review feedback --- dist/setup/index.js | 9 +-------- src/main.ts | 13 +++++-------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/dist/setup/index.js b/dist/setup/index.js index 6806461..f051753 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71842,14 +71842,7 @@ function run() { yield installer.getNode(version, stable, checkLatest, auth, arch); } // Output version of node is being used - let installedVersion = ''; - yield exec.exec('node', ['--version'], { - listeners: { - stdout: data => { - installedVersion += data.toString(); - } - } - }); + const { stdout: installedVersion } = yield exec.getExecOutput('node', ['--version'], { ignoreReturnCode: true }); core.setOutput('node-version', installedVersion); const registryUrl = core.getInput('registry-url'); const alwaysAuth = core.getInput('always-auth'); diff --git a/src/main.ts b/src/main.ts index 106de77..5cfba61 100644 --- a/src/main.ts +++ b/src/main.ts @@ -41,14 +41,11 @@ export async function run() { } // Output version of node is being used - let installedVersion = ''; - await exec.exec('node', ['--version'], { - listeners: { - stdout: data => { - installedVersion += data.toString(); - } - } - }); + const {stdout: installedVersion} = await exec.getExecOutput( + 'node', + ['--version'], + {ignoreReturnCode: true} + ); core.setOutput('node-version', installedVersion); const registryUrl: string = core.getInput('registry-url'); From 0ad06209dd6a907d8d744031025d5a9e225c7ed6 Mon Sep 17 00:00:00 2001 From: James Ottaway Date: Fri, 1 Jul 2022 09:12:46 +1000 Subject: [PATCH 07/18] Update advanced-usage.md --- docs/advanced-usage.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md index e51f8ab..7e8b9c8 100644 --- a/docs/advanced-usage.md +++ b/docs/advanced-usage.md @@ -248,4 +248,4 @@ steps: - run: npm rebuild && npm run prepare --if-present ``` -NOTE: As per https://github.com/actions/setup-node/issues/49 you cannot use `secrets.GITHUB_TOKEN` to access private GitHub Packages within the same organisation. +NOTE: As per https://github.com/actions/setup-node/issues/49 you cannot use `secrets.GITHUB_TOKEN` to access private GitHub Packages within the same organisation but in a different repository. From d8b0944270f217dc91d376432646b3705ba2afdd Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Fri, 1 Jul 2022 01:27:37 +0200 Subject: [PATCH 08/18] add mock for getExecOutput in installer.test.ts --- __tests__/installer.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/__tests__/installer.test.ts b/__tests__/installer.test.ts index 5a3ad55..5e9da02 100644 --- a/__tests__/installer.test.ts +++ b/__tests__/installer.test.ts @@ -1,6 +1,7 @@ import * as core from '@actions/core'; import * as io from '@actions/io'; import * as tc from '@actions/tool-cache'; +import * as exec from '@actions/exec'; import * as im from '../src/installer'; import * as cache from '@actions/cache'; import fs from 'fs'; @@ -38,6 +39,7 @@ describe('setup-node', () => { let authSpy: jest.SpyInstance; let parseNodeVersionSpy: jest.SpyInstance; let isCacheActionAvailable: jest.SpyInstance; + let getExecOutputSpy: jest.SpyInstance; beforeEach(() => { // @actions/core @@ -103,6 +105,10 @@ describe('setup-node', () => { // uncomment to debug // process.stderr.write('log:' + line + '\n'); }); + + // @actions/exec + getExecOutputSpy = jest.spyOn(exec, 'getExecOutput'); + getExecOutputSpy.mockImplementation(() => '16.15.0'); }); afterEach(() => { From 460f88643a0200820f22522a1e0d7d98221a16fc Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Fri, 1 Jul 2022 01:30:18 +0200 Subject: [PATCH 09/18] fixup mocked version output --- __tests__/installer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/__tests__/installer.test.ts b/__tests__/installer.test.ts index 5e9da02..67948a3 100644 --- a/__tests__/installer.test.ts +++ b/__tests__/installer.test.ts @@ -108,7 +108,7 @@ describe('setup-node', () => { // @actions/exec getExecOutputSpy = jest.spyOn(exec, 'getExecOutput'); - getExecOutputSpy.mockImplementation(() => '16.15.0'); + getExecOutputSpy.mockImplementation(() => 'v16.15.0'); }); afterEach(() => { From b3ca1ac971f58028968bf4f3199547ade2bb277d Mon Sep 17 00:00:00 2001 From: AJ Jordan Date: Mon, 4 Jul 2022 17:29:56 -0400 Subject: [PATCH 10/18] Support npm-shrinkwrap.json out-of-the-box (#439) --- README.md | 2 +- dist/cache-save/index.js | 2 +- dist/setup/index.js | 2 +- src/cache-utils.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3b9ea0a..2259891 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ It's **always** recommended to commit the lockfile of your package manager for s The action has a built-in functionality for caching and restoring dependencies. It uses [actions/cache](https://github.com/actions/cache) under the hood for caching global packages data but requires less configuration settings. Supported package managers are `npm`, `yarn`, `pnpm` (v6.10+). The `cache` input is optional, and caching is turned off by default. -The action defaults to search for the dependency file (`package-lock.json` or `yarn.lock`) in the repository root, and uses its hash as a part of the cache key. Use `cache-dependency-path` for cases when multiple dependency files are used, or they are located in different subdirectories. +The action defaults to search for the dependency file (`package-lock.json`, `npm-shrinkwrap.json` or `yarn.lock`) in the repository root, and uses its hash as a part of the cache key. Use `cache-dependency-path` for cases when multiple dependency files are used, or they are located in different subdirectories. **Note:** The action does not cache `node_modules` diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index a55d232..ccd3a5a 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59926,7 +59926,7 @@ const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); exports.supportedPackageManagers = { npm: { - lockFilePatterns: ['package-lock.json', 'yarn.lock'], + lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], getCacheFolderCommand: 'npm config get cache' }, pnpm: { diff --git a/dist/setup/index.js b/dist/setup/index.js index f051753..43231cd 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71272,7 +71272,7 @@ const exec = __importStar(__nccwpck_require__(1514)); const cache = __importStar(__nccwpck_require__(7799)); exports.supportedPackageManagers = { npm: { - lockFilePatterns: ['package-lock.json', 'yarn.lock'], + lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], getCacheFolderCommand: 'npm config get cache' }, pnpm: { diff --git a/src/cache-utils.ts b/src/cache-utils.ts index b71bcc8..4db730e 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -13,7 +13,7 @@ export interface PackageManagerInfo { export const supportedPackageManagers: SupportedPackageManagers = { npm: { - lockFilePatterns: ['package-lock.json', 'yarn.lock'], + lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], getCacheFolderCommand: 'npm config get cache' }, pnpm: { From 09ba51f18e18a3756fea1f54d09c6745c064491d Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 7 Jul 2022 14:53:32 +0200 Subject: [PATCH 11/18] README.md: Encourage testing on current Node.js (#533) --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 2259891..6f44fdc 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 16 - run: npm ci - run: npm test ``` @@ -39,8 +39,8 @@ The `node-version` input supports the Semantic Versioning Specification, for mor Examples: - - Major versions: `12`, `14`, `16` - - More specific versions: `10.15`, `14.2.0`, `16.3.0` + - Major versions: `14`, `16`, `18` + - More specific versions: `10.15`, `16.15.1` , `18.4.0` - NVM LTS syntax: `lts/erbium`, `lts/fermium`, `lts/*`, `lts/-n` - Latest release: `*` or `latest`/`current`/`node` @@ -71,7 +71,7 @@ steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 16 cache: 'npm' - run: npm ci - run: npm test @@ -84,7 +84,7 @@ steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 16 cache: 'npm' cache-dependency-path: subdir/package-lock.json - run: npm ci @@ -99,7 +99,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [ 12, 14, 16 ] + node: [ 14, 16, 18 ] name: Node ${{ matrix.node }} sample steps: - uses: actions/checkout@v3 From aab7cc882a63a6e74f0d36e92552d03d190d4e7e Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Tue, 12 Jul 2022 10:30:30 +0200 Subject: [PATCH 12/18] add silent --- dist/setup/index.js | 2 +- src/main.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/setup/index.js b/dist/setup/index.js index 1b41467..679421c 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71846,7 +71846,7 @@ function run() { yield installer.getNode(version, stable, checkLatest, auth, arch); } // Output version of node is being used - const { stdout: installedVersion } = yield exec.getExecOutput('node', ['--version'], { ignoreReturnCode: true }); + const { stdout: installedVersion } = yield exec.getExecOutput('node', ['--version'], { ignoreReturnCode: true, silent: false }); core.setOutput('node-version', installedVersion); const registryUrl = core.getInput('registry-url'); const alwaysAuth = core.getInput('always-auth'); diff --git a/src/main.ts b/src/main.ts index 5cfba61..c17e8ae 100644 --- a/src/main.ts +++ b/src/main.ts @@ -44,7 +44,7 @@ export async function run() { const {stdout: installedVersion} = await exec.getExecOutput( 'node', ['--version'], - {ignoreReturnCode: true} + {ignoreReturnCode: true, silent: false} ); core.setOutput('node-version', installedVersion); From 48de4c13f6f686eebe0d350838793fffd4421b26 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Tue, 12 Jul 2022 10:36:10 +0200 Subject: [PATCH 13/18] change to streams --- dist/setup/index.js | 11 ++++++++++- src/main.ts | 15 ++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/dist/setup/index.js b/dist/setup/index.js index 679421c..31aa5cc 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71846,7 +71846,16 @@ function run() { yield installer.getNode(version, stable, checkLatest, auth, arch); } // Output version of node is being used - const { stdout: installedVersion } = yield exec.getExecOutput('node', ['--version'], { ignoreReturnCode: true, silent: false }); + let installedVersion = ''; + const result = yield exec.exec('node', ['--version'], { + ignoreReturnCode: true, + silent: false, + listeners: { + stdout: data => { + installedVersion = data.toString(); + } + } + }); core.setOutput('node-version', installedVersion); const registryUrl = core.getInput('registry-url'); const alwaysAuth = core.getInput('always-auth'); diff --git a/src/main.ts b/src/main.ts index c17e8ae..88f99e0 100644 --- a/src/main.ts +++ b/src/main.ts @@ -41,11 +41,16 @@ export async function run() { } // Output version of node is being used - const {stdout: installedVersion} = await exec.getExecOutput( - 'node', - ['--version'], - {ignoreReturnCode: true, silent: false} - ); + let installedVersion = ''; + const result = await exec.exec('node', ['--version'], { + ignoreReturnCode: true, + silent: false, + listeners: { + stdout: data => { + installedVersion = data.toString(); + } + } + }); core.setOutput('node-version', installedVersion); const registryUrl: string = core.getInput('registry-url'); From 28ad38fe0624edc69ffde19aa0a6b8be0573641f Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Tue, 12 Jul 2022 10:45:50 +0200 Subject: [PATCH 14/18] add try catch --- dist/setup/index.js | 18 +++++++----------- src/main.ts | 21 ++++++++++----------- 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/dist/setup/index.js b/dist/setup/index.js index 31aa5cc..f203ff6 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71846,17 +71846,13 @@ function run() { yield installer.getNode(version, stable, checkLatest, auth, arch); } // Output version of node is being used - let installedVersion = ''; - const result = yield exec.exec('node', ['--version'], { - ignoreReturnCode: true, - silent: false, - listeners: { - stdout: data => { - installedVersion = data.toString(); - } - } - }); - core.setOutput('node-version', installedVersion); + try { + const { stdout: installedVersion } = yield exec.getExecOutput('node', ['--version'], { ignoreReturnCode: true, silent: false }); + core.setOutput('node-version', installedVersion); + } + catch (err) { + core.setOutput('node-version', ''); + } const registryUrl = core.getInput('registry-url'); const alwaysAuth = core.getInput('always-auth'); if (registryUrl) { diff --git a/src/main.ts b/src/main.ts index 88f99e0..57f1922 100644 --- a/src/main.ts +++ b/src/main.ts @@ -41,17 +41,16 @@ export async function run() { } // Output version of node is being used - let installedVersion = ''; - const result = await exec.exec('node', ['--version'], { - ignoreReturnCode: true, - silent: false, - listeners: { - stdout: data => { - installedVersion = data.toString(); - } - } - }); - core.setOutput('node-version', installedVersion); + try { + const {stdout: installedVersion} = await exec.getExecOutput( + 'node', + ['--version'], + {ignoreReturnCode: true, silent: false} + ); + core.setOutput('node-version', installedVersion); + } catch (err) { + core.setOutput('node-version', ''); + } const registryUrl: string = core.getInput('registry-url'); const alwaysAuth: string = core.getInput('always-auth'); From 072a2e3b100f5d9394c602616700b044ce5e72f8 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Tue, 12 Jul 2022 14:19:55 +0200 Subject: [PATCH 15/18] add trim and silent true --- dist/setup/index.js | 4 ++-- src/main.ts | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/dist/setup/index.js b/dist/setup/index.js index f203ff6..801cf33 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71847,8 +71847,8 @@ function run() { } // Output version of node is being used try { - const { stdout: installedVersion } = yield exec.getExecOutput('node', ['--version'], { ignoreReturnCode: true, silent: false }); - core.setOutput('node-version', installedVersion); + const { stdout: installedVersion } = yield exec.getExecOutput('node', ['--version'], { ignoreReturnCode: true, silent: true }); + core.setOutput('node-version', installedVersion.trim()); } catch (err) { core.setOutput('node-version', ''); diff --git a/src/main.ts b/src/main.ts index 57f1922..21f9b33 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,6 +2,7 @@ import * as core from '@actions/core'; import * as exec from '@actions/exec'; import * as installer from './installer'; import fs from 'fs'; +import * as child_process from 'child_process'; import * as auth from './authutil'; import * as path from 'path'; import {restoreCache} from './cache-restore'; @@ -45,9 +46,9 @@ export async function run() { const {stdout: installedVersion} = await exec.getExecOutput( 'node', ['--version'], - {ignoreReturnCode: true, silent: false} + {ignoreReturnCode: true, silent: true} ); - core.setOutput('node-version', installedVersion); + core.setOutput('node-version', installedVersion.trim()); } catch (err) { core.setOutput('node-version', ''); } From 3d11add77113802f5dc907ae13379fa7ffdcd839 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Tue, 12 Jul 2022 14:44:36 +0200 Subject: [PATCH 16/18] remove unused import --- src/main.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main.ts b/src/main.ts index 21f9b33..ac7e51f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,7 +2,6 @@ import * as core from '@actions/core'; import * as exec from '@actions/exec'; import * as installer from './installer'; import fs from 'fs'; -import * as child_process from 'child_process'; import * as auth from './authutil'; import * as path from 'path'; import {restoreCache} from './cache-restore'; From 2fddd8803e2f5c9604345a0b591c3020ee971a93 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Wed, 13 Jul 2022 16:20:39 +0200 Subject: [PATCH 17/18] fixing pnpm output issue (#545) --- dist/cache-save/index.js | 4 ++-- dist/setup/index.js | 4 ++-- src/cache-utils.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index ccd3a5a..a79693b 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -59931,7 +59931,7 @@ exports.supportedPackageManagers = { }, pnpm: { lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path' + getCacheFolderCommand: 'pnpm store path --silent' }, yarn1: { lockFilePatterns: ['yarn.lock'], @@ -59986,7 +59986,7 @@ exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaite throw new Error(`Could not get cache folder path for ${packageManager}`); } core.debug(`${packageManager} path is ${stdOut}`); - return stdOut; + return stdOut.trim(); }); function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); diff --git a/dist/setup/index.js b/dist/setup/index.js index 801cf33..28d5dc8 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71277,7 +71277,7 @@ exports.supportedPackageManagers = { }, pnpm: { lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path' + getCacheFolderCommand: 'pnpm store path --silent' }, yarn1: { lockFilePatterns: ['yarn.lock'], @@ -71332,7 +71332,7 @@ exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaite throw new Error(`Could not get cache folder path for ${packageManager}`); } core.debug(`${packageManager} path is ${stdOut}`); - return stdOut; + return stdOut.trim(); }); function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); diff --git a/src/cache-utils.ts b/src/cache-utils.ts index 4db730e..ccd4e98 100644 --- a/src/cache-utils.ts +++ b/src/cache-utils.ts @@ -18,7 +18,7 @@ export const supportedPackageManagers: SupportedPackageManagers = { }, pnpm: { lockFilePatterns: ['pnpm-lock.yaml'], - getCacheFolderCommand: 'pnpm store path' + getCacheFolderCommand: 'pnpm store path --silent' }, yarn1: { lockFilePatterns: ['yarn.lock'], @@ -94,7 +94,7 @@ export const getCacheDirectoryPath = async ( core.debug(`${packageManager} path is ${stdOut}`); - return stdOut; + return stdOut.trim(); }; export function isGhes(): boolean { From 2a814b57e1a920a0c910a1007b50142423386ff0 Mon Sep 17 00:00:00 2001 From: "mannie.exe" <7815113+schmannie@users.noreply.github.com> Date: Thu, 21 Jul 2022 10:17:21 -0700 Subject: [PATCH 18/18] Respect `package.json`'s `engines.node` field when used as a `node-version-file` (#485) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Allow reading 'package.json' as node-version-file * Run 'npm run build' * Read package.json contents directly during tests - this eliminates OS-specific line-ending issues * Run project Prettier 💅 --- __tests__/data/package.json | 5 +++++ __tests__/installer.test.ts | 27 +++++++++++++++++++++++++++ dist/setup/index.js | 24 +++++++++++++++++------- src/installer.ts | 24 +++++++++++++++++------- 4 files changed, 66 insertions(+), 14 deletions(-) create mode 100644 __tests__/data/package.json diff --git a/__tests__/data/package.json b/__tests__/data/package.json new file mode 100644 index 0000000..e537e20 --- /dev/null +++ b/__tests__/data/package.json @@ -0,0 +1,5 @@ +{ + "engines": { + "node": ">=14.0.0" + } +} diff --git a/__tests__/installer.test.ts b/__tests__/installer.test.ts index cd53619..c1e16b5 100644 --- a/__tests__/installer.test.ts +++ b/__tests__/installer.test.ts @@ -591,6 +591,33 @@ describe('setup-node', () => { ); }); + it('reads package.json as node-version-file if provided', async () => { + // Arrange + const versionSpec = fs.readFileSync( + path.join(__dirname, 'data/package.json'), + 'utf-8' + ); + const versionFile = 'package.json'; + const expectedVersionSpec = '14'; + process.env['GITHUB_WORKSPACE'] = path.join(__dirname, 'data'); + inputs['node-version-file'] = versionFile; + + parseNodeVersionSpy.mockImplementation(() => expectedVersionSpec); + existsSpy.mockImplementationOnce( + input => input === path.join(__dirname, 'data', versionFile) + ); + // Act + await main.run(); + + // Assert + expect(existsSpy).toHaveBeenCalledTimes(1); + expect(existsSpy).toHaveReturnedWith(true); + expect(parseNodeVersionSpy).toHaveBeenCalledWith(versionSpec); + expect(logSpy).toHaveBeenCalledWith( + `Resolved ${versionFile} as ${expectedVersionSpec}` + ); + }); + it('both node-version-file and node-version are provided', async () => { inputs['node-version'] = '12'; const versionSpec = 'v14'; diff --git a/dist/setup/index.js b/dist/setup/index.js index 28d5dc8..0a0c0ba 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -71768,15 +71768,25 @@ function translateArchToDistUrl(arch) { } } function parseNodeVersionFile(contents) { - var _a; + var _a, _b; + let nodeVersion; const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); - const nodeVersion = (_a = found === null || found === void 0 ? void 0 : found.groups) === null || _a === void 0 ? void 0 : _a.version; - if (nodeVersion) { - return nodeVersion; + nodeVersion = (_a = found === null || found === void 0 ? void 0 : found.groups) === null || _a === void 0 ? void 0 : _a.version; + if (!nodeVersion) { + try { + // Try parsing the file as an NPM `package.json` + // file. + nodeVersion = (_b = JSON.parse(contents).engines) === null || _b === void 0 ? void 0 : _b.node; + if (!nodeVersion) + throw new Error(); + } + catch (err) { + // In the case of an unknown format, + // return as is and evaluate the version separately. + nodeVersion = contents.trim(); + } } - // In the case of an unknown format, - // return as is and evaluate the version separately. - return contents.trim(); + return nodeVersion; } exports.parseNodeVersionFile = parseNodeVersionFile; function isLatestSyntax(versionSpec) { diff --git a/src/installer.ts b/src/installer.ts index 019f2ed..193ff16 100644 --- a/src/installer.ts +++ b/src/installer.ts @@ -495,16 +495,26 @@ function translateArchToDistUrl(arch: string): string { } export function parseNodeVersionFile(contents: string): string { - const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); - const nodeVersion = found?.groups?.version; + let nodeVersion: string | undefined; - if (nodeVersion) { - return nodeVersion; + const found = contents.match(/^(?:nodejs\s+)?v?(?[^\s]+)$/m); + nodeVersion = found?.groups?.version; + + if (!nodeVersion) { + try { + // Try parsing the file as an NPM `package.json` + // file. + nodeVersion = JSON.parse(contents).engines?.node; + + if (!nodeVersion) throw new Error(); + } catch (err) { + // In the case of an unknown format, + // return as is and evaluate the version separately. + nodeVersion = contents.trim(); + } } - // In the case of an unknown format, - // return as is and evaluate the version separately. - return contents.trim(); + return nodeVersion as string; } function isLatestSyntax(versionSpec): boolean {