4
0
Fork 0
mirror of https://github.com/Azure/setup-helm.git synced 2025-11-07 21:16:57 +00:00

Merge pull request #1 from taakleton/asgayle/setup-helm-refactor

Asgayle/setup helm refactor
This commit is contained in:
Asa Gayle 2022-01-13 16:31:28 -05:00 committed by GitHub
commit db9832f989
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 215 additions and 208 deletions

View file

@ -2,25 +2,6 @@
// Copyright (c) Microsoft Corporation. // Copyright (c) Microsoft Corporation.
// Copyright (c) Microsoft Corporation. // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license. // Licensed under the MIT license.
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) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
@ -30,29 +11,53 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __generator = (this && this.__generator) || function (thisArg, body) {
exports.getStableHelmVersion = void 0; var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
const os = __importStar(require("os")); return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
const path = __importStar(require("path")); function verb(n) { return function (v) { return step([n, v]); }; }
const util = __importStar(require("util")); function step(op) {
const fs = __importStar(require("fs")); if (f) throw new TypeError("Generator is already executing.");
const semver = __importStar(require("semver")); while (_) try {
const toolCache = __importStar(require("@actions/tool-cache")); if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
const core = __importStar(require("@actions/core")); if (y = 0, t) op = [op[0] & 2, t.value];
const graphql_1 = require("@octokit/graphql"); switch (op[0]) {
const helmToolName = 'helm'; case 0: case 1: t = op; break;
const stableHelmVersion = 'v3.2.1'; case 4: _.label++; return { value: op[1], done: false };
const stableHelm3Version = 'v3.5.3'; case 5: _.label++; y = op[1]; op = [0]; continue;
const stableHelm2Version = 'v2.17.0'; case 7: op = _.ops.pop(); _.trys.pop(); continue;
const LATEST_HELM2_VERSION = '2.*'; default:
const LATEST_HELM3_VERSION = '3.*'; if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
const helmAllReleasesUrl = 'https://api.github.com/repos/helm/helm/releases'; if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.run = exports.findHelm = exports.downloadHelm = exports.walkSync = exports.getStableHelmVersion = exports.getHelmDownloadURL = exports.getExecutableExtension = void 0;
var os = require("os");
var path = require("path");
var util = require("util");
var fs = require("fs");
var semver = require("semver");
var exec = require("@actions/exec");
var toolCache = require("@actions/tool-cache");
var core = require("@actions/core");
var helmToolName = 'helm';
var stableHelmVersion = 'v3.7.1';
var helmAllReleasesUrl = 'https://api.github.com/repos/helm/helm/releases';
function getExecutableExtension() { function getExecutableExtension() {
if (os.type().match(/^Win/)) { if (os.type().match(/^Win/)) {
return '.exe'; return '.exe';
} }
return ''; return '';
} }
exports.getExecutableExtension = getExecutableExtension;
function getHelmDownloadURL(version) { function getHelmDownloadURL(version) {
switch (os.type()) { switch (os.type()) {
case 'Linux': case 'Linux':
@ -64,30 +69,39 @@ function getHelmDownloadURL(version) {
return util.format('https://get.helm.sh/helm-%s-windows-amd64.zip', version); return util.format('https://get.helm.sh/helm-%s-windows-amd64.zip', version);
} }
} }
exports.getHelmDownloadURL = getHelmDownloadURL;
function getStableHelmVersion() { function getStableHelmVersion() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function () {
try { var downloadPath, responseArray, latestHelmVersion_1, error_1;
const downloadPath = yield toolCache.downloadTool(helmAllReleasesUrl); return __generator(this, function (_a) {
const responseArray = JSON.parse(fs.readFileSync(downloadPath, 'utf8').toString().trim()); switch (_a.label) {
let latestHelmVersion = semver.clean(stableHelmVersion); case 0:
responseArray.forEach(response => { _a.trys.push([0, 2, , 3]);
if (response && response.tag_name) { return [4 /*yield*/, toolCache.downloadTool(helmAllReleasesUrl)];
let currentHelmVerison = semver.clean(response.tag_name.toString()); case 1:
if (currentHelmVerison) { downloadPath = _a.sent();
if (currentHelmVerison.toString().indexOf('rc') == -1 && semver.gt(currentHelmVerison, latestHelmVersion)) { responseArray = JSON.parse(fs.readFileSync(downloadPath, 'utf8').toString().trim());
//If current helm version is not a pre release and is greater than latest helm version latestHelmVersion_1 = semver.clean(stableHelmVersion);
latestHelmVersion = currentHelmVerison; responseArray.forEach(function (response) {
if (response && response.tag_name) {
var currentHelmVerison = semver.clean(response.tag_name.toString());
if (currentHelmVerison) {
if (currentHelmVerison.toString().indexOf('rc') == -1 && semver.gt(currentHelmVerison, latestHelmVersion_1)) {
//If current helm version is not a pre release and is greater than latest helm version
latestHelmVersion_1 = currentHelmVerison;
}
}
} }
} });
} latestHelmVersion_1 = "v" + latestHelmVersion_1;
}); return [2 /*return*/, latestHelmVersion_1];
latestHelmVersion = "v" + latestHelmVersion; case 2:
return latestHelmVersion; error_1 = _a.sent();
} core.warning(util.format("Cannot get the latest Helm info from %s. Error %s. Using default Helm version %s.", helmAllReleasesUrl, error_1, stableHelmVersion));
catch (error) { return [3 /*break*/, 3];
core.warning(util.format("Cannot get the latest Helm info from %s. Error %s. Using default Helm version %s.", helmAllReleasesUrl, error, stableHelmVersion)); case 3: return [2 /*return*/, stableHelmVersion];
} }
return stableHelmVersion; });
}); });
} }
exports.getStableHelmVersion = getStableHelmVersion; exports.getStableHelmVersion = getStableHelmVersion;
@ -96,7 +110,7 @@ var walkSync = function (dir, filelist, fileToFind) {
filelist = filelist || []; filelist = filelist || [];
files.forEach(function (file) { files.forEach(function (file) {
if (fs.statSync(path.join(dir, file)).isDirectory()) { if (fs.statSync(path.join(dir, file)).isDirectory()) {
filelist = walkSync(path.join(dir, file), filelist, fileToFind); filelist = (0, exports.walkSync)(path.join(dir, file), filelist, fileToFind);
} }
else { else {
core.debug(file); core.debug(file);
@ -107,64 +121,80 @@ var walkSync = function (dir, filelist, fileToFind) {
}); });
return filelist; return filelist;
}; };
exports.walkSync = walkSync;
function downloadHelm(version) { function downloadHelm(version) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function () {
if (!version) { var cachedToolpath, helmDownloadPath, exception_1, unzipedHelmPath, helmpath;
version = yield getLatestHelmVersionFor("v3"); return __generator(this, function (_a) {
} switch (_a.label) {
let cachedToolpath = toolCache.find(helmToolName, version); case 0:
if (!cachedToolpath) { if (!!version) return [3 /*break*/, 2];
let helmDownloadPath; return [4 /*yield*/, getStableHelmVersion()];
try { case 1:
helmDownloadPath = yield toolCache.downloadTool(getHelmDownloadURL(version)); version = _a.sent();
} _a.label = 2;
catch (exception) { case 2:
throw new Error(util.format("Failed to download Helm from location ", getHelmDownloadURL(version))); cachedToolpath = toolCache.find(helmToolName, version);
} if (!!cachedToolpath) return [3 /*break*/, 9];
fs.chmodSync(helmDownloadPath, '777'); helmDownloadPath = void 0;
const unzipedHelmPath = yield toolCache.extractZip(helmDownloadPath); _a.label = 3;
cachedToolpath = yield toolCache.cacheDir(unzipedHelmPath, helmToolName, version); case 3:
} _a.trys.push([3, 5, , 6]);
const helmpath = findHelm(cachedToolpath); return [4 /*yield*/, toolCache.downloadTool(getHelmDownloadURL(version))];
if (!helmpath) { case 4:
throw new Error(util.format("Helm executable not found in path ", cachedToolpath)); helmDownloadPath = _a.sent();
} return [3 /*break*/, 6];
fs.chmodSync(helmpath, '777'); case 5:
return helmpath; exception_1 = _a.sent();
}); throw new Error(util.format("Failed to download Helm from location", getHelmDownloadURL(version)));
} case 6:
function getLatestHelmVersionFor(type) { fs.chmodSync(helmDownloadPath, '777');
return __awaiter(this, void 0, void 0, function* () { return [4 /*yield*/, toolCache.extractZip(helmDownloadPath)];
const token = core.getInput('token', { 'required': true }); case 7:
try { unzipedHelmPath = _a.sent();
const { repository } = yield graphql_1.graphql(`{ return [4 /*yield*/, toolCache.cacheDir(unzipedHelmPath, helmToolName, version)];
repository(name: "helm", owner: "helm") { case 8:
releases(last: 100) { cachedToolpath = _a.sent();
nodes { _a.label = 9;
tagName case 9:
} helmpath = findHelm(cachedToolpath);
if (!helmpath) {
throw new Error(util.format("Helm executable not found in path", cachedToolpath));
} }
} fs.chmodSync(helmpath, '777');
}`, { return [2 /*return*/, helmpath];
headers: { }
authorization: `token ${token}` });
}
});
const releases = repository.releases.nodes.reverse();
let latestValidRelease = releases.find(release => isValidVersion(release.tagName, type));
if (latestValidRelease)
return latestValidRelease.tagName;
}
catch (err) {
core.warning(util.format("Error while fetching the latest Helm %s release. Error: %s. Using default Helm version %s.", type, err.toString(), getStableHelmVersionFor(type)));
return getStableHelmVersionFor(type);
}
core.warning(util.format("Could not find stable release for Helm %s. Using default Helm version %s.", type, getStableHelmVersionFor(type)));
return getStableHelmVersionFor(type);
}); });
} }
function getStableHelmVersionFor(type) { exports.downloadHelm = downloadHelm;
return type === "v2" ? stableHelm2Version : stableHelm3Version; function getLatestHelmVersion() {
return __awaiter(this, void 0, void 0, function () {
var command, latestHelm, latestHelmErr, options;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
command = "curl -Ls https://api.github.com/repos/helm/helm/releases | grep 'v3.[0-9]*.[0-9]*' | sed -E 's/ .*/helm/helm/releases/tag/tag/(v[0-9.]+)\".*/1/g' | head -1 | sed -E 's/.*tag///' | sed -E 's/\".*//'";
latestHelm = "";
latestHelmErr = "";
options = {};
options.listeners = {
stdout: function (data) {
latestHelm += data.toString();
},
stderr: function (data) {
latestHelmErr += data.toString();
}
};
return [4 /*yield*/, exec.exec(command, [], options)];
case 1:
_a.sent();
if (latestHelmErr !== "")
return [2 /*return*/, getStableHelmVersion()];
return [2 /*return*/, latestHelm];
}
});
});
} }
// isValidVersion checks if verison matches the specified type and is a stable release // isValidVersion checks if verison matches the specified type and is a stable release
function isValidVersion(version, type) { function isValidVersion(version, type) {
@ -175,48 +205,46 @@ function isValidVersion(version, type) {
function findHelm(rootFolder) { function findHelm(rootFolder) {
fs.chmodSync(rootFolder, '777'); fs.chmodSync(rootFolder, '777');
var filelist = []; var filelist = [];
walkSync(rootFolder, filelist, helmToolName + getExecutableExtension()); (0, exports.walkSync)(rootFolder, filelist, helmToolName + getExecutableExtension());
if (!filelist) { if (!filelist || filelist.length == 0) {
throw new Error(util.format("Helm executable not found in path ", rootFolder)); throw new Error(util.format("Helm executable not found in path", rootFolder));
} }
else { else {
return filelist[0]; return filelist[0];
} }
} }
exports.findHelm = findHelm;
function run() { function run() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function () {
let version = core.getInput('version', { 'required': true }); var version, cachedPath;
if (process.env['HELM_INSTALLER_LEGACY_VERSIONING'] == 'true') { return __generator(this, function (_a) {
if (version.toLocaleLowerCase() === 'latest') { switch (_a.label) {
version = yield getStableHelmVersion(); case 0:
version = core.getInput('version', { 'required': true });
if (!(version.toLocaleLowerCase() === 'latest')) return [3 /*break*/, 2];
return [4 /*yield*/, getLatestHelmVersion()];
case 1:
version = _a.sent();
_a.label = 2;
case 2:
core.debug(util.format("Downloading %s", version));
return [4 /*yield*/, downloadHelm(version)];
case 3:
cachedPath = _a.sent();
try {
if (!process.env['PATH'].startsWith(path.dirname(cachedPath))) {
core.addPath(path.dirname(cachedPath));
}
}
catch (_b) {
//do nothing, set as output variable
}
console.log("Helm tool version: '".concat(version, "' has been cached at ").concat(cachedPath));
core.setOutput('helm-path', cachedPath);
return [2 /*return*/];
} }
else if (!version.toLocaleLowerCase().startsWith('v')) { });
version = 'v' + version;
}
}
else {
if (version.toLocaleLowerCase() === 'latest' || version === LATEST_HELM3_VERSION) {
version = yield getLatestHelmVersionFor("v3");
}
else if (version === LATEST_HELM2_VERSION) {
version = yield getLatestHelmVersionFor("v2");
}
else if (!version.toLocaleLowerCase().startsWith('v')) {
version = 'v' + version;
}
}
core.debug(util.format("Downloading %s", version));
let cachedPath = yield downloadHelm(version);
try {
if (!process.env['PATH'].startsWith(path.dirname(cachedPath))) {
core.addPath(path.dirname(cachedPath));
}
}
catch (_a) {
//do nothing, set as output variable
}
console.log(`Helm tool version: '${version}' has been cached at ${cachedPath}`);
core.setOutput('helm-path', cachedPath);
}); });
} }
run().catch(core.setFailed); exports.run = run;
run()["catch"](core.setFailed);

View file

@ -8,6 +8,7 @@ import * as util from 'util';
import * as fs from 'fs'; import * as fs from 'fs';
import * as semver from 'semver'; import * as semver from 'semver';
import * as exec from '@actions/exec';
import * as toolCache from '@actions/tool-cache'; import * as toolCache from '@actions/tool-cache';
import * as core from '@actions/core'; import * as core from '@actions/core';
import { graphql } from '@octokit/graphql'; import { graphql } from '@octokit/graphql';
@ -108,6 +109,9 @@ export async function downloadHelm(version: string): Promise<string> {
return helmpath; return helmpath;
} }
async function getLatestHelmVersionForTest(type: string): Promise<string>{
exec.exec(`curl -Ls https://api.github.com/repos/helm/helm/releases | grep 'v3.[0-9]*.[0-9]*' | sed -E 's/ .*\/helm\/helm\/releases\/tag\/tag\/(v[0-9\.]+)".*/\1/g' | head -1 | sed -E 's/.*tag\///' | sed -E 's/".*//'`)
}
async function getLatestHelmVersionFor(type: string): Promise<string> { async function getLatestHelmVersionFor(type: string): Promise<string> {
const token = core.getInput('token', { 'required': true }); const token = core.getInput('token', { 'required': true });
try { try {

View file

@ -8,16 +8,13 @@ import * as util from 'util';
import * as fs from 'fs'; import * as fs from 'fs';
import * as semver from 'semver'; import * as semver from 'semver';
import * as exec from '@actions/exec';
import { ExecOptions } from '@actions/exec/lib/interfaces';
import * as toolCache from '@actions/tool-cache'; import * as toolCache from '@actions/tool-cache';
import * as core from '@actions/core'; import * as core from '@actions/core';
import { graphql } from '@octokit/graphql';
const helmToolName = 'helm'; const helmToolName = 'helm';
const stableHelmVersion = 'v3.2.1'; const stableHelmVersion = 'v3.7.1';
const stableHelm3Version = 'v3.5.3';
const stableHelm2Version = 'v2.17.0';
const LATEST_HELM2_VERSION = '2.*';
const LATEST_HELM3_VERSION = '3.*';
const helmAllReleasesUrl = 'https://api.github.com/repos/helm/helm/releases'; const helmAllReleasesUrl = 'https://api.github.com/repos/helm/helm/releases';
export function getExecutableExtension(): string { export function getExecutableExtension(): string {
@ -50,7 +47,7 @@ export async function getStableHelmVersion(): Promise<string> {
if (response && response.tag_name) { if (response && response.tag_name) {
let currentHelmVerison = semver.clean(response.tag_name.toString()); let currentHelmVerison = semver.clean(response.tag_name.toString());
if (currentHelmVerison) { if (currentHelmVerison) {
if (currentHelmVerison.toString().indexOf('rc') === -1 && semver.gt(currentHelmVerison, latestHelmVersion)) { if (currentHelmVerison.toString().indexOf('rc') == -1 && semver.gt(currentHelmVerison, latestHelmVersion)) {
//If current helm version is not a pre release and is greater than latest helm version //If current helm version is not a pre release and is greater than latest helm version
latestHelmVersion = currentHelmVerison; latestHelmVersion = currentHelmVerison;
} }
@ -75,9 +72,8 @@ export var walkSync = function (dir, filelist, fileToFind) {
} }
else { else {
core.debug(file); core.debug(file);
if (file === fileToFind) { if (file == fileToFind) {
filelist.push(path.join(dir, file)); filelist.push(path.join(dir, file));
return filelist;
} }
} }
}); });
@ -109,40 +105,26 @@ export async function downloadHelm(version: string): Promise<string> {
return helmpath; return helmpath;
} }
async function getLatestHelmVersionFor(type: string): Promise<string> { async function getLatestHelmVersion(): Promise<string>{
const token = core.getInput('token', { 'required': true }); const command:string = `curl -Ls https://api.github.com/repos/helm/helm/releases | grep 'v3.[0-9]*.[0-9]*' | sed -E 's/ .*\/helm\/helm\/releases\/tag\/tag\/(v[0-9\.]+)".*/\1/g' | head -1 | sed -E 's/.*tag\///' | sed -E 's/".*//'`;
try { let latestHelm: string = "";
const { repository } = await graphql( let latestHelmErr: string = "";
`{
repository(name: "helm", owner: "helm") {
releases(last: 100) {
nodes {
tagName
}
}
}
}`,
{
headers: {
authorization: `token ${token}`
}
}
);
const releases = repository.releases.nodes.reverse(); const options:ExecOptions = {};
let latestValidRelease = releases.find(release => isValidVersion(release.tagName, type));
if (latestValidRelease)
return latestValidRelease.tagName;
} catch (err) {
core.warning(util.format("Error while fetching the latest Helm %s release. Error: %s. Using default Helm version %s.", type, err.toString(), getStableHelmVersionFor(type)));
return getStableHelmVersionFor(type);
}
core.warning(util.format("Could not find stable release for Helm %s. Using default Helm version %s.", type, getStableHelmVersionFor(type)));
return getStableHelmVersionFor(type);
}
function getStableHelmVersionFor(type: string) { options.listeners = {
return type === "v2" ? stableHelm2Version : stableHelm3Version; stdout: (data: Buffer) => {
latestHelm += data.toString();
},
stderr: (data: Buffer) => {
latestHelmErr += data.toString();
}
};
await exec.exec(command, [], options);
if(latestHelmErr !== "") return getStableHelmVersion();
return latestHelm;
} }
// isValidVersion checks if verison matches the specified type and is a stable release // isValidVersion checks if verison matches the specified type and is a stable release
@ -167,29 +149,22 @@ export function findHelm(rootFolder: string): string {
export async function run() { export async function run() {
let version = core.getInput('version', { 'required': true }); let version = core.getInput('version', { 'required': true });
if (process.env['HELM_INSTALLER_LEGACY_VERSIONING'] == 'true') { if (version.toLocaleLowerCase() === 'latest') {
if (version.toLocaleLowerCase() === 'latest') { version = await getLatestHelmVersion();
version = await getStableHelmVersion();
} else if (!version.toLocaleLowerCase().startsWith('v')) {
version = 'v' + version;
}
} else {
if (version.toLocaleLowerCase() === 'latest' || version === LATEST_HELM3_VERSION) {
version = await getLatestHelmVersionFor("v3");
} else if (version === LATEST_HELM2_VERSION) {
version = await getLatestHelmVersionFor("v2");
} else if (!version.toLocaleLowerCase().startsWith('v')) {
version = 'v' + version;
}
} }
core.debug(util.format("Downloading %s", version)); core.debug(util.format("Downloading %s", version));
let cachedPath = await downloadHelm(version); let cachedPath = await downloadHelm(version);
if (!process.env['PATH'].startsWith(path.dirname(cachedPath))) { try {
core.addPath(path.dirname(cachedPath));
}
if (!process.env['PATH'].startsWith(path.dirname(cachedPath))) {
core.addPath(path.dirname(cachedPath));
}
}
catch {
//do nothing, set as output variable
}
console.log(`Helm tool version: '${version}' has been cached at ${cachedPath}`); console.log(`Helm tool version: '${version}' has been cached at ${cachedPath}`);
core.setOutput('helm-path', cachedPath); core.setOutput('helm-path', cachedPath);