From d50f842f5443acd7f617637e9429d22f18a80b45 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Fri, 18 Feb 2022 15:20:03 +0300 Subject: [PATCH 1/7] make some refactoring --- dist/index.js | 40 ++++++++++++++++------------------------ src/installer.ts | 42 +++++++++++++----------------------------- src/main.ts | 7 +------ src/system.ts | 2 +- 4 files changed, 31 insertions(+), 60 deletions(-) diff --git a/dist/index.js b/dist/index.js index 59a4067ce..1601976f5 100644 --- a/dist/index.js +++ b/dist/index.js @@ -2082,7 +2082,7 @@ function run() { let token = core.getInput('token'); let auth = !token || isGhes() ? undefined : `token ${token}`; const checkLatest = core.getBooleanInput('check-latest'); - const installDir = yield installer.getGo(versionSpec, stable, checkLatest, auth); + const installDir = yield installer.getGo(versionSpec, checkLatest, auth); core.exportVariable('GOROOT', installDir); core.addPath(path_1.default.join(installDir, 'bin')); core.info('Added go to the path'); @@ -5718,7 +5718,7 @@ module.exports = bytesToUuid; Object.defineProperty(exports, "__esModule", { value: true }); exports.getArch = exports.getPlatform = void 0; -let os = __webpack_require__(87); +const os = __webpack_require__(87); function getPlatform() { // darwin and linux match already // freebsd not supported yet but future proofed. @@ -5890,13 +5890,13 @@ const semver = __importStar(__webpack_require__(280)); const httpm = __importStar(__webpack_require__(539)); const sys = __importStar(__webpack_require__(737)); const os_1 = __importDefault(__webpack_require__(87)); -function getGo(versionSpec, stable, checkLatest, auth) { +function getGo(versionSpec, checkLatest, auth) { return __awaiter(this, void 0, void 0, function* () { let osPlat = os_1.default.platform(); let osArch = os_1.default.arch(); if (checkLatest) { core.info('Attempting to resolve the latest version from the manifest...'); - const resolvedVersion = yield resolveVersionFromManifest(versionSpec, stable, auth); + const resolvedVersion = yield resolveVersionFromManifest(versionSpec, true, auth); if (resolvedVersion) { versionSpec = resolvedVersion; core.info(`Resolved as '${versionSpec}'`); @@ -5920,7 +5920,7 @@ function getGo(versionSpec, stable, checkLatest, auth) { // Try download from internal distribution (popular versions only) // try { - info = yield getInfoFromManifest(versionSpec, stable, auth); + info = yield getInfoFromManifest(versionSpec, true, auth); if (info) { downloadPath = yield installGoVersion(info, auth); } @@ -5943,7 +5943,7 @@ function getGo(versionSpec, stable, checkLatest, auth) { // Download from storage.googleapis.com // if (!downloadPath) { - info = yield getInfoFromDist(versionSpec, stable); + info = yield getInfoFromDist(versionSpec); if (!info) { throw new Error(`Unable to find Go version '${versionSpec}' for platform ${osPlat} and architecture ${osArch}.`); } @@ -6018,10 +6018,10 @@ function getInfoFromManifest(versionSpec, stable, auth) { }); } exports.getInfoFromManifest = getInfoFromManifest; -function getInfoFromDist(versionSpec, stable) { +function getInfoFromDist(versionSpec) { return __awaiter(this, void 0, void 0, function* () { let version; - version = yield findMatch(versionSpec, stable); + version = yield findMatch(versionSpec); if (!version) { return null; } @@ -6034,7 +6034,7 @@ function getInfoFromDist(versionSpec, stable) { }; }); } -function findMatch(versionSpec, stable) { +function findMatch(versionSpec) { return __awaiter(this, void 0, void 0, function* () { let archFilter = sys.getArch(); let platFilter = sys.getPlatform(); @@ -6049,15 +6049,8 @@ function findMatch(versionSpec, stable) { for (let i = 0; i < candidates.length; i++) { let candidate = candidates[i]; let version = makeSemver(candidate.version); - // 1.13.0 is advertised as 1.13 preventing being able to match exactly 1.13.0 - // since a semver of 1.13 would match latest 1.13 - let parts = version.split('.'); - if (parts.length == 2) { - version = version + '.0'; - } core.debug(`check ${version} satisfies ${versionSpec}`); - if (semver.satisfies(version, versionSpec) && - (!stable || candidate.stable === stable)) { + if (semver.satisfies(version, versionSpec)) { goFile = candidate.files.find(file => { core.debug(`${file.arch}===${archFilter} && ${file.os}===${platFilter}`); return file.arch === archFilter && file.os === platFilter; @@ -6097,15 +6090,14 @@ exports.getVersionsDist = getVersionsDist; // 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 function makeSemver(version) { version = version.replace('go', ''); - version = version.replace('beta', '-beta').replace('rc', '-rc'); + version = version.replace('beta', '-beta.').replace('rc', '-rc.'); let parts = version.split('-'); - let verPart = parts[0]; - let prereleasePart = parts.length > 1 ? `-${parts[1]}` : ''; - let verParts = verPart.split('.'); - if (verParts.length == 2) { - verPart += '.0'; + let semVersion = semver.coerce(version).version; + if (!parts[1]) { + return semVersion; } - return `${verPart}${prereleasePart}`; + semVersion = new semver.SemVer(`${semVersion}-${parts[1]}`).version; + return semVersion; } exports.makeSemver = makeSemver; //# sourceMappingURL=installer.js.map diff --git a/src/installer.ts b/src/installer.ts index ee45c6485..6cc029cf6 100644 --- a/src/installer.ts +++ b/src/installer.ts @@ -30,7 +30,6 @@ export interface IGoVersionInfo { export async function getGo( versionSpec: string, - stable: boolean, checkLatest: boolean, auth: string | undefined ) { @@ -41,7 +40,7 @@ export async function getGo( core.info('Attempting to resolve the latest version from the manifest...'); const resolvedVersion = await resolveVersionFromManifest( versionSpec, - stable, + true, auth ); if (resolvedVersion) { @@ -68,7 +67,7 @@ export async function getGo( // Try download from internal distribution (popular versions only) // try { - info = await getInfoFromManifest(versionSpec, stable, auth); + info = await getInfoFromManifest(versionSpec, true, auth); if (info) { downloadPath = await installGoVersion(info, auth); } else { @@ -95,7 +94,7 @@ export async function getGo( // Download from storage.googleapis.com // if (!downloadPath) { - info = await getInfoFromDist(versionSpec, stable); + info = await getInfoFromDist(versionSpec); if (!info) { throw new Error( `Unable to find Go version '${versionSpec}' for platform ${osPlat} and architecture ${osArch}.` @@ -191,11 +190,10 @@ export async function getInfoFromManifest( } async function getInfoFromDist( - versionSpec: string, - stable: boolean + versionSpec: string ): Promise { let version: IGoVersion | undefined; - version = await findMatch(versionSpec, stable); + version = await findMatch(versionSpec); if (!version) { return null; } @@ -211,8 +209,7 @@ async function getInfoFromDist( } export async function findMatch( - versionSpec: string, - stable: boolean + versionSpec: string ): Promise { let archFilter = sys.getArch(); let platFilter = sys.getPlatform(); @@ -233,18 +230,8 @@ export async function findMatch( let candidate: IGoVersion = candidates[i]; let version = makeSemver(candidate.version); - // 1.13.0 is advertised as 1.13 preventing being able to match exactly 1.13.0 - // since a semver of 1.13 would match latest 1.13 - let parts: string[] = version.split('.'); - if (parts.length == 2) { - version = version + '.0'; - } - core.debug(`check ${version} satisfies ${versionSpec}`); - if ( - semver.satisfies(version, versionSpec) && - (!stable || candidate.stable === stable) - ) { + if (semver.satisfies(version, versionSpec)) { goFile = candidate.files.find(file => { core.debug( `${file.arch}===${archFilter} && ${file.os}===${platFilter}` @@ -288,16 +275,13 @@ export async function getVersionsDist( // 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 export function makeSemver(version: string): string { version = version.replace('go', ''); - version = version.replace('beta', '-beta').replace('rc', '-rc'); + version = version.replace('beta', '-beta.').replace('rc', '-rc.'); let parts = version.split('-'); - let verPart: string = parts[0]; - let prereleasePart = parts.length > 1 ? `-${parts[1]}` : ''; - - let verParts: string[] = verPart.split('.'); - if (verParts.length == 2) { - verPart += '.0'; + let semVersion = semver.coerce(version)!.version; + if (!parts[1]) { + return semVersion; } - - return `${verPart}${prereleasePart}`; + semVersion = new semver.SemVer(`${semVersion}-${parts[1]}`).version; + return semVersion; } diff --git a/src/main.ts b/src/main.ts index 5837dee86..452308f4e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -25,12 +25,7 @@ export async function run() { let auth = !token || isGhes() ? undefined : `token ${token}`; const checkLatest = core.getBooleanInput('check-latest'); - const installDir = await installer.getGo( - versionSpec, - stable, - checkLatest, - auth - ); + const installDir = await installer.getGo(versionSpec, checkLatest, auth); core.exportVariable('GOROOT', installDir); core.addPath(path.join(installDir, 'bin')); diff --git a/src/system.ts b/src/system.ts index 8dfad42fd..6973f9998 100644 --- a/src/system.ts +++ b/src/system.ts @@ -1,4 +1,4 @@ -let os = require('os'); +const os = require('os'); export function getPlatform(): string { // darwin and linux match already From 5021096bd0a365f241197c8b519fa921230a632e Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Fri, 18 Feb 2022 15:28:51 +0300 Subject: [PATCH 2/7] fixing tests --- __tests__/setup-go.test.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/__tests__/setup-go.test.ts b/__tests__/setup-go.test.ts index db94e82de..873e8dca5 100644 --- a/__tests__/setup-go.test.ts +++ b/__tests__/setup-go.test.ts @@ -147,7 +147,7 @@ describe('setup-go', () => { os.arch = 'x64'; // spec: 1.13.0 => 1.13 - let match: im.IGoVersion | undefined = await im.findMatch('1.13.0', true); + let match: im.IGoVersion | undefined = await im.findMatch('1.13.0'); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13'); @@ -160,7 +160,7 @@ describe('setup-go', () => { os.arch = 'x64'; // spec: 1.13 => 1.13.7 (latest) - let match: im.IGoVersion | undefined = await im.findMatch('1.13', true); + let match: im.IGoVersion | undefined = await im.findMatch('1.13'); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13.7'); @@ -173,7 +173,7 @@ describe('setup-go', () => { os.arch = 'x64'; // spec: ^1.13.6 => 1.13.7 - let match: im.IGoVersion | undefined = await im.findMatch('^1.13.6', true); + let match: im.IGoVersion | undefined = await im.findMatch('^1.13.6'); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13.7'); @@ -186,7 +186,7 @@ describe('setup-go', () => { os.arch = 'x32'; // spec: 1 => 1.13.7 (latest) - let match: im.IGoVersion | undefined = await im.findMatch('1', true); + let match: im.IGoVersion | undefined = await im.findMatch('1'); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13.7'); @@ -199,10 +199,7 @@ describe('setup-go', () => { os.arch = 'x64'; // spec: 1.14, stable=false => go1.14rc1 - let match: im.IGoVersion | undefined = await im.findMatch( - '1.14.0-rc1', - false - ); + let match: im.IGoVersion | undefined = await im.findMatch('1.14.0-rc1'); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.14rc1'); From 5e49df42b0610dccb08db91862f48a741e1e9b33 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Fri, 18 Feb 2022 15:49:48 +0300 Subject: [PATCH 3/7] fixing test --- __tests__/setup-go.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/__tests__/setup-go.test.ts b/__tests__/setup-go.test.ts index 873e8dca5..840ff43d7 100644 --- a/__tests__/setup-go.test.ts +++ b/__tests__/setup-go.test.ts @@ -199,7 +199,7 @@ describe('setup-go', () => { os.arch = 'x64'; // spec: 1.14, stable=false => go1.14rc1 - let match: im.IGoVersion | undefined = await im.findMatch('1.14.0-rc1'); + let match: im.IGoVersion | undefined = await im.findMatch('1.14.0-rc.1'); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.14rc1'); @@ -560,8 +560,8 @@ describe('setup-go', () => { // 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1 // 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 it('converts prerelease versions', async () => { - expect(im.makeSemver('1.10beta1')).toBe('1.10.0-beta1'); - expect(im.makeSemver('1.10rc1')).toBe('1.10.0-rc1'); + expect(im.makeSemver('1.10beta1')).toBe('1.10.0-beta.1'); + expect(im.makeSemver('1.10rc1')).toBe('1.10.0-rc.1'); }); it('converts dot zero versions', async () => { From 54167c0c258ca7f12eac819ea9a7b6fa057a3b10 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Mon, 21 Feb 2022 10:32:45 +0300 Subject: [PATCH 4/7] throw errors --- dist/index.js | 13 ++++++++++--- src/installer.ts | 19 ++++++++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/dist/index.js b/dist/index.js index 1601976f5..537d58f7a 100644 --- a/dist/index.js +++ b/dist/index.js @@ -6089,15 +6089,22 @@ exports.getVersionsDist = getVersionsDist; // 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1 // 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 function makeSemver(version) { + var _a; version = version.replace('go', ''); version = version.replace('beta', '-beta.').replace('rc', '-rc.'); let parts = version.split('-'); - let semVersion = semver.coerce(version).version; + let semVersion = (_a = semver.coerce(version)) === null || _a === void 0 ? void 0 : _a.version; + if (!semVersion) { + throw new Error(`The version: ${version} can't be changed to SemVer notation`); + } if (!parts[1]) { return semVersion; } - semVersion = new semver.SemVer(`${semVersion}-${parts[1]}`).version; - return semVersion; + const fullVersion = semver.valid(`${semVersion}-${parts[1]}`); + if (!fullVersion) { + throw new Error(`The version: ${version} can't be changed to SemVer notation`); + } + return fullVersion; } exports.makeSemver = makeSemver; //# sourceMappingURL=installer.js.map diff --git a/src/installer.ts b/src/installer.ts index 6cc029cf6..7fef3cdf3 100644 --- a/src/installer.ts +++ b/src/installer.ts @@ -278,10 +278,23 @@ export function makeSemver(version: string): string { version = version.replace('beta', '-beta.').replace('rc', '-rc.'); let parts = version.split('-'); - let semVersion = semver.coerce(version)!.version; + let semVersion = semver.coerce(version)?.version; + if (!semVersion) { + throw new Error( + `The version: ${version} can't be changed to SemVer notation` + ); + } + if (!parts[1]) { return semVersion; } - semVersion = new semver.SemVer(`${semVersion}-${parts[1]}`).version; - return semVersion; + + const fullVersion = semver.valid(`${semVersion}-${parts[1]}`); + + if (!fullVersion) { + throw new Error( + `The version: ${version} can't be changed to SemVer notation` + ); + } + return fullVersion; } From e53583cbb2e651a395b79d2c1931d22cb243c783 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Thu, 24 Feb 2022 12:49:40 +0300 Subject: [PATCH 5/7] fix tests and add log --- __tests__/setup-go.test.ts | 14 +- action.yml | 3 - dist/index.js | 1135 ++++++++++-------------------------- src/installer.ts | 4 +- src/main.ts | 6 +- 5 files changed, 319 insertions(+), 843 deletions(-) diff --git a/__tests__/setup-go.test.ts b/__tests__/setup-go.test.ts index 840ff43d7..ba54900f9 100644 --- a/__tests__/setup-go.test.ts +++ b/__tests__/setup-go.test.ts @@ -215,7 +215,7 @@ describe('setup-go', () => { findSpy.mockImplementation(() => toolPath); await main.run(); - expect(logSpy).toHaveBeenCalledWith(`Setup go stable version spec 1.13.0`); + expect(logSpy).toHaveBeenCalledWith(`Setup go version spec 1.13.0`); }); it('evaluates to stable with no input', async () => { @@ -227,7 +227,7 @@ describe('setup-go', () => { findSpy.mockImplementation(() => toolPath); await main.run(); - expect(logSpy).toHaveBeenCalledWith(`Setup go stable version spec 1.13.0`); + expect(logSpy).toHaveBeenCalledWith(`Setup go version spec 1.13.0`); }); it('finds a version of go already in the cache', async () => { @@ -393,7 +393,7 @@ describe('setup-go', () => { await main.run(); let expPath = path.join(toolPath, 'bin'); - expect(logSpy).toHaveBeenCalledWith('Setup go stable version spec 1.12.14'); + expect(logSpy).toHaveBeenCalledWith('Setup go version spec 1.12.14'); expect(findSpy).toHaveBeenCalled(); expect(logSpy).toHaveBeenCalledWith('Attempting to download 1.12.14...'); expect(dlSpy).toHaveBeenCalled(); @@ -557,8 +557,8 @@ describe('setup-go', () => { // 1.13.1 => 1.13.1 // 1.13 => 1.13.0 - // 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1 - // 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 + // 1.10beta1 => 1.10.0-beta.1, 1.10rc1 => 1.10.0-rc.1 + // 1.8.5beta1 => 1.8.5-beta.1, 1.8.5rc1 => 1.8.5-rc.1 it('converts prerelease versions', async () => { expect(im.makeSemver('1.10beta1')).toBe('1.10.0-beta.1'); expect(im.makeSemver('1.10rc1')).toBe('1.10.0-rc.1'); @@ -605,7 +605,7 @@ describe('setup-go', () => { await main.run(); - expect(logSpy).toHaveBeenCalledWith('Setup go stable version spec 1.16'); + expect(logSpy).toHaveBeenCalledWith('Setup go version spec 1.16'); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); }); @@ -630,7 +630,7 @@ describe('setup-go', () => { await main.run(); expect(logSpy).toHaveBeenCalledWith( - `Setup go stable version spec ${versionSpec}` + `Setup go version spec ${versionSpec}` ); expect(logSpy).toHaveBeenCalledWith( 'Attempting to resolve the latest version from the manifest...' diff --git a/action.yml b/action.yml index 5706f1b86..8bbaebef5 100644 --- a/action.yml +++ b/action.yml @@ -7,9 +7,6 @@ inputs: check-latest: description: 'Set this option to true if you want the action to always check for the latest available version that satisfies the version spec' default: false - stable: - description: 'Whether to download only stable versions' - default: 'true' token: description: Used to pull node distributions from go-versions. Since there's a default, this is typically not supplied by the user. default: ${{ github.token }} diff --git a/dist/index.js b/dist/index.js index 537d58f7a..171d28da1 100644 --- a/dist/index.js +++ b/dist/index.js @@ -345,6 +345,25 @@ function copyFile(srcFile, destFile, force) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; 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) { @@ -354,20 +373,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge 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 }); +exports.argStringToArray = exports.ToolRunner = void 0; const os = __importStar(__webpack_require__(87)); const events = __importStar(__webpack_require__(614)); const child = __importStar(__webpack_require__(129)); const path = __importStar(__webpack_require__(622)); const io = __importStar(__webpack_require__(1)); const ioUtil = __importStar(__webpack_require__(672)); +const timers_1 = __webpack_require__(213); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* @@ -437,11 +451,12 @@ class ToolRunner extends events.EventEmitter { s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } - strBuffer = s; + return s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); + return ''; } } _getSpawnFileName() { @@ -723,7 +738,7 @@ class ToolRunner extends events.EventEmitter { // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { @@ -737,9 +752,12 @@ class ToolRunner extends events.EventEmitter { state.on('debug', (message) => { this._debug(message); }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - const stdbuffer = ''; + let stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { @@ -748,14 +766,14 @@ class ToolRunner extends events.EventEmitter { if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } - this._processLineBuffer(data, stdbuffer, (line) => { + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } - const errbuffer = ''; + let errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; @@ -770,7 +788,7 @@ class ToolRunner extends events.EventEmitter { : optionsNonNull.outStream; s.write(data); } - this._processLineBuffer(data, errbuffer, (line) => { + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } @@ -817,7 +835,7 @@ class ToolRunner extends events.EventEmitter { } cp.stdin.end(this.options.input); } - }); + })); }); } } @@ -903,7 +921,7 @@ class ExecState extends events.EventEmitter { this._setResult(); } else if (this.processExited) { - this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this); + this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { @@ -1476,680 +1494,205 @@ main_1.run(); /***/ }), -/***/ 192: +/***/ 198: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); -const http = __webpack_require__(605); -const https = __webpack_require__(211); -const pm = __webpack_require__(651); -let tunnel; -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); +exports.addBinToPath = exports.run = void 0; +const core = __importStar(__webpack_require__(470)); +const io = __importStar(__webpack_require__(1)); +const installer = __importStar(__webpack_require__(749)); +const path_1 = __importDefault(__webpack_require__(622)); +const child_process_1 = __importDefault(__webpack_require__(129)); +const fs_1 = __importDefault(__webpack_require__(747)); +const url_1 = __webpack_require__(835); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + // + // versionSpec is optional. If supplied, install / use from the tool cache + // If not supplied then problem matchers will still be setup. Useful for self-hosted. + // + let versionSpec = core.getInput('go-version'); + core.info(`Setup go version spec ${versionSpec}`); + if (versionSpec) { + let token = core.getInput('token'); + let auth = !token || isGhes() ? undefined : `token ${token}`; + const checkLatest = core.getBooleanInput('check-latest'); + const installDir = yield installer.getGo(versionSpec, checkLatest, auth); + core.exportVariable('GOROOT', installDir); + core.addPath(path_1.default.join(installDir, 'bin')); + core.info('Added go to the path'); + let added = yield addBinToPath(); + core.debug(`add bin ${added}`); + core.info(`Successfully setup go version ${versionSpec}`); } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; + // add problem matchers + const matchersPath = path_1.default.join(__dirname, '..', 'matchers.json'); + core.info(`##[add-matcher]${matchersPath}`); + // output the version actually being used + let goPath = yield io.which('go'); + let goVersion = (child_process_1.default.execSync(`${goPath} version`) || '').toString(); + core.info(goVersion); + core.startGroup('go env'); + let goEnv = (child_process_1.default.execSync(`${goPath} env`) || '').toString(); + core.info(goEnv); + core.endGroup(); + } + catch (error) { + core.setFailed(error.message); + } + }); +} +exports.run = run; +function addBinToPath() { + return __awaiter(this, void 0, void 0, function* () { + let added = false; + let g = yield io.which('go'); + core.debug(`which go :${g}:`); + if (!g) { + core.debug('go not in the path'); + return added; + } + let buf = child_process_1.default.execSync('go env GOPATH'); + if (buf) { + let gp = buf.toString().trim(); + core.debug(`go env GOPATH :${gp}:`); + if (!fs_1.default.existsSync(gp)) { + // some of the hosted images have go install but not profile dir + core.debug(`creating ${gp}`); + io.mkdirP(gp); } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - } - get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - } - del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - } - post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - } - patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - } - put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - } - head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(verb, requestUrl, stream, additionalHeaders); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); - } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - let socket; - if (typeof data === 'string') { - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - let handleResult = (err, res) => { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); - }); - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error('Request timeout: ' + info.options.path), null); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err, null); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - this.handlers.forEach(handler => { - handler.prepareRequest(info.options); - }); - } - return info; - } - _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (!!agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (!!this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __webpack_require__(413); - } - const agentOptions = { - maxSockets: maxSockets, - keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; + let bp = path_1.default.join(gp, 'bin'); + if (!fs_1.default.existsSync(bp)) { + core.debug(`creating ${bp}`); + io.mkdirP(bp); } + core.addPath(bp); + added = true; } - return value; - } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = 'Failed request: (' + statusCode + ')'; - } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - }); - } + return added; + }); } -exports.HttpClient = HttpClient; +exports.addBinToPath = addBinToPath; +function isGhes() { + const ghUrl = new url_1.URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +//# sourceMappingURL=main.js.map + +/***/ }), + +/***/ 211: +/***/ (function(module) { +module.exports = require("https"); /***/ }), -/***/ 198: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 213: +/***/ (function(module) { + +module.exports = require("timers"); + +/***/ }), + +/***/ 226: +/***/ (function(__unusedmodule, exports) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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 __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -exports.addBinToPath = exports.run = void 0; -const core = __importStar(__webpack_require__(470)); -const io = __importStar(__webpack_require__(1)); -const installer = __importStar(__webpack_require__(749)); -const path_1 = __importDefault(__webpack_require__(622)); -const child_process_1 = __importDefault(__webpack_require__(129)); -const fs_1 = __importDefault(__webpack_require__(747)); -const url_1 = __webpack_require__(835); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - // - // versionSpec is optional. If supplied, install / use from the tool cache - // If not supplied then problem matchers will still be setup. Useful for self-hosted. - // - let versionSpec = core.getInput('go-version'); - // stable will be true unless false is the exact input - // since getting unstable versions should be explicit - let stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE'; - core.info(`Setup go ${stable ? 'stable' : ''} version spec ${versionSpec}`); - if (versionSpec) { - let token = core.getInput('token'); - let auth = !token || isGhes() ? undefined : `token ${token}`; - const checkLatest = core.getBooleanInput('check-latest'); - const installDir = yield installer.getGo(versionSpec, checkLatest, auth); - core.exportVariable('GOROOT', installDir); - core.addPath(path_1.default.join(installDir, 'bin')); - core.info('Added go to the path'); - let added = yield addBinToPath(); - core.debug(`add bin ${added}`); - core.info(`Successfully setup go version ${versionSpec}`); - } - // add problem matchers - const matchersPath = path_1.default.join(__dirname, '..', 'matchers.json'); - core.info(`##[add-matcher]${matchersPath}`); - // output the version actually being used - let goPath = yield io.which('go'); - let goVersion = (child_process_1.default.execSync(`${goPath} version`) || '').toString(); - core.info(goVersion); - core.startGroup('go env'); - let goEnv = (child_process_1.default.execSync(`${goPath} env`) || '').toString(); - core.info(goEnv); - core.endGroup(); - } - catch (error) { - core.setFailed(error.message); - } - }); -} -exports.run = run; -function addBinToPath() { - return __awaiter(this, void 0, void 0, function* () { - let added = false; - let g = yield io.which('go'); - core.debug(`which go :${g}:`); - if (!g) { - core.debug('go not in the path'); - return added; - } - let buf = child_process_1.default.execSync('go env GOPATH'); - if (buf) { - let gp = buf.toString().trim(); - core.debug(`go env GOPATH :${gp}:`); - if (!fs_1.default.existsSync(gp)) { - // some of the hosted images have go install but not profile dir - core.debug(`creating ${gp}`); - io.mkdirP(gp); - } - let bp = path_1.default.join(gp, 'bin'); - if (!fs_1.default.existsSync(bp)) { - core.debug(`creating ${bp}`); - io.mkdirP(bp); - } - core.addPath(bp); - added = true; - } - return added; - }); +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + + Buffer.from(this.username + ':' + this.password).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } } -exports.addBinToPath = addBinToPath; -function isGhes() { - const ghUrl = new url_1.URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = 'Bearer ' + this.token; + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } } -//# sourceMappingURL=main.js.map - -/***/ }), - -/***/ 211: -/***/ (function(module) { +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -module.exports = require("https"); /***/ }), @@ -3754,6 +3297,13 @@ function coerce (version, options) { } +/***/ }), + +/***/ 304: +/***/ (function(module) { + +module.exports = require("string_decoder"); + /***/ }), /***/ 357: @@ -4777,7 +4327,6 @@ function _getGlobal(key, defaultValue) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const url = __webpack_require__(835); const http = __webpack_require__(605); const https = __webpack_require__(211); const pm = __webpack_require__(950); @@ -4826,7 +4375,7 @@ var MediaTypes; * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); + let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; @@ -4845,6 +4394,15 @@ const HttpResponseRetryCodes = [ const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } +} +exports.HttpClientError = HttpClientError; class HttpClientResponse { constructor(message) { this.message = message; @@ -4863,7 +4421,7 @@ class HttpClientResponse { } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { - let parsedUrl = url.parse(requestUrl); + let parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; @@ -4968,7 +4526,7 @@ class HttpClient { if (this._disposed) { throw new Error('Client has already been disposed.'); } - let parsedUrl = url.parse(requestUrl); + let parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 @@ -5007,7 +4565,7 @@ class HttpClient { // if there's no location to redirect to, we won't break; } - let parsedRedirectUrl = url.parse(redirectUrl); + let parsedRedirectUrl = new URL(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { @@ -5123,7 +4681,7 @@ class HttpClient { * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { - let parsedUrl = url.parse(serverUrl); + let parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { @@ -5196,7 +4754,9 @@ class HttpClient { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { - proxyAuth: proxyUrl.auth, + ...((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), host: proxyUrl.hostname, port: proxyUrl.port } @@ -5291,12 +4851,8 @@ class HttpClient { else { msg = 'Failed request: (' + statusCode + ')'; } - let err = new Error(msg); - // attach statusCode and body obj (if available) to the error object - err['statusCode'] = statusCode; - if (response.result) { - err['result'] = response.result; - } + let err = new HttpClientError(msg, statusCode); + err.result = response.result; reject(err); } else { @@ -5329,72 +4885,6 @@ module.exports = require("events"); module.exports = require("path"); -/***/ }), - -/***/ 623: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + - Buffer.from(this.username + ':' + this.password).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = 'Bearer ' + this.token; - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; - - /***/ }), /***/ 631: @@ -5402,71 +4892,6 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand module.exports = require("net"); -/***/ }), - -/***/ 651: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -function getProxyUrl(reqUrl) { - let usingSsl = reqUrl.protocol === 'https:'; - let proxyUrl; - if (checkBypass(reqUrl)) { - return proxyUrl; - } - let proxyVar; - if (usingSsl) { - proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - if (proxyVar) { - proxyUrl = new URL(proxyVar); - } - return proxyUrl; -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - let upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (let upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; - } - } - return false; -} -exports.checkBypass = checkBypass; - - /***/ }), /***/ 669: @@ -5770,8 +5195,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OidcClient = void 0; -const http_client_1 = __webpack_require__(192); -const auth_1 = __webpack_require__(623); +const http_client_1 = __webpack_require__(539); +const auth_1 = __webpack_require__(226); const core_1 = __webpack_require__(470); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { @@ -6086,8 +5511,8 @@ exports.getVersionsDist = getVersionsDist; // Convert the go version syntax into semver for semver matching // 1.13.1 => 1.13.1 // 1.13 => 1.13.0 -// 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1 -// 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 +// 1.10beta1 => 1.10.0-beta.1, 1.10rc1 => 1.10.0-rc.1 +// 1.8.5beta1 => 1.8.5-beta.1, 1.8.5rc1 => 1.8.5-rc.1 function makeSemver(version) { var _a; version = version.replace('go', ''); @@ -6162,12 +5587,11 @@ module.exports = require("url"); /***/ }), /***/ 950: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const url = __webpack_require__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; @@ -6182,7 +5606,7 @@ function getProxyUrl(reqUrl) { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { - proxyUrl = url.parse(proxyVar); + proxyUrl = new URL(proxyVar); } return proxyUrl; } @@ -6309,6 +5733,25 @@ exports.RetryHelper = RetryHelper; "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; 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) { @@ -6318,14 +5761,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge 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 }); +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __webpack_require__(304); const tr = __importStar(__webpack_require__(9)); /** * Exec a command. @@ -6351,6 +5789,51 @@ function exec(commandLine, args, options) { }); } exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; + const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); +} +exports.getExecOutput = getExecOutput; //# sourceMappingURL=exec.js.map /***/ }) diff --git a/src/installer.ts b/src/installer.ts index 7fef3cdf3..b9d6c36fb 100644 --- a/src/installer.ts +++ b/src/installer.ts @@ -271,8 +271,8 @@ export async function getVersionsDist( // Convert the go version syntax into semver for semver matching // 1.13.1 => 1.13.1 // 1.13 => 1.13.0 -// 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1 -// 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 +// 1.10beta1 => 1.10.0-beta.1, 1.10rc1 => 1.10.0-rc.1 +// 1.8.5beta1 => 1.8.5-beta.1, 1.8.5rc1 => 1.8.5-rc.1 export function makeSemver(version: string): string { version = version.replace('go', ''); version = version.replace('beta', '-beta.').replace('rc', '-rc.'); diff --git a/src/main.ts b/src/main.ts index 452308f4e..f785b85da 100644 --- a/src/main.ts +++ b/src/main.ts @@ -14,11 +14,7 @@ export async function run() { // let versionSpec = core.getInput('go-version'); - // stable will be true unless false is the exact input - // since getting unstable versions should be explicit - let stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE'; - - core.info(`Setup go ${stable ? 'stable' : ''} version spec ${versionSpec}`); + core.info(`Setup go version spec ${versionSpec}`); if (versionSpec) { let token = core.getInput('token'); From 2c166f1880999f6c9a5abe8d857636ed5fd6e4d6 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Thu, 24 Feb 2022 12:52:46 +0300 Subject: [PATCH 6/7] rebuild --- dist/index.js | 1134 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 824 insertions(+), 310 deletions(-) diff --git a/dist/index.js b/dist/index.js index 171d28da1..9a99b416d 100644 --- a/dist/index.js +++ b/dist/index.js @@ -345,25 +345,6 @@ function copyFile(srcFile, destFile, force) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; 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) { @@ -373,15 +354,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge 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 }); -exports.argStringToArray = exports.ToolRunner = void 0; const os = __importStar(__webpack_require__(87)); const events = __importStar(__webpack_require__(614)); const child = __importStar(__webpack_require__(129)); const path = __importStar(__webpack_require__(622)); const io = __importStar(__webpack_require__(1)); const ioUtil = __importStar(__webpack_require__(672)); -const timers_1 = __webpack_require__(213); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* @@ -451,12 +437,11 @@ class ToolRunner extends events.EventEmitter { s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } - return s; + strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); - return ''; } } _getSpawnFileName() { @@ -738,7 +723,7 @@ class ToolRunner extends events.EventEmitter { // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { @@ -752,12 +737,9 @@ class ToolRunner extends events.EventEmitter { state.on('debug', (message) => { this._debug(message); }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ''; + const stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { @@ -766,14 +748,14 @@ class ToolRunner extends events.EventEmitter { if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } - let errbuffer = ''; + const errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; @@ -788,7 +770,7 @@ class ToolRunner extends events.EventEmitter { : optionsNonNull.outStream; s.write(data); } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } @@ -835,7 +817,7 @@ class ToolRunner extends events.EventEmitter { } cp.stdin.end(this.options.input); } - })); + }); }); } } @@ -921,7 +903,7 @@ class ExecState extends events.EventEmitter { this._setResult(); } else if (this.processExited) { - this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); + this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { @@ -1494,205 +1476,677 @@ main_1.run(); /***/ }), -/***/ 198: +/***/ 192: /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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 __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -exports.addBinToPath = exports.run = void 0; -const core = __importStar(__webpack_require__(470)); -const io = __importStar(__webpack_require__(1)); -const installer = __importStar(__webpack_require__(749)); -const path_1 = __importDefault(__webpack_require__(622)); -const child_process_1 = __importDefault(__webpack_require__(129)); -const fs_1 = __importDefault(__webpack_require__(747)); -const url_1 = __webpack_require__(835); -function run() { - return __awaiter(this, void 0, void 0, function* () { - try { - // - // versionSpec is optional. If supplied, install / use from the tool cache - // If not supplied then problem matchers will still be setup. Useful for self-hosted. - // - let versionSpec = core.getInput('go-version'); - core.info(`Setup go version spec ${versionSpec}`); - if (versionSpec) { - let token = core.getInput('token'); - let auth = !token || isGhes() ? undefined : `token ${token}`; - const checkLatest = core.getBooleanInput('check-latest'); - const installDir = yield installer.getGo(versionSpec, checkLatest, auth); - core.exportVariable('GOROOT', installDir); - core.addPath(path_1.default.join(installDir, 'bin')); - core.info('Added go to the path'); - let added = yield addBinToPath(); - core.debug(`add bin ${added}`); - core.info(`Successfully setup go version ${versionSpec}`); - } - // add problem matchers - const matchersPath = path_1.default.join(__dirname, '..', 'matchers.json'); - core.info(`##[add-matcher]${matchersPath}`); - // output the version actually being used - let goPath = yield io.which('go'); - let goVersion = (child_process_1.default.execSync(`${goPath} version`) || '').toString(); - core.info(goVersion); - core.startGroup('go env'); - let goEnv = (child_process_1.default.execSync(`${goPath} env`) || '').toString(); - core.info(goEnv); - core.endGroup(); - } - catch (error) { - core.setFailed(error.message); - } - }); -} -exports.run = run; -function addBinToPath() { - return __awaiter(this, void 0, void 0, function* () { - let added = false; - let g = yield io.which('go'); - core.debug(`which go :${g}:`); - if (!g) { - core.debug('go not in the path'); - return added; - } - let buf = child_process_1.default.execSync('go env GOPATH'); - if (buf) { - let gp = buf.toString().trim(); - core.debug(`go env GOPATH :${gp}:`); - if (!fs_1.default.existsSync(gp)) { - // some of the hosted images have go install but not profile dir - core.debug(`creating ${gp}`); - io.mkdirP(gp); - } - let bp = path_1.default.join(gp, 'bin'); - if (!fs_1.default.existsSync(bp)) { - core.debug(`creating ${bp}`); - io.mkdirP(bp); - } - core.addPath(bp); - added = true; - } - return added; - }); +const http = __webpack_require__(605); +const https = __webpack_require__(211); +const pm = __webpack_require__(651); +let tunnel; +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } -exports.addBinToPath = addBinToPath; -function isGhes() { - const ghUrl = new url_1.URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } } -//# sourceMappingURL=main.js.map - -/***/ }), - -/***/ 211: -/***/ (function(module) { - -module.exports = require("https"); - -/***/ }), - -/***/ 213: -/***/ (function(module) { - -module.exports = require("timers"); - -/***/ }), - -/***/ 226: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; } - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + - Buffer.from(this.username + ':' + this.password).toString('base64'); + readBody() { + return new Promise(async (resolve, reject) => { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + }); } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + let parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + } + get(requestUrl, additionalHeaders) { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + } + del(requestUrl, additionalHeaders) { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + } + post(requestUrl, data, additionalHeaders) { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + } + patch(requestUrl, data, additionalHeaders) { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + } + put(requestUrl, data, additionalHeaders) { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + } + head(requestUrl, additionalHeaders) { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return this.request(verb, requestUrl, stream, additionalHeaders); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + async getJson(requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + let res = await this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async postJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async putJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async patchJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + async request(verb, requestUrl, data, headers) { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + let parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + while (numTries < maxTries) { + response = await this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (let i = 0; i < this.handlers.length; i++) { + if (this.handlers[i].canHandleAuthentication(response)) { + authenticationHandler = this.handlers[i]; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + let parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol == 'https:' && + parsedUrl.protocol != parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + await response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (let header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = await this.requestRaw(info, data); + redirectsRemaining--; + } + if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + await response.readBody(); + await this._performExponentialBackoff(numTries); + } + } + return response; + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return new Promise((resolve, reject) => { + let callbackForResult = function (err, res) { + if (err) { + reject(err); + } + resolve(res); + }; + this.requestRawWithCallback(info, data, callbackForResult); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + let socket; + if (typeof data === 'string') { + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + let handleResult = (err, res) => { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + }; + let req = info.httpModule.request(info.options, (msg) => { + let res = new HttpClientResponse(msg); + handleResult(null, res); + }); + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error('Request timeout: ' + info.options.path), null); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err, null); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + let parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + this.handlers.forEach(handler => { + handler.prepareRequest(info.options); + }); + } + return info; } - handleAuthentication(httpClient, requestInfo, objs) { - return null; + _mergeHeaders(headers) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); + } + return lowercaseKeys(headers || {}); } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = 'Bearer ' + this.token; + _getAgent(parsedUrl) { + let agent; + let proxyUrl = pm.getProxyUrl(parsedUrl); + let useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (!!agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (!!this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (useProxy) { + // If using proxy, need tunnel + if (!tunnel) { + tunnel = __webpack_require__(413); + } + const agentOptions = { + maxSockets: maxSockets, + keepAlive: this._keepAlive, + proxy: { + ...((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), + host: proxyUrl.hostname, + port: proxyUrl.port + } + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; + _performExponentialBackoff(retryNumber) { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); } - handleAuthentication(httpClient, requestInfo, objs) { - return null; + static dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + let a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + async _processResponse(res, options) { + return new Promise(async (resolve, reject) => { + const statusCode = res.message.statusCode; + const response = { + statusCode: statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode == HttpCodes.NotFound) { + resolve(response); + } + let obj; + let contents; + // get the result from the body + try { + contents = await res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = 'Failed request: (' + statusCode + ')'; + } + let err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + }); } } -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } +exports.HttpClient = HttpClient; + + +/***/ }), + +/***/ 198: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addBinToPath = exports.run = void 0; +const core = __importStar(__webpack_require__(470)); +const io = __importStar(__webpack_require__(1)); +const installer = __importStar(__webpack_require__(749)); +const path_1 = __importDefault(__webpack_require__(622)); +const child_process_1 = __importDefault(__webpack_require__(129)); +const fs_1 = __importDefault(__webpack_require__(747)); +const url_1 = __webpack_require__(835); +function run() { + return __awaiter(this, void 0, void 0, function* () { + try { + // + // versionSpec is optional. If supplied, install / use from the tool cache + // If not supplied then problem matchers will still be setup. Useful for self-hosted. + // + let versionSpec = core.getInput('go-version'); + core.info(`Setup go version spec ${versionSpec}`); + if (versionSpec) { + let token = core.getInput('token'); + let auth = !token || isGhes() ? undefined : `token ${token}`; + const checkLatest = core.getBooleanInput('check-latest'); + const installDir = yield installer.getGo(versionSpec, checkLatest, auth); + core.exportVariable('GOROOT', installDir); + core.addPath(path_1.default.join(installDir, 'bin')); + core.info('Added go to the path'); + let added = yield addBinToPath(); + core.debug(`add bin ${added}`); + core.info(`Successfully setup go version ${versionSpec}`); + } + // add problem matchers + const matchersPath = path_1.default.join(__dirname, '..', 'matchers.json'); + core.info(`##[add-matcher]${matchersPath}`); + // output the version actually being used + let goPath = yield io.which('go'); + let goVersion = (child_process_1.default.execSync(`${goPath} version`) || '').toString(); + core.info(goVersion); + core.startGroup('go env'); + let goEnv = (child_process_1.default.execSync(`${goPath} env`) || '').toString(); + core.info(goEnv); + core.endGroup(); + } + catch (error) { + core.setFailed(error.message); + } + }); +} +exports.run = run; +function addBinToPath() { + return __awaiter(this, void 0, void 0, function* () { + let added = false; + let g = yield io.which('go'); + core.debug(`which go :${g}:`); + if (!g) { + core.debug('go not in the path'); + return added; + } + let buf = child_process_1.default.execSync('go env GOPATH'); + if (buf) { + let gp = buf.toString().trim(); + core.debug(`go env GOPATH :${gp}:`); + if (!fs_1.default.existsSync(gp)) { + // some of the hosted images have go install but not profile dir + core.debug(`creating ${gp}`); + io.mkdirP(gp); + } + let bp = path_1.default.join(gp, 'bin'); + if (!fs_1.default.existsSync(bp)) { + core.debug(`creating ${bp}`); + io.mkdirP(bp); + } + core.addPath(bp); + added = true; + } + return added; + }); } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +exports.addBinToPath = addBinToPath; +function isGhes() { + const ghUrl = new url_1.URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +//# sourceMappingURL=main.js.map + +/***/ }), +/***/ 211: +/***/ (function(module) { + +module.exports = require("https"); /***/ }), @@ -3297,13 +3751,6 @@ function coerce (version, options) { } -/***/ }), - -/***/ 304: -/***/ (function(module) { - -module.exports = require("string_decoder"); - /***/ }), /***/ 357: @@ -4327,6 +4774,7 @@ function _getGlobal(key, defaultValue) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +const url = __webpack_require__(835); const http = __webpack_require__(605); const https = __webpack_require__(211); const pm = __webpack_require__(950); @@ -4375,7 +4823,7 @@ var MediaTypes; * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + let proxyUrl = pm.getProxyUrl(url.parse(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; @@ -4394,15 +4842,6 @@ const HttpResponseRetryCodes = [ const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; class HttpClientResponse { constructor(message) { this.message = message; @@ -4421,7 +4860,7 @@ class HttpClientResponse { } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { - let parsedUrl = new URL(requestUrl); + let parsedUrl = url.parse(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; @@ -4526,7 +4965,7 @@ class HttpClient { if (this._disposed) { throw new Error('Client has already been disposed.'); } - let parsedUrl = new URL(requestUrl); + let parsedUrl = url.parse(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 @@ -4565,7 +5004,7 @@ class HttpClient { // if there's no location to redirect to, we won't break; } - let parsedRedirectUrl = new URL(redirectUrl); + let parsedRedirectUrl = url.parse(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { @@ -4681,7 +5120,7 @@ class HttpClient { * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); + let parsedUrl = url.parse(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { @@ -4754,9 +5193,7 @@ class HttpClient { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), + proxyAuth: proxyUrl.auth, host: proxyUrl.hostname, port: proxyUrl.port } @@ -4851,8 +5288,12 @@ class HttpClient { else { msg = 'Failed request: (' + statusCode + ')'; } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; + let err = new Error(msg); + // attach statusCode and body obj (if available) to the error object + err['statusCode'] = statusCode; + if (response.result) { + err['result'] = response.result; + } reject(err); } else { @@ -4885,6 +5326,72 @@ module.exports = require("events"); module.exports = require("path"); +/***/ }), + +/***/ 623: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + + Buffer.from(this.username + ':' + this.password).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = 'Bearer ' + this.token; + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; + } + handleAuthentication(httpClient, requestInfo, objs) { + return null; + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; + + /***/ }), /***/ 631: @@ -4892,6 +5399,71 @@ module.exports = require("path"); module.exports = require("net"); +/***/ }), + +/***/ 651: +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +function getProxyUrl(reqUrl) { + let usingSsl = reqUrl.protocol === 'https:'; + let proxyUrl; + if (checkBypass(reqUrl)) { + return proxyUrl; + } + let proxyVar; + if (usingSsl) { + proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + if (proxyVar) { + proxyUrl = new URL(proxyVar); + } + return proxyUrl; +} +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + let upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (let upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperReqHosts.some(x => x === upperNoProxyItem)) { + return true; + } + } + return false; +} +exports.checkBypass = checkBypass; + + /***/ }), /***/ 669: @@ -5195,8 +5767,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OidcClient = void 0; -const http_client_1 = __webpack_require__(539); -const auth_1 = __webpack_require__(226); +const http_client_1 = __webpack_require__(192); +const auth_1 = __webpack_require__(623); const core_1 = __webpack_require__(470); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { @@ -5587,11 +6159,12 @@ module.exports = require("url"); /***/ }), /***/ 950: -/***/ (function(__unusedmodule, exports) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +const url = __webpack_require__(835); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; @@ -5606,7 +6179,7 @@ function getProxyUrl(reqUrl) { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { - proxyUrl = new URL(proxyVar); + proxyUrl = url.parse(proxyVar); } return proxyUrl; } @@ -5733,25 +6306,6 @@ exports.RetryHelper = RetryHelper; "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; 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) { @@ -5761,9 +6315,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge 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 }); -exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __webpack_require__(304); const tr = __importStar(__webpack_require__(9)); /** * Exec a command. @@ -5789,51 +6348,6 @@ function exec(commandLine, args, options) { }); } exports.exec = exec; -/** - * Exec a command and get the output. - * Output will be streamed to the live console. - * Returns promise with the exit code and collected stdout and stderr - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code, stdout, and stderr - */ -function getExecOutput(commandLine, args, options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - let stdout = ''; - let stderr = ''; - //Using string decoder covers the case where a mult-byte character is split - const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); - const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - //flush any remaining characters - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; - }); -} -exports.getExecOutput = getExecOutput; //# sourceMappingURL=exec.js.map /***/ }) From 0a17f6b30b13f09fc87aaca4798164f31eff909b Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Thu, 24 Feb 2022 17:26:03 +0300 Subject: [PATCH 7/7] change version to parts --- dist/index.js | 2 +- src/installer.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/index.js b/dist/index.js index 9a99b416d..ac3d0e5c1 100644 --- a/dist/index.js +++ b/dist/index.js @@ -6090,7 +6090,7 @@ function makeSemver(version) { version = version.replace('go', ''); version = version.replace('beta', '-beta.').replace('rc', '-rc.'); let parts = version.split('-'); - let semVersion = (_a = semver.coerce(version)) === null || _a === void 0 ? void 0 : _a.version; + let semVersion = (_a = semver.coerce(parts[0])) === null || _a === void 0 ? void 0 : _a.version; if (!semVersion) { throw new Error(`The version: ${version} can't be changed to SemVer notation`); } diff --git a/src/installer.ts b/src/installer.ts index b9d6c36fb..46eecc35a 100644 --- a/src/installer.ts +++ b/src/installer.ts @@ -278,7 +278,7 @@ export function makeSemver(version: string): string { version = version.replace('beta', '-beta.').replace('rc', '-rc.'); let parts = version.split('-'); - let semVersion = semver.coerce(version)?.version; + let semVersion = semver.coerce(parts[0])?.version; if (!semVersion) { throw new Error( `The version: ${version} can't be changed to SemVer notation`