setup-kubectl/src/run.ts

77 lines
2.7 KiB
TypeScript
Raw Normal View History

2019-09-10 12:10:21 +02:00
import * as os from 'os';
import * as path from 'path';
import * as util from 'util';
import * as fs from 'fs';
import * as toolCache from '@actions/tool-cache';
import * as core from '@actions/core';
const kubectlToolName = 'kubectl';
const stableKubectlVersion = 'v1.15.0';
const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt';
function getExecutableExtension(): string {
if (os.type().match(/^Win/)) {
return '.exe';
}
return '';
}
function getkubectlDownloadURL(version: string): string {
switch (os.type()) {
case 'Linux':
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/amd64/kubectl', version);
case 'Darwin':
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/amd64/kubectl', version);
case 'Windows_NT':
default:
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/amd64/kubectl.exe', version);
}
}
async function getStableKubectlVersion(): Promise<string> {
return toolCache.downloadTool(stableVersionUrl).then((downloadPath) => {
let version = fs.readFileSync(downloadPath, 'utf8').toString().trim();
if (!version) {
version = stableKubectlVersion;
}
return version;
}, (error) => {
core.debug(error);
core.warning('GetStableVersionFailed');
return stableKubectlVersion;
});
}
async function downloadKubectl(version: string): Promise<string> {
let cachedToolpath = toolCache.find(kubectlToolName, version);
let kubectlDownloadPath = '';
if (!cachedToolpath) {
try {
kubectlDownloadPath = await toolCache.downloadTool(getkubectlDownloadURL(version));
} catch (exception) {
throw new Error('DownloadKubectlFailed');
}
cachedToolpath = await toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version);
}
const kubectlPath = path.join(cachedToolpath, kubectlToolName + getExecutableExtension());
fs.chmodSync(kubectlPath, '777');
return kubectlPath;
}
async function run() {
let version = core.getInput('version', { 'required': true });
if (version.toLocaleLowerCase() === 'latest') {
version = await getStableKubectlVersion();
}
let cachedPath = await downloadKubectl(version);
console.log(`Kubectl tool version: '${version}' has been cached at ${cachedPath}`);
core.setOutput('kubectl-path', cachedPath);
}
run().catch(core.setFailed);