@docker/actions-toolkit
Version:
Toolkit for Docker (GitHub) Actions
214 lines • 6.84 kB
JavaScript
/**
* Copyright 2023 actions-toolkit authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import * as core from '@actions/core';
import * as io from '@actions/io';
import { parse } from 'csv-parse/sync';
export class Util {
static getInputList(name, opts) {
return this.getList(core.getInput(name), opts);
}
static getList(input, opts) {
const res = [];
if (input == '') {
return res;
}
const records = parse(input, {
columns: false,
relaxQuotes: true,
comment: opts?.comment,
comment_no_infix: opts?.commentNoInfix,
relaxColumnCount: true,
skipEmptyLines: true,
quote: opts?.quote
});
for (const record of records) {
if (record.length == 1) {
if (opts?.ignoreComma) {
res.push(record[0]);
}
else {
res.push(...record[0].split(','));
}
}
else if (!opts?.ignoreComma) {
res.push(...record);
}
else {
res.push(record.join(','));
}
}
return res.filter(item => item).map(pat => pat.trim());
}
static getInputNumber(name) {
const value = core.getInput(name);
if (!value) {
return undefined;
}
return parseInt(value);
}
static async asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
static isValidURL(urlStr) {
let url;
try {
url = new URL(urlStr);
}
catch {
return false;
}
return url.protocol === 'http:' || url.protocol === 'https:';
}
static isValidRef(refStr) {
if (Util.isValidURL(refStr)) {
return true;
}
for (const prefix of ['git://', 'github.com/', 'git@']) {
if (refStr.startsWith(prefix)) {
return true;
}
}
return false;
}
static async powershellCommand(script, params) {
const powershellPath = await io.which('powershell', true);
const escapedScript = script.replace(/'/g, "''").replace(/"|\n|\r/g, '');
const escapedParams = [];
if (params) {
for (const key in params) {
escapedParams.push(`-${key} '${params[key].replace(/'/g, "''").replace(/"|\n|\r/g, '')}'`);
}
}
return {
command: `"${powershellPath}"`,
args: ['-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', `& '${escapedScript}' ${escapedParams.join(' ')}`]
};
}
static isDirectory(p) {
try {
return fs.lstatSync(p).isDirectory();
}
catch {
// noop
}
return false;
}
static trimPrefix(str, suffix) {
if (!str || !suffix) {
return str;
}
const index = str.indexOf(suffix);
if (index !== 0) {
return str;
}
return str.substring(suffix.length);
}
static trimSuffix(str, suffix) {
if (!str || !suffix) {
return str;
}
const index = str.lastIndexOf(suffix);
if (index === -1 || index + suffix.length !== str.length) {
return str;
}
return str.substring(0, index);
}
static sleep(seconds) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}
static hash(input) {
return crypto.createHash('sha256').update(input).digest('hex');
}
// https://github.com/golang/go/blob/f6b93a4c358b28b350dd8fe1780c1f78e520c09c/src/strconv/atob.go#L7-L18
static parseBool(str) {
if (str === undefined) {
return false;
}
switch (str) {
case '1':
case 't':
case 'T':
case 'true':
case 'TRUE':
case 'True':
return true;
case '0':
case 'f':
case 'F':
case 'false':
case 'FALSE':
case 'False':
return false;
default:
throw new Error(`parseBool syntax error: ${str}`);
}
}
static parseBoolOrDefault(str, defaultValue = false) {
try {
return this.parseBool(str);
}
catch {
return defaultValue;
}
}
static formatFileSize(bytes) {
if (bytes === 0)
return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
static generateRandomString(length = 10) {
const bytes = crypto.randomBytes(Math.ceil(length / 2));
return bytes.toString('hex').slice(0, length);
}
static stringToUnicodeEntities(str) {
return Array.from(str)
.map(char => `&#x${char.charCodeAt(0).toString(16)};`)
.join('');
}
static countLines(input) {
return input.split(/\r\n|\r|\n/).length;
}
static isPathRelativeTo(parentPath, childPath) {
const rpp = path.resolve(parentPath);
const rcp = path.resolve(childPath);
return rcp.startsWith(rpp.endsWith(path.sep) ? rpp : `${rpp}${path.sep}`);
}
static formatDuration(ns) {
if (ns === 0)
return '0s';
const totalSeconds = Math.floor(ns / 1e9);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const parts = [];
if (hours)
parts.push(`${hours}h`);
if (minutes)
parts.push(`${minutes}m`);
if (seconds || parts.length === 0)
parts.push(`${seconds}s`);
return parts.join('');
}
}
//# sourceMappingURL=util.js.map