Set GOPATH to the default directory if unset

This commit is contained in:
CrazyMax 2019-09-04 01:36:31 +02:00 committed by CrazyMax
parent 595aed780b
commit eb3673a122
No known key found for this signature in database
GPG Key ID: 3248E46B6BB8C7F7
2 changed files with 234 additions and 207 deletions

View File

@ -1,205 +1,217 @@
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 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 rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
// Load tempDirectory before it gets wiped by tool-cache // Load tempDirectory before it gets wiped by tool-cache
let tempDirectory = process.env['RUNNER_TEMPDIRECTORY'] || ''; let tempDirectory = process.env['RUNNER_TEMPDIRECTORY'] || '';
const core = __importStar(require("@actions/core")); const core = __importStar(require("@actions/core"));
const tc = __importStar(require("@actions/tool-cache")); const tc = __importStar(require("@actions/tool-cache"));
const os = __importStar(require("os")); const os = __importStar(require("os"));
const path = __importStar(require("path")); const path = __importStar(require("path"));
const util = __importStar(require("util")); const util = __importStar(require("util"));
const semver = __importStar(require("semver")); const semver = __importStar(require("semver"));
const restm = __importStar(require("typed-rest-client/RestClient")); const restm = __importStar(require("typed-rest-client/RestClient"));
let osPlat = os.platform(); let osPlat = os.platform();
let osArch = os.arch(); let osArch = os.arch();
if (!tempDirectory) { if (!tempDirectory) {
let baseLocation; let baseLocation;
if (process.platform === 'win32') { if (process.platform === 'win32') {
// On windows use the USERPROFILE env variable // On windows use the USERPROFILE env variable
baseLocation = process.env['USERPROFILE'] || 'C:\\'; baseLocation = process.env['USERPROFILE'] || 'C:\\';
} }
else { else {
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
baseLocation = '/Users'; baseLocation = '/Users';
} }
else { else {
baseLocation = '/home'; baseLocation = '/home';
} }
} }
tempDirectory = path.join(baseLocation, 'actions', 'temp'); tempDirectory = path.join(baseLocation, 'actions', 'temp');
} }
function getGo(version) { function getGo(version) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const selected = yield determineVersion(version); const selected = yield determineVersion(version);
if (selected) { if (selected) {
version = selected; version = selected;
} }
// check cache // check cache
let toolPath; let toolPath;
toolPath = tc.find('go', normalizeVersion(version)); toolPath = tc.find('go', normalizeVersion(version));
if (!toolPath) { if (!toolPath) {
// download, extract, cache // download, extract, cache
toolPath = yield acquireGo(version); toolPath = yield acquireGo(version);
core.debug('Go tool is cached under ' + toolPath); core.debug('Go tool is cached under ' + toolPath);
} }
setGoEnvironmentVariables(toolPath); setGoEnvironmentVariables(toolPath);
toolPath = path.join(toolPath, 'bin'); toolPath = path.join(toolPath, 'bin');
// //
// prepend the tools path. instructs the agent to prepend for future tasks // prepend the tools path. instructs the agent to prepend for future tasks
// //
core.addPath(toolPath); core.addPath(toolPath);
}); });
} }
exports.getGo = getGo; exports.getGo = getGo;
function acquireGo(version) { function acquireGo(version) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
// //
// Download - a tool installer intimately knows how to get the tool (and construct urls) // Download - a tool installer intimately knows how to get the tool (and construct urls)
// //
let fileName = getFileName(version); let fileName = getFileName(version);
let downloadUrl = getDownloadUrl(fileName); let downloadUrl = getDownloadUrl(fileName);
let downloadPath = null; let downloadPath = null;
try { try {
downloadPath = yield tc.downloadTool(downloadUrl); downloadPath = yield tc.downloadTool(downloadUrl);
} }
catch (error) { catch (error) {
core.debug(error); core.debug(error);
throw `Failed to download version ${version}: ${error}`; throw `Failed to download version ${version}: ${error}`;
} }
// //
// Extract // Extract
// //
let extPath = tempDirectory; let extPath = tempDirectory;
if (!extPath) { if (!extPath) {
throw new Error('Temp directory not set'); throw new Error('Temp directory not set');
} }
if (osPlat == 'win32') { if (osPlat == 'win32') {
extPath = yield tc.extractZip(downloadPath); extPath = yield tc.extractZip(downloadPath);
} }
else { else {
extPath = yield tc.extractTar(downloadPath); extPath = yield tc.extractTar(downloadPath);
} }
// //
// Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded // Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded
// //
const toolRoot = path.join(extPath, 'go'); const toolRoot = path.join(extPath, 'go');
version = normalizeVersion(version); version = normalizeVersion(version);
return yield tc.cacheDir(toolRoot, 'go', version); return yield tc.cacheDir(toolRoot, 'go', version);
}); });
} }
function getFileName(version) { function getFileName(version) {
const platform = osPlat == 'win32' ? 'windows' : osPlat; const platform = osPlat == 'win32' ? 'windows' : osPlat;
const arch = osArch == 'x64' ? 'amd64' : '386'; const arch = osArch == 'x64' ? 'amd64' : '386';
const ext = osPlat == 'win32' ? 'zip' : 'tar.gz'; const ext = osPlat == 'win32' ? 'zip' : 'tar.gz';
const filename = util.format('go%s.%s-%s.%s', version, platform, arch, ext); const filename = util.format('go%s.%s-%s.%s', version, platform, arch, ext);
return filename; return filename;
} }
function getDownloadUrl(filename) { function getDownloadUrl(filename) {
return util.format('https://storage.googleapis.com/golang/%s', filename); return util.format('https://storage.googleapis.com/golang/%s', filename);
} }
function setGoEnvironmentVariables(goRoot) { function setGoEnvironmentVariables(goRoot) {
core.exportVariable('GOROOT', goRoot); core.exportVariable('GOROOT', goRoot);
const goPath = process.env['GOPATH'] || ''; const goPath = getGoPath();
const goBin = process.env['GOBIN'] || ''; const goBin = process.env['GOBIN'] || '';
// set GOPATH and GOBIN as user value // set GOPATH and GOBIN if defined
if (goPath) { if (goPath) {
core.exportVariable('GOPATH', goPath); core.exportVariable('GOPATH', goPath);
} core.addPath(path.join(goPath, 'bin'));
if (goBin) { }
core.exportVariable('GOBIN', goBin); if (goBin) {
} core.exportVariable('GOBIN', goBin);
} }
// This function is required to convert the version 1.10 to 1.10.0. }
// Because caching utility accept only sementic version, // Get GOPATH as user value or as defined by https://golang.org/doc/code.html#GOPATH
// which have patch number as well. function getGoPath() {
function normalizeVersion(version) { const home = process.env['HOME'] || '';
const versionPart = version.split('.'); const goPath = process.env['GOPATH'] || '';
if (versionPart[1] == null) { if (goPath) {
//append minor and patch version if not available return goPath;
return version.concat('.0.0'); } else if (home) {
} return path.join(home, 'go');
else { }
// handle beta and rc: 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1 return '';
if (versionPart[1].includes('beta') || versionPart[1].includes('rc')) { }
versionPart[1] = versionPart[1] // This function is required to convert the version 1.10 to 1.10.0.
.replace('beta', '.0-beta') // Because caching utility accept only sementic version,
.replace('rc', '.0-rc'); // which have patch number as well.
return versionPart.join('.'); function normalizeVersion(version) {
} const versionPart = version.split('.');
} if (versionPart[1] == null) {
if (versionPart[2] == null) { //append minor and patch version if not available
//append patch version if not available return version.concat('.0.0');
return version.concat('.0'); }
} else {
else { // handle beta and rc: 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1
// handle beta and rc: 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 if (versionPart[1].includes('beta') || versionPart[1].includes('rc')) {
if (versionPart[2].includes('beta') || versionPart[2].includes('rc')) { versionPart[1] = versionPart[1]
versionPart[2] = versionPart[2] .replace('beta', '.0-beta')
.replace('beta', '-beta') .replace('rc', '.0-rc');
.replace('rc', '-rc'); return versionPart.join('.');
return versionPart.join('.'); }
} }
} if (versionPart[2] == null) {
return version; //append patch version if not available
} return version.concat('.0');
function determineVersion(version) { }
return __awaiter(this, void 0, void 0, function* () { else {
if (!version.endsWith('.x')) { // handle beta and rc: 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1
const versionPart = version.split('.'); if (versionPart[2].includes('beta') || versionPart[2].includes('rc')) {
if (versionPart[1] == null || versionPart[2] == null) { versionPart[2] = versionPart[2]
return yield getLatestVersion(version.concat('.x')); .replace('beta', '-beta')
} .replace('rc', '-rc');
else { return versionPart.join('.');
return version; }
} }
} return version;
return yield getLatestVersion(version); }
}); function determineVersion(version) {
} return __awaiter(this, void 0, void 0, function* () {
function getLatestVersion(version) { if (!version.endsWith('.x')) {
return __awaiter(this, void 0, void 0, function* () { const versionPart = version.split('.');
// clean .x syntax: 1.10.x -> 1.10 if (versionPart[1] == null || versionPart[2] == null) {
const trimmedVersion = version.slice(0, version.length - 2); return yield getLatestVersion(version.concat('.x'));
const versions = yield getPossibleVersions(trimmedVersion); }
core.debug(`evaluating ${versions.length} versions`); else {
if (version.length === 0) { return version;
throw new Error('unable to get latest version'); }
} }
core.debug(`matched: ${versions[0]}`); return yield getLatestVersion(version);
return versions[0]; });
}); }
} function getLatestVersion(version) {
function getAvailableVersions() { return __awaiter(this, void 0, void 0, function* () {
return __awaiter(this, void 0, void 0, function* () { // clean .x syntax: 1.10.x -> 1.10
let rest = new restm.RestClient('setup-go'); const trimmedVersion = version.slice(0, version.length - 2);
let tags = (yield rest.get('https://api.github.com/repos/golang/go/git/refs/tags')).result || []; const versions = yield getPossibleVersions(trimmedVersion);
return tags core.debug(`evaluating ${versions.length} versions`);
.filter(tag => tag.ref.match(/go\d+\.[\w\.]+/g)) if (version.length === 0) {
.map(tag => tag.ref.replace('refs/tags/go', '')); throw new Error('unable to get latest version');
}); }
} core.debug(`matched: ${versions[0]}`);
function getPossibleVersions(version) { return versions[0];
return __awaiter(this, void 0, void 0, function* () { });
const versions = yield getAvailableVersions(); }
const possibleVersions = versions.filter(v => v.startsWith(version)); function getAvailableVersions() {
const versionMap = new Map(); return __awaiter(this, void 0, void 0, function* () {
possibleVersions.forEach(v => versionMap.set(normalizeVersion(v), v)); let rest = new restm.RestClient('setup-go');
return Array.from(versionMap.keys()) let tags = (yield rest.get('https://api.github.com/repos/golang/go/git/refs/tags')).result || [];
.sort(semver.rcompare) return tags
.map(v => versionMap.get(v)); .filter(tag => tag.ref.match(/go\d+\.[\w\.]+/g))
}); .map(tag => tag.ref.replace('refs/tags/go', ''));
} });
}
function getPossibleVersions(version) {
return __awaiter(this, void 0, void 0, function* () {
const versions = yield getAvailableVersions();
const possibleVersions = versions.filter(v => v.startsWith(version));
const versionMap = new Map();
possibleVersions.forEach(v => versionMap.set(normalizeVersion(v), v));
return Array.from(versionMap.keys())
.sort(semver.rcompare)
.map(v => versionMap.get(v));
});
}

View File

@ -109,18 +109,33 @@ function getDownloadUrl(filename: string): string {
function setGoEnvironmentVariables(goRoot: string) { function setGoEnvironmentVariables(goRoot: string) {
core.exportVariable('GOROOT', goRoot); core.exportVariable('GOROOT', goRoot);
const goPath: string = process.env['GOPATH'] || ''; const goPath = getGoPath();
const goBin: string = process.env['GOBIN'] || ''; const goBin = process.env['GOBIN'] || '';
// set GOPATH and GOBIN as user value // set GOPATH and GOBIN as user value
if (goPath) { if (goPath) {
core.exportVariable('GOPATH', goPath); core.exportVariable('GOPATH', goPath);
core.addPath(path.join(goPath, 'bin'));
} }
if (goBin) { if (goBin) {
core.exportVariable('GOBIN', goBin); core.exportVariable('GOBIN', goBin);
} }
} }
// Get GOPATH as user value or as defined by https://golang.org/doc/code.html#GOPATH
function getGoPath(): string {
const home: string = process.env['HOME'] || '';
const goPath: string = process.env['GOPATH'] || '';
if (goPath) {
return goPath;
} else if (home) {
return path.join(home, 'go');
}
return '';
}
// This function is required to convert the version 1.10 to 1.10.0. // This function is required to convert the version 1.10 to 1.10.0.
// Because caching utility accept only sementic version, // Because caching utility accept only sementic version,
// which have patch number as well. // which have patch number as well.