@142vip/utils
Version:
通用型基础工具集合,对常用模块的二次集成
1,553 lines (1,523 loc) • 51.6 kB
JavaScript
'use strict';
const node_buffer = require('node:buffer');
const fs = require('node:fs');
const nodePath = require('node:path');
const process = require('node:process');
const ansiColors = require('ansi-colors');
const childProcess = require('node:child_process');
const node_module = require('node:module');
const convertGitmoji = require('convert-gitmoji');
const originImportSemVer = require('semver');
const enums_index = require('./enums/index.cjs');
const json = require('klona/json');
const prompts = require('@inquirer/prompts');
const openSource = require('@142vip/open-source');
const jsYaml = require('js-yaml');
const commander = require('commander');
const cosmiconfig = require('cosmiconfig');
const _ = require('lodash');
const dayjs = require('dayjs');
const detectPort = require('detect-port');
const nanoid = require('nanoid');
const qs = require('qs');
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
function _interopNamespaceCompat(e) {
if (e && typeof e === 'object' && 'default' in e) return e;
const n = Object.create(null);
if (e) {
for (const k in e) {
n[k] = e[k];
}
}
n.default = e;
return n;
}
const fs__namespace = /*#__PURE__*/_interopNamespaceCompat(fs);
const nodePath__default = /*#__PURE__*/_interopDefaultCompat(nodePath);
const nodePath__namespace = /*#__PURE__*/_interopNamespaceCompat(nodePath);
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
const ansiColors__default = /*#__PURE__*/_interopDefaultCompat(ansiColors);
const childProcess__namespace = /*#__PURE__*/_interopNamespaceCompat(childProcess);
const originImportSemVer__default = /*#__PURE__*/_interopDefaultCompat(originImportSemVer);
const ___default = /*#__PURE__*/_interopDefaultCompat(_);
const dayjs__default = /*#__PURE__*/_interopDefaultCompat(dayjs);
const qs__default = /*#__PURE__*/_interopDefaultCompat(qs);
const VipColor = ansiColors__default.create();
const VipSymbols = {
success: VipColor.symbols.check,
error: VipColor.symbols.cross,
warning: VipColor.symbols.warning,
info: VipColor.symbols.info,
question: VipColor.symbols.question,
heart: VipColor.symbols.heart,
mark: VipColor.symbols.mark
};
class VipCommander extends commander.Command {
constructor(name, version, description) {
super(name);
this.version(version, "-v,--version", "VipCommander Version By @142vip");
if (description != null) {
this.description(description);
}
}
/**
* 初始化,不包括命令
*/
init(options, args = {}) {
const vipCommander = this.summary(options.summary).description(options.description);
return this.initOptions(vipCommander, args);
}
/**
* 对命令初始化,增加aliases,summary,description等信息
* - 增加默认的一些参数
*/
initCommand(options, args = {}) {
const vipCommander = this.command(options.command).aliases(options.aliases).summary(options.summary).description(options.description);
return this.initOptions(vipCommander, args);
}
// 对description、summary方法重新,增加颜色处理
// public descriptionByColor(str: string) {
// super.description(VipColor.green(str))
// }
//
// public summaryByColor(str: string): this {
// return super.summary(str)
// }
/**
* 初始化参数
*/
initOptions(program, { dryRun = true, trace = true, vip = false, help = false }) {
if (trace) {
program.option("--trace", "\u5F00\u542F\u65E5\u5FD7\u8FFD\u8E2A\u6A21\u5F0F", false);
}
if (dryRun) {
program.option("--dry-run", "\u8BD5\u8FD0\u884C", false);
}
if (vip) {
program.option("--vip", "@142vip\u7EC4\u7EC7\u4E13\u7528\u529F\u80FD", false);
}
if (help) {
program.helpCommand(true);
}
return program;
}
}
const vipLodash = ___default.omit(___default, ["VERSION"]);
class VipConfig {
/**
* 加载配置
* - 本地配置,形如:xxx.config.ts
* - 包配置,package.json中的xxx字段
*/
loadCliConfig(configName, defaultValue, cosmiconfigOptions) {
const cliConfig = this.loadConfig(configName, cosmiconfigOptions);
if (cliConfig == null) {
return defaultValue;
}
return this.mergeConfig(defaultValue, cliConfig);
}
/**
* 加载cli配置
* @param configName
* @param cosmiconfigOptions
*/
loadConfig(configName, cosmiconfigOptions) {
const explorerSync = cosmiconfig.cosmiconfigSync(configName, cosmiconfigOptions);
const result = explorerSync.search();
if (result == null || result.isEmpty) {
return void 0;
}
return result.config;
}
/**
* 合并配置
* @param cliConfig cli自定义配置
* @param commanderConfig 用户在cli终端输入的配置
*/
mergeCommanderConfig(cliConfig, commanderConfig) {
return this.mergeConfig(cliConfig, commanderConfig);
}
/**
* 合并配置,后面配置覆盖前面的
* @private
*/
mergeConfig(beforeConfig, afterConfig) {
return vipLodash.merge({}, beforeConfig, afterConfig);
}
}
const vipConfig = new VipConfig();
var VipConsoleLogLevel = /* @__PURE__ */ ((VipConsoleLogLevel2) => {
VipConsoleLogLevel2["ERROR"] = "ERROR";
VipConsoleLogLevel2["SUCCESS"] = "SUCCESS";
VipConsoleLogLevel2["INFO"] = "INFO";
return VipConsoleLogLevel2;
})(VipConsoleLogLevel || {});
function log(message, level) {
if (message == null)
message = "";
if (level === "INFO" /* INFO */) {
console.log(`${VipSymbols.info} ${message}`);
} else if (level === "SUCCESS" /* SUCCESS */) {
console.log(`${VipSymbols.success} ${message}`);
} else if (level === "ERROR" /* ERROR */) {
console.log(`${VipSymbols.error} ${message}`);
} else {
console.log(message);
}
}
function trace(...data) {
console.log(data);
}
function error(e) {
console.log(e);
}
const VipConsole = {
log,
trace,
error
};
const FormatTemplateStr = "YYYY-MM-DD HH:mm:ss";
function getCurrentTimestamp() {
return dayjs__default().valueOf();
}
function formatDateToStr(date, template) {
return dayjs__default(date).format(template ?? FormatTemplateStr);
}
function formatDateToYMD() {
return formatDateToStr(/* @__PURE__ */ new Date(), "YYYY-MM-DD");
}
const VipDayjs = {
getCurrentTimestamp,
FormatTemplateStr,
formatDateToStr,
formatDateToYMD
};
const INDENT_REGEX = /^(?:( )+|\t+)/;
const INDENT_TYPE_SPACE = "space";
const INDENT_TYPE_TAB = "tab";
function makeIndentsMap(str, ignoreSingleSpaces) {
const indents = /* @__PURE__ */ new Map();
let previousSize = 0;
let previousIndentType;
let key;
for (const line of str.split(/\n/g)) {
if (!line) {
continue;
}
let indent;
let indentType;
let use;
let weight;
let entry;
const matches = line.match(INDENT_REGEX);
if (matches === null) {
previousSize = 0;
previousIndentType = "";
} else {
indent = matches[0].length;
indentType = matches[1] ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && indent === 1) {
continue;
}
if (indentType !== previousIndentType) {
previousSize = 0;
}
previousIndentType = indentType;
use = 1;
weight = 0;
const indentDifference = indent - previousSize;
previousSize = indent;
if (indentDifference === 0) {
use = 0;
weight = 1;
} else {
const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference;
key = encodeIndentsKey(indentType, absoluteIndentDifference);
}
entry = indents.get(key);
entry = entry === void 0 ? [1, 0] : [entry[0] + use, entry[1] + weight];
indents.set(key, entry);
}
}
return indents;
}
function encodeIndentsKey(indentType, indentAmount) {
const typeCharacter = indentType === INDENT_TYPE_SPACE ? "s" : "t";
return typeCharacter + String(indentAmount);
}
function decodeIndentsKey(indentsKey) {
const keyHasTypeSpace = indentsKey[0] === "s";
const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
const amount = Number(indentsKey.slice(1));
return { type, amount };
}
function getMostUsedKey(indentsMap) {
let result;
let maxUsed = 0;
let maxWeight = 0;
for (const [key, [usedCount, weight]] of indentsMap) {
if (usedCount > maxUsed || usedCount === maxUsed && weight > maxWeight) {
maxUsed = usedCount;
maxWeight = weight;
result = key;
}
}
return result;
}
function makeIndentString(type, amount) {
const indentCharacter = type === INDENT_TYPE_SPACE ? " " : " ";
return indentCharacter.repeat(amount);
}
function detectIndent(str) {
let indents = makeIndentsMap(str, true);
if (indents.size === 0) {
indents = makeIndentsMap(str, false);
}
const keyOfMostUsedIndent = getMostUsedKey(indents);
let type;
let amount = 0;
let indent = "";
if (keyOfMostUsedIndent !== void 0) {
({ type, amount } = decodeIndentsKey(keyOfMostUsedIndent));
indent = makeIndentString(type, amount);
}
return {
amount,
type,
indent
};
}
function detectNewline(str) {
const newlines = str.match(/\r?\n/g) || [];
if (newlines.length === 0) {
return;
}
const crlf = newlines.filter((newline) => newline === "\r\n").length;
const lf = newlines.length - crlf;
return crlf > lf ? "\r\n" : "\n";
}
class VipDetect {
/**
* 检测端口
*/
async detectPort(port) {
try {
const realPort = await detectPort.detect(port);
return realPort !== port;
} catch {
vipLogger.error(`detect port ${port} failed`);
return false;
}
}
detectIndent(str) {
return detectIndent(str);
}
detectNewLine(str) {
return detectNewline(str);
}
}
const vipDetect = new VipDetect();
const name = "@142vip/utils";
const version = "0.0.1-alpha.42";
async function promptNumber(message, defaultValue) {
return prompts.number({ message, default: defaultValue });
}
async function promptList(message, choices) {
return prompts.rawlist({ message, choices });
}
async function promptInput(message, defaultValue) {
return prompts.input({ message, default: defaultValue });
}
async function promptInputRequired(message) {
return prompts.input({ message, required: true });
}
async function promptPassword(message) {
return prompts.password({ message, mask: "*" });
}
async function promptSelect(message, choices, options) {
if (options != null && options.default == null && choices.length > 0) {
const choice = choices[0];
options.default = typeof choice === "object" ? choice.value : choice;
}
return prompts.select({ message, choices, ...options == null ? {} : options });
}
async function promptCheckBox(message, choices, options) {
return prompts.checkbox({ message, choices, ...options == null ? {} : options });
}
async function promptConfirm(message, defaultValue) {
return prompts.confirm({ message, default: defaultValue });
}
async function promptConfirmWithSuccessExit(message, { exitMsg, defaultValue }) {
const isContinue = await promptConfirm(message, defaultValue);
if (!isContinue) {
vipLogger.logByBlank(exitMsg ?? `${VipColor.yellow("\u7528\u6237\u53D6\u6D88\u64CD\u4F5C\uFF01\uFF01")}`);
VipNodeJS.existSuccessProcess();
}
}
async function promptSearch(message, source, pageSize) {
return prompts.search({ message, source, pageSize });
}
function handleSimpleSearchSource(sources) {
return function(input2) {
if (input2 == null) {
return sources;
}
return sources.filter((name2) => name2.includes(input2));
};
}
function withTryCatch(fn) {
return async (...args) => {
try {
return await fn(...args);
} catch (error) {
if (error instanceof Error && error.name === "ExitPromptError") {
vipLogger.logByBlank(`${VipPackageJSON.getPkgGreenLabel(name)} \u7528\u6237\u5B89\u5168\u9000\u51FA\uFF0C\u6B22\u8FCE\u4E0B\u6B21\u4F7F\u7528\u{1F44F}\u{1F3FB}\u{1F44F}\u{1F3FB}\u{1F44F}\u{1F3FB}`);
} else {
throw error;
}
}
};
}
const VipInquirer = {
promptList: withTryCatch(promptList),
promptInput: withTryCatch(promptInput),
promptInputRequired: withTryCatch(promptInputRequired),
promptNumber: withTryCatch(promptNumber),
promptPassword: withTryCatch(promptPassword),
promptSelect: withTryCatch(promptSelect),
promptCheckBox: withTryCatch(promptCheckBox),
promptConfirm: withTryCatch(promptConfirm),
promptConfirmWithSuccessExit: withTryCatch(promptConfirmWithSuccessExit),
promptSearch: withTryCatch(promptSearch),
handleSimpleSearchSource
};
class VipInquirerSeparator extends prompts.Separator {
}
function VipInquirerDefaultArrayParser(value, previous) {
return !value ? [value] : previous.concat(value);
}
function clone(json$1) {
return json.klona(json$1);
}
function stringify$1(value, replacer, space) {
return JSON.stringify(value, replacer, space);
}
function parse$1(originData, defaultData) {
if (originData == null || originData.length === 0) {
return defaultData;
}
return JSON.parse(originData);
}
function readFile(name, cwd) {
const filePath = VipNodeJS.pathJoin(cwd, name);
const dataStr = VipNodeJS.readFileToStrByUTF8(filePath);
const data = parse$1(dataStr, {});
const indent = detectIndent(dataStr).indent;
const newline = detectNewline(dataStr);
return { path: filePath, data, indent, newline };
}
function writeFile(file) {
let jsonStr = JSON.stringify(file.data, void 0, file.indent);
if (file.newline)
jsonStr += file.newline;
return VipNodeJS.writeFileByUTF8(file.path, jsonStr);
}
const VipJSON = {
clone,
stringify: stringify$1,
parse: parse$1,
readFile,
writeFile
};
var Alphabet = /* @__PURE__ */ ((Alphabet2) => {
Alphabet2["DEFAULT"] = "0123456789abcdefghijklmnopqrstuvwxyz";
Alphabet2["ONLY_NUMBER"] = "0123456789";
Alphabet2["ONLY_CHAR"] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Alphabet2["COMPLEX"] = "-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return Alphabet2;
})(Alphabet || {});
function getNanoId(alphabet) {
return nanoid.customAlphabet(alphabet ?? "0123456789abcdefghijklmnopqrstuvwxyz" /* DEFAULT */);
}
function getRandomId(size) {
return nanoid.nanoid(size);
}
const VipNanoId = {
getRandomId,
getNanoId
};
function stringify(obj, options) {
return qs__default.stringify(obj, options);
}
function parse(str, options) {
return qs__default.parse(str, options);
}
const VipQs = {
stringify,
parse
};
const prereleaseTypes = ["premajor", "preminor", "prepatch", "prerelease"];
const releaseTypes = prereleaseTypes.concat(["major", "minor", "patch"]);
function createSemver(version, optionsOrLoose) {
return new originImportSemVer.SemVer(version, optionsOrLoose);
}
function isPrereleaseType(value) {
return prereleaseTypes.includes(value);
}
function isReleaseType(value) {
return releaseTypes.includes(value);
}
function getNextVersions(currentVersion, preid) {
const validVersion = originImportSemVer.valid(currentVersion);
if (validVersion == null) {
vipLogger.logByBlank(VipColor.red(`${currentVersion} is not a valid version number, please check it.`));
return null;
}
const parsed = originImportSemVer.parse(validVersion);
if (parsed === null) {
return null;
}
const { prerelease: prerelease2 } = parsed;
if (prerelease2 != null) {
const [currentPreid] = prerelease2;
preid = typeof currentPreid === "string" ? currentPreid : preid;
}
return {
major: originImportSemVer.inc(parsed, "major"),
minor: originImportSemVer.inc(parsed, "minor"),
patch: originImportSemVer.inc(parsed, "patch"),
preMajor: originImportSemVer.inc(parsed, "premajor", preid),
preMinor: originImportSemVer.inc(parsed, "preminor", preid),
prePatch: originImportSemVer.inc(parsed, "prepatch", preid),
next: originImportSemVer.inc(parsed, "prerelease", preid)
};
}
const VipSemver = {
valid: originImportSemVer.valid,
clean: originImportSemVer.clean,
satisfies: originImportSemVer.satisfies,
gt: originImportSemVer.gt,
lt: originImportSemVer.lt,
eq: originImportSemVer.eq,
inc: originImportSemVer.inc,
parse: originImportSemVer.parse,
compare: originImportSemVer.compare,
prerelease: originImportSemVer.prerelease,
createSemver,
originImportSemVer: originImportSemVer__default,
getNextVersions,
isPrereleaseType,
isReleaseType
};
const VipYaml = {
load: jsYaml.load,
loadAll: jsYaml.loadAll
};
class VipLogger {
static logger;
constructor(_opts) {
}
static getInstance(opts) {
if (this.logger == null) {
this.logger = new VipLogger(opts);
}
return this.logger;
}
log(msg, opts) {
const logText = `${VipColor.green(opts?.startLabel ?? "")} ${VipColor.magenta(msg)} ${VipColor.yellow(opts?.endLabel ?? "")}`;
console.log(logText);
}
error(msg, opts) {
const text = `${VipColor.red(opts?.startLabel ?? "")} ${VipColor.magenta(msg)} ${VipColor.yellow(opts?.endLabel ?? "")}`;
console.error(text);
}
/**
* 打印空行
*/
println() {
this.log("");
}
/**
* 上下空行输出
*/
logByBlank(message) {
this.println();
VipConsole.log(message);
this.println();
}
}
const vipLogger = new VipLogger();
async function execCommand(cmd, opts) {
const executable = Array.isArray(cmd) ? cmd.join(";") : cmd;
const options = {
...opts,
stdio: "pipe",
cwd: VipNodeJS.getProcessCwd()
};
try {
const cmd2 = VipNodeJS.getProcessPlatform() === "win32" ? "cmd" : "sh";
const arg = VipNodeJS.getProcessPlatform() === "win32" ? "/C" : "-c";
const child = childProcess__namespace.spawn(cmd2, [arg, executable], options);
return new Promise((resolve) => {
const stdoutList = [];
const stderrList = [];
if (child.stdout != null) {
child.stdout.on("data", (data) => {
if (node_buffer.Buffer.isBuffer(data))
return stdoutList.push(data.toString());
stdoutList.push(data);
});
}
if (child.stderr != null) {
child.stderr.on("data", (data) => {
if (node_buffer.Buffer.isBuffer(data))
return stderrList.push(data.toString());
stderrList.push(JSON.stringify(data));
});
}
const getDefaultResult = () => {
const stderr = stderrList.join("\n");
const stdout = stdoutList.join("\n");
return { stdout, stderr, command: executable };
};
child.on("error", (error) => resolve({ ...getDefaultResult(), error, code: 110 }));
child.on("close", (code) => resolve({ ...getDefaultResult(), code }));
});
} catch (error) {
return Promise.reject(error);
}
}
async function commandStandardExecutor(cmd) {
const commandStr = Array.isArray(cmd) ? cmd.join("&&") : cmd;
vipLogger.logByBlank(`\u6267\u884C\u547D\u4EE4\uFF1A${VipColor.greenBright(commandStr)}`);
let stdout = "";
let stderr = "";
return new Promise((resolve, reject) => {
const cmd2 = VipNodeJS.getProcessPlatform() === "win32" ? "cmd" : "sh";
const arg = VipNodeJS.getProcessPlatform() === "win32" ? "/C" : "-c";
const child = childProcess.spawn(cmd2, [arg, commandStr], {
stdio: "inherit",
cwd: VipNodeJS.getProcessCwd(),
// 添加环境变量,避免命令找不到
env: {
...VipNodeJS.getEnv(),
// ...VipNodeJS.getProcessEnv(),
PATH: `${nodePath__default.join(VipNodeJS.getProcessCwd(), "node_modules", ".bin")}${nodePath__default.delimiter}${VipNodeJS.getProcessEnv("PATH")}`
}
});
if (child.stdout) {
child.stdout.on("data", (data) => {
stdout += data;
});
}
if (child.stderr) {
child.stderr.on("data", (data) => {
stderr += data;
});
}
child.on("close", (code) => {
if (code === 0) {
resolve({ stdout, stderr, code });
} else {
const error = new Error(`\u6807\u51C6\u547D\u4EE4\u6267\u884C\u5668\uFF0C\u975E\u96F6\u9000\u51FA\u3002\u9000\u51FA\u7801\uFF1A${code}`);
Object.assign(error, { stdout, stderr, code });
reject(error);
}
});
child.on("error", (error) => {
Object.assign(error, { stdout, stderr, code: null });
reject(error);
});
VipNodeJS.getProcess().on("SIGINT", () => {
child.kill();
VipNodeJS.existSuccessProcess();
});
VipNodeJS.getProcess().on("SIGTERM", () => {
VipNodeJS.existSuccessProcess();
});
VipNodeJS.getProcess().on("exit", () => {
vipLogger.logByBlank(VipColor.greenBright("\u8FDB\u7A0B\u5DF2\u5B89\u5168\u9000\u51FA\uFF0C\u6B22\u8FCE\u4E0B\u6B21\u4F7F\u7528\u{1F44F}\u{1F3FB}\u{1F44F}\u{1F3FB}\u{1F44F}\u{1F3FB}"));
VipNodeJS.existSuccessProcess();
});
});
}
function execCommandSync(cmd, cwd) {
return childProcess.execSync(cmd, { encoding: "utf8", cwd }).trim();
}
async function execShell(commands) {
const vipLog = VipLogger.getInstance();
const projectName = VipColor.greenBright(`[${name}@${version}]`);
let runCommands = [];
if (typeof commands === "string") {
runCommands.push({
command: commands
});
}
if (typeof commands === "object") {
if (Array.isArray(commands)) {
runCommands = commands;
} else {
runCommands.push(commands);
}
}
for (const { command, description = "\u811A\u672C" } of runCommands) {
vipLog.log(`\u3010${description}\u3011${command}`, {
startLabel: `${projectName}\u6267\u884C\u7684\u547D\u4EE4:`,
endLabel: ""
});
await execCommand(command);
}
}
async function getCommandTrimResponse(command) {
const { code, stdout } = await execCommand(command);
if (code !== 0) {
return null;
}
return stdout.trim();
}
const VipExecutor = {
execCommandSync,
execCommand,
execShell,
commandStandardExecutor,
// commandStandardAsyncExecutor,
getCommandTrimResponse
};
function getCommitLogs(latestTag, branch) {
const command = `git log ${branch ?? ""} --pretty=format:"%s" --date=short "${latestTag}"..HEAD`;
const commitLogs = VipExecutor.execCommandSync(command);
return commitLogs.split("\n");
}
function getRecentCommitsByScope(gitScope) {
const latestTag = VipPackageJSON.getVersionGitTag();
if (latestTag == null) {
vipLogger.logByBlank(VipColor.red(`\u4ED3\u5E93\u6CA1\u6709tag\u6807\u7B7E\uFF0C\u8BF7\u5148\u6253tag\u6807\u7B7E\u6216\u914D\u7F6Eversion\u5B57\u6BB5\uFF01\uFF01\uFF01`));
VipNodeJS.exitProcess(1);
}
const commitLogs = getCommitLogs(latestTag);
return commitLogs.filter((commit) => commit.includes(`(${gitScope})`));
}
function getRecentCommit() {
const gitLog = VipExecutor.execCommandSync('git log --no-merges -1 --pretty=format:"%h||%s"');
const [commitHash, ...commitMessage] = gitLog.split("||");
return {
hash: commitHash,
message: commitMessage.join(" ")
};
}
function getRecentCommitHash() {
return VipExecutor.execCommandSync("git rev-parse HEAD");
}
function getRecentCommitShortHash() {
const hash = getRecentCommitHash();
return hash.substring(0, 6);
}
function getGitHubRepo(baseUrl) {
const url = VipExecutor.execCommandSync("git config --get remote.origin.url");
const escapedBaseUrl = baseUrl.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`${escapedBaseUrl}[/:]([\\w\\d._-]+?)\\/([\\w\\d._-]+?)(\\.git)?$`, "i");
const match = regex.exec(url);
if (!match)
throw new Error(`Can not parse GitHub repo from url ${url}`);
return `${match[1]}/${match[2]}`;
}
function getCurrentBranch() {
return VipExecutor.execCommandSync("git rev-parse --abbrev-ref HEAD");
}
function isRepoShallow() {
return VipExecutor.execCommandSync("git rev-parse --is-shallow-repository") === "true";
}
function getTags() {
const tagStr = VipExecutor.execCommandSync("git --no-pager tag -l --sort=creatordate");
return tagStr.split("\n").reverse();
}
function getTagInHead() {
const tag = VipExecutor.execCommandSync("git tag --points-at HEAD");
return tag !== "" ? tag : null;
}
function getLastMatchingTag(inputTag) {
const inputTagWithoutPrefix = inputTag.replace(/^v/, "");
const isVersion = VipSemver.valid(inputTagWithoutPrefix) !== null;
const isPrerelease2 = VipSemver.prerelease(inputTag) !== null;
const tags = getTags();
let tag;
if (!isPrerelease2 && isVersion) {
tag = tags.find((tag2) => {
const tagWithoutPrefix = tag2.replace(/^v/, "");
return tagWithoutPrefix !== inputTagWithoutPrefix && VipSemver.valid(tagWithoutPrefix) !== null && VipSemver.prerelease(tagWithoutPrefix) === null;
});
}
tag ||= tags.find((tag2) => tag2 !== inputTag);
return tag;
}
function isPrerelease(version) {
return !/^[^.]*(?:\.[\d.]*|\d)$/.test(version);
}
function execCommit(args) {
VipExecutor.execCommandSync(`git commit ${args.join(" ")}`);
}
function execTag(args) {
VipExecutor.execCommandSync(`git tag ${args.join(" ")}`);
}
function execPush(args) {
VipExecutor.execCommandSync(`git push ${args.join(" ")}`);
}
function getRemoteNames() {
const remoteStr = VipExecutor.execCommandSync("git remote");
return remoteStr.split("\n");
}
function convertEmoji(content, withSpace) {
return convertGitmoji.convert(content, withSpace);
}
function getCommitContent() {
const msgPath = VipNodeJS.pathJoin(".git/COMMIT_EDITMSG");
return VipNodeJS.readFileToStrByUTF8(msgPath);
}
function getCommitTrimMsg() {
const commitContent = getCommitContent();
return commitContent.trim();
}
function getCommitFirstLineMsg() {
const commitContent = getCommitContent();
const firstLine = commitContent.split("\n").shift() ?? "";
return firstLine.trim();
}
function parseCommitMsg(message) {
const PATTERN = /^(?<type>\w+)(?:\((?<scope>[^()]*)\))?:\s*(?<message>.*)$/;
const matches = PATTERN.exec(message);
return matches != null ? {
type: matches[1],
scope: matches[2],
subject: matches[3]
} : null;
}
function validateBranch(allowBranch) {
const currentBranch = getCurrentBranch();
if (allowBranch == null) {
allowBranch = [enums_index.GitGeneralBranch.MASTER, enums_index.GitGeneralBranch.NEXT, enums_index.GitGeneralBranch.NEXT];
}
const branches = typeof allowBranch === "string" ? [allowBranch] : allowBranch;
if (!branches.includes(currentBranch)) {
vipLogger.logByBlank(VipColor.red(`\u5F53\u524D\u5206\u652F\u662F\uFF1A${currentBranch} \uFF0C\u7248\u672C\u8FED\u4EE3\u5141\u8BB8\u5728 ${VipColor.green(branches.join("|"))} \u5206\u652F\u64CD\u4F5C\uFF0C\u5E76\u63A8\u9001\u5230\u8FDC\u7A0B\uFF01\uFF01\uFF01`));
VipNodeJS.existSuccessProcess();
}
}
const VipGit = {
getRecentCommit,
getRecentCommitHash,
getRecentCommitShortHash,
getCommitLogs,
getRecentCommitsByScope,
getGitHubRepo,
getCurrentBranch,
isRepoShallow,
getTags,
getTagInHead,
getLastMatchingTag,
isPrerelease,
execCommit,
execTag,
execPush,
convertEmoji,
getCommitTrimMsg,
getCommitFirstLineMsg,
parseCommitMsg,
getRemoteNames,
validateBranch
};
async function runScript(scriptName, cwd) {
const pkgPath = getPackagePath(cwd);
const pkgJSONStr = VipNodeJS.readFileToStrByUTF8(pkgPath);
const data = JSON.parse(pkgJSONStr);
if (!hasScript(data, scriptName)) {
VipConsole.error(`script not found in package.json\uFF0CscriptName: ${scriptName}`);
VipNodeJS.existErrorProcess();
}
VipExecutor.execCommandSync(`npm run ${scriptName} --silent`);
}
function hasScript(packageJSON, script) {
const npmScripts = packageJSON.scripts;
if (npmScripts && typeof npmScripts === "object")
return Boolean(npmScripts[script]);
return false;
}
function getCurrentVersion(cwd) {
const pkgPath = getPackagePath(cwd);
const pkgJSONStr = VipNodeJS.readFileToStrByUTF8(pkgPath);
const pkgJSON = VipJSON.parse(pkgJSONStr, {});
return pkgJSON.version ?? null;
}
function getVersionGitTag() {
const version = getCurrentVersion();
const gitTags = VipGit.getTags();
const filterTag = gitTags.find((tag) => tag === `v${version}`);
return filterTag ?? gitTags.length > 0 ? gitTags[0] : null;
}
function getReleaseVersion(currentVersion, releaseType) {
return VipSemver.inc(currentVersion, releaseType);
}
async function promptReleaseVersion(currentVersion, preid) {
const nextVersion = VipSemver.getNextVersions(currentVersion, preid);
const PADDING = 13;
let version = await VipInquirer.promptSelect(`Current version ${VipColor.green(currentVersion)}`, [
{ value: nextVersion.major, name: `${"major".padStart(PADDING, " ")} ${VipColor.bold(nextVersion.major)}` },
{ value: nextVersion.minor, name: `${"minor".padStart(PADDING, " ")} ${VipColor.bold(nextVersion.minor)}` },
{ value: nextVersion.patch, name: `${"patch".padStart(PADDING, " ")} ${VipColor.bold(nextVersion.patch)}` },
{ value: nextVersion.next, name: `${"next".padStart(PADDING, " ")} ${VipColor.bold(nextVersion.next)}` },
{ value: nextVersion.prePatch, name: `${"pre-patch".padStart(PADDING, " ")} ${VipColor.bold(nextVersion.prePatch)}` },
{ value: nextVersion.preMinor, name: `${"pre-minor".padStart(PADDING, " ")} ${VipColor.bold(nextVersion.preMinor)}` },
{ value: nextVersion.preMajor, name: `${"pre-major".padStart(PADDING, " ")} ${VipColor.bold(nextVersion.preMajor)}` },
{ value: currentVersion, name: `${"as-is".padStart(PADDING, " ")} ${VipColor.bold(currentVersion)}` },
{ value: "custom", name: "custom ...".padStart(PADDING + 4, " ") }
], { default: nextVersion.next, loop: false, pageSize: 20 });
if (version === "custom") {
version = await VipInquirer.promptInputRequired("Enter the new version number:");
}
if (!VipSemver.valid(version)) {
vipLogger.logByBlank(VipColor.red("That's not a valid version number"));
VipNodeJS.existSuccessProcess();
}
return version;
}
function replaceOrAddToJSON(json, cwd) {
const pkgPath = getPackagePath(cwd);
const pkgJSONStr = VipNodeJS.readFileToStrByUTF8(pkgPath);
const pkgJSON = VipJSON.parse(pkgJSONStr, {});
for (const [key, value] of Object.entries(json)) {
pkgJSON[key] = value;
}
VipNodeJS.writeFileByUTF8(pkgPath, VipJSON.stringify(pkgJSON));
}
function updateVersion(newVersion, cwd) {
const jsonFile = VipJSON.readFile("package.json", cwd ?? VipNodeJS.getProcessCwd());
jsonFile.data = Object.assign(jsonFile.data, { version: newVersion });
VipJSON.writeFile(jsonFile);
}
function getPackageJSON(cwd) {
const pkgPath = getPackagePath(cwd);
const pkg = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))(pkgPath);
return pkg;
}
function getPackagePath(cwd) {
const isExist = isExistPackageJSON(cwd);
if (!isExist) {
VipConsole.log("package.json not found");
VipNodeJS.exitProcess(1);
}
return VipNodeJS.pathJoin(cwd ?? VipNodeJS.getProcessCwd(), "package.json");
}
function isExistPackageJSON(cwd) {
return VipNodeJS.isExistFile("package.json", cwd);
}
function isExistPackageLock(cwd) {
return VipNodeJS.isExistFile("package--lock.json", cwd);
}
function isExistPnpmLock(cwd) {
return VipNodeJS.isExistFile("pnpm-lock.yaml", cwd);
}
function isPackageJSON(packageJSON) {
return packageJSON && typeof packageJSON === "object" && (packageJSON.name != null || packageJSON.version != null || packageJSON.description != null);
}
function getPkgRedLabel(pkgName) {
return VipColor.red(`\u3010${pkgName}\u3011`);
}
function getPkgGreenLabel(pkgName) {
return VipColor.green(`\u3010${pkgName}\u3011`);
}
const VipPackageJSON = {
runScript,
hasScript,
getCurrentVersion,
getVersionGitTag,
getReleaseVersion,
promptReleaseVersion,
getPackagePath,
isExistPackageJSON,
isPackageJSON,
isExistPackageLock,
isExistPnpmLock,
replaceOrAddToJSON,
getPackageJSON,
getPkgRedLabel,
getPkgGreenLabel,
updateVersion
};
function formatVersionStr(template, newVersion) {
return template.includes("%s") ? template.replace(/%s/g, newVersion) : `${template}${newVersion}`;
}
async function getNpmVersion() {
return await VipExecutor.getCommandTrimResponse('echo "v$(npm -v)"');
}
async function getNodeVersion() {
return await VipExecutor.getCommandTrimResponse("node -v");
}
async function getPnpmVersion() {
return await VipExecutor.getCommandTrimResponse('echo "v$(pnpm -v)"');
}
async function isExistNodeJs() {
return !!await getNodeVersion();
}
async function isExistNpm() {
return !!await getNpmVersion();
}
async function isExistPnpm() {
return !!await getPnpmVersion();
}
async function getTurboPackVersion() {
return await VipExecutor.getCommandTrimResponse('echo "v$(turbo --version)"');
}
async function isExistTurboPack() {
return !!await getTurboPackVersion();
}
async function getTurboPackApps() {
const command = "npx turbo ls --output json";
const turboJsonStr = await VipExecutor.getCommandTrimResponse(command);
try {
if (turboJsonStr == null) {
return [];
}
const turboJSON = VipJSON.parse(turboJsonStr, {});
return turboJSON.packages?.items.map((item) => item.name);
} catch {
return [];
}
}
function getPackageJSONByPnpm(pnpmLsCommand) {
try {
const packageStr = VipExecutor.execCommandSync(pnpmLsCommand);
return JSON.parse(packageStr);
} catch (error) {
VipConsole.log("Failed to get the release package name, in function getPackageJSONByPnpm");
VipConsole.error(error);
return [];
}
}
async function installByNpm(args) {
const npmExist = await isExistNpm();
if (!npmExist) {
vipLogger.error("\u672A\u5B89\u88C5npm\uFF0C\u8BF7\u5148\u5B89\u88C5node.js\u73AF\u5883\u3002");
VipNodeJS.exitProcess(1);
}
if (!args.force) {
const isExist = VipPackageJSON.isExistPackageLock(args.cwd);
if (!isExist) {
args.force = true;
}
}
const command = `${args.force ? "npm i" : "npm ci"}`;
await VipExecutor.commandStandardExecutor(`${command} --registry ${args.registry ?? enums_index.RegistryAddressEnum.VIP_NPM_TENCENT}`);
}
async function installByPnpm(args) {
const pnpmExist = await isExistPnpm();
if (pnpmExist == null) {
vipLogger.error("\u672A\u5B89\u88C5pnpm\uFF0C\u8BF7\u5168\u5C40\u5B89\u88C5pnpm\u3002\u547D\u4EE4\uFF1Anpm i -g pnpm");
VipNodeJS.exitProcess(1);
}
if (!args.force) {
const isExist = VipPackageJSON.isExistPnpmLock(args.cwd);
if (!isExist) {
args.force = true;
}
}
const commands = [
"pnpm i",
args.force ? "" : "--frozen-lockfile",
`--registry ${args.registry ?? enums_index.RegistryAddressEnum.VIP_NPM_TENCENT}`
];
await VipExecutor.commandStandardExecutor(commands.join(" "));
}
async function userLogin$1(args) {
const command = `npm login --registry ${args.registry}`;
await VipExecutor.commandStandardExecutor(command);
}
const VipNpm = {
formatVersionStr,
getNpmVersion,
getNodeVersion,
getPnpmVersion,
getTurboPackVersion,
isExistTurboPack,
getTurboPackApps,
isExistNodeJs,
isExistNpm,
isExistPnpm,
installByNpm,
installByPnpm,
getPackageJSONByPnpm,
userLogin: userLogin$1
};
function getProcess() {
return process__default;
}
function getEnv() {
return process__default.env;
}
function getProcessArgv() {
return process__default.argv;
}
function getProcessFirstArgv() {
return process__default.argv0;
}
function getProcessArgvByIndex(index) {
const argv = getProcessArgv();
if (index < 0 || index >= argv.length) {
return null;
}
return process__default.argv[index];
}
function getProcessEnv(key) {
const envs = process__default.env;
if (envs[key] != null)
return envs[key];
return void 0;
}
function setProcessEnv(key, value) {
process__default.env[key] = value;
}
function getProcessPlatform() {
return process__default.platform;
}
function getProcessCwd() {
return process__default.cwd();
}
function getProcessVersions() {
return process__default.versions;
}
function getCPUArch() {
return process__default.arch;
}
function pathJoin(...paths) {
return nodePath__namespace.join(...paths);
}
function pathDirname(dirPath) {
return nodePath__namespace.dirname(dirPath);
}
function pathExtname(path) {
return nodePath__namespace.extname(path);
}
function exitProcess(exitCode) {
process__default.exit(exitCode);
}
function existSuccessProcess() {
exitProcess(enums_index.ProcessExitCodeEnum.SUCCESS);
}
function existErrorProcess() {
exitProcess(enums_index.ProcessExitCodeEnum.FatalError);
}
function existPath(path) {
return fs.existsSync(path);
}
function isExistFile(name, cwd) {
const filePath = pathJoin(cwd ?? getProcessCwd(), name);
return existPath(filePath);
}
function isExistDir(name, cwd) {
const dirPath = pathJoin(cwd ?? getProcessCwd(), name);
return existPath(dirPath) && isDirectory(dirPath);
}
function isDirectory(path) {
try {
const stat = fs__namespace.statSync(path);
return stat.isDirectory();
} catch {
return false;
}
}
function readFileToStrByUTF8(filePath) {
return fs.readFileSync(filePath, "utf-8");
}
function readdirSync(path, options) {
return fs__namespace.readdirSync(path, options);
}
function writeFileByUTF8(filePath, data) {
return fs.writeFileSync(filePath, data, "utf-8");
}
function isBuffer(data) {
return node_buffer.Buffer.isBuffer(data);
}
function mkdirSync(path) {
fs__namespace.mkdirSync(path);
}
async function printStandardNodeDevEnv() {
const npm = await VipNpm.getNpmVersion();
const pnpm = await VipNpm.getPnpmVersion();
const node = await VipNpm.getNodeVersion();
VipConsole.log(`Node.js\u5F00\u53D1\u73AF\u5883\uFF0C\u7248\u672C\u4FE1\u606F\u7EDF\u8BA1\uFF1A`);
vipLogger.println();
if (npm != null) {
VipConsole.log(VipColor.green(`${VipSymbols.success} npm\u7248\u672C\uFF1A${npm}`));
} else {
VipConsole.error(VipColor.red(`${VipSymbols.error} \u672A\u5B89\u88C5npm\u73AF\u5883`));
}
if (node != null) {
VipConsole.log(VipColor.green(`${VipSymbols.success} node\u7248\u672C\uFF1A${node}`));
} else {
VipConsole.error(VipColor.red(`${VipSymbols.error} \u672A\u5B89\u88C5node\u73AF\u5883`));
}
if (pnpm != null) {
VipConsole.log(VipColor.green(`${VipSymbols.success} pnpm\u7248\u672C\uFF1A${pnpm}`));
} else {
VipConsole.error(VipColor.red(`${VipSymbols.error} \u672A\u5B89\u88C5pnpm\u73AF\u5883\uFF0C\u8BF7\u5168\u5C40\u5B89\u88C5pnpm\u547D\u4EE4\u3002\u53C2\u8003\uFF1Anpm i -g pnpm`));
}
vipLogger.println();
}
function pathResolve(...pathSegments) {
return nodePath__namespace.resolve(...pathSegments);
}
function getProcessStdin() {
return process__default.stdin;
}
function getProcessStdout() {
return process__default.stdout;
}
function pick(obj, keys) {
const result = {};
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
result[key] = obj[key];
}
}
return result;
}
const VipNodeJS = {
getProcess,
getEnv,
getProcessFirstArgv,
getProcessArgv,
getProcessArgvByIndex,
getCPUArch,
setProcessEnv,
getProcessEnv,
getProcessPlatform,
getProcessCwd,
getProcessVersions,
getProcessStdin,
getProcessStdout,
exitProcess,
existSuccessProcess,
existErrorProcess,
existPath,
isExistFile,
isExistDir,
isDirectory,
readdirSync,
readFileToStrByUTF8,
writeFileByUTF8,
mkdirSync,
pathJoin,
pathResolve,
pathDirname,
pathExtname,
isBuffer,
pick,
printStandardNodeDevEnv
};
class VipDocSite {
/**
* 默认的环境变量的键
*/
defaultEnvKey = "NEED_PROXY";
/**
* 用于区分base路径,是否nginx代理
* - 路径名称
* - 默认环境变量 NEED_PROXY
* @param baseName 路径名称
* @param envKey 环境变量的键
*/
getBase(baseName, envKey) {
const needProxy = VipNodeJS.getProcessEnv(envKey ?? this.defaultEnvKey) ?? false;
return needProxy ? `/${baseName}/` : "/";
}
}
const vipDocSite = new VipDocSite();
async function scriptExecutor(command) {
try {
const { code } = await VipExecutor.commandStandardExecutor(command);
if (code !== 0) {
vipLogger.error(`Error Code: ${code}`, { startLabel: "commandStandardExecutor" });
VipNodeJS.exitProcess(1);
}
} catch {
VipNodeJS.exitProcess(1);
}
}
async function isExistImage(imageName) {
const command = `docker images -q ${imageName}`;
const { code, stdout } = await VipExecutor.execCommand(command);
return code === 0 && stdout.trim() !== "";
}
async function deleteImage(imageName) {
const command = `docker rmi -f ${imageName}`;
return await VipExecutor.execCommand(command);
}
async function deletePruneImages() {
const command = "docker image prune -f";
return await VipExecutor.execCommand(command);
}
async function listPruneImages() {
const command = "docker images -f dangling=true";
await scriptExecutor(command);
}
async function isExistContainer(containerName) {
const command = `docker ps -aq -f name=${containerName}`;
const { code, stdout } = await VipExecutor.execCommand(command);
return code === 0 && stdout.trim() !== "";
}
async function userLogin(args) {
if (args.registry) {
args.registry = enums_index.RegistryAddressEnum.VIP_DOCKER;
}
const command = `docker login --username=${args.username} --password="${args.password}" ${args.registry}`;
await scriptExecutor(command);
}
async function deleteContainer(containerName) {
const command = `docker rm -f ${containerName}`;
const { code } = await VipExecutor.execCommand(command);
return code === 0;
}
async function deleteForceContainer(containerName) {
const imageAddress = await getImageAddress(containerName);
const success = await deleteContainer(containerName);
if (success && imageAddress != null) {
await deleteImage(imageAddress);
}
return success;
}
async function getImageAddress(containerName) {
const command = `docker inspect ${containerName} --format "{{.Config.Image}}"`;
const { code, stdout } = await VipExecutor.execCommand(command);
if (code !== 0) {
return null;
}
return stdout.trim().replace(/\n/g, "");
}
async function isExistDocker(args) {
const command = "docker -v";
const { code, stdout, stderr } = await VipExecutor.execCommand(command);
if (args?.logger) {
if (code === 0) {
vipLogger.log(`\u68C0\u6D4B\u5230docker\uFF0C\u7248\u672C\u4FE1\u606F\uFF1A
`, { startLabel: VipSymbols.success });
vipLogger.log(stdout);
} else {
vipLogger.log(`\u672A\u68C0\u6D4B\u5230docker\uFF0C\u8BF7\u5148\u5B89\u88C5!!
`, { startLabel: VipSymbols.error });
vipLogger.error(stderr);
}
}
return code === 0 && stdout.includes("Docker");
}
async function isExistDockerCompose(args) {
const command = "docker-compose -v";
const { code, stdout, stderr } = await VipExecutor.execCommand(command);
if (args?.logger) {
if (code === 0) {
vipLogger.log(`\u68C0\u6D4B\u5230docker-compose\uFF0C\u7248\u672C\u4FE1\u606F\uFF1A
`, { startLabel: VipSymbols.success });
vipLogger.log(stdout);
} else {
vipLogger.log(`\u672A\u68C0\u6D4B\u5230docker-compose\uFF0C\u8BF7\u5148\u5B89\u88C5!!
`, { startLabel: VipSymbols.error });
vipLogger.error(stderr);
}
}
return code === 0 && stdout.includes("Docker Compose");
}
async function pushImage(imageName) {
const command = `docker push ${imageName}`;
await scriptExecutor(command);
}
async function pullImage(imageAddress) {
const command = `docker pull ${imageAddress}`;
await scriptExecutor(command);
}
async function buildImage(args) {
let buildArg = "";
if (args.buildArgs != null) {
buildArg = args.buildArgs.map(([key, value]) => {
const newValue = typeof value === "string" ? `'${value}'` : value;
return `--build-arg ${key}=${newValue}`;
}).join(" ");
}
const targetParams = args.target != null ? `--target ${args.target}` : "";
const memoryParams = args.memory != null ? `--memory=${args.memory}mb` : "";
const platformParams = args.platform != null ? `--platform=${args.platform}` : "";
const command = `docker build ${buildArg} ${targetParams} ${memoryParams} ${platformParams} -t '${args.imageName}' .`;
if (args.logger) {
vipLogger.log(`\u6267\u884C\u7684\u547D\u4EE4\uFF1A
`, { startLabel: VipSymbols.success });
vipLogger.log(`${command}
`, { startLabel: VipSymbols.success });
}
vipLogger.log(args.imageName, { startLabel: "\u6784\u5EFA\u955C\u50CF" });
await scriptExecutor(command);
if (args.push) {
const exist = await isExistImage(args.imageName);
if (exist) {
vipLogger.log(args.imageName, { startLabel: "\u63A8\u9001\u955C\u50CF" });
await pushImage(args.imageName);
}
}
if (args.push && args.delete) {
vipLogger.log(args.imageName, { startLabel: "\u5220\u9664\u955C\u50CF" });
await deleteImage(args.imageName);
}
}
async function createContainer(args) {
if (args.networkName && !args.ip) {
vipLogger.error(`\u53EA\u6307\u5B9AIP\uFF0C\u6CA1\u6709\u6307\u5B9A\u5BB9\u5668\u5C40\u57DF\u7F51\u540D\u79F0\uFF0C\u7F3A\u5C11--networkName\u53C2\u6570`, { startLabel: "\u521B\u5EFA\u5BB9\u5668" });
VipNodeJS.exitProcess(1);
}
const networkParams = args.networkName && args.ip ? `--network ${args.networkName} --ip ${args.ip}` : "";
const portStr = args.port ? args.port.map((port) => `-p ${port}`).join(" ") : "";
const runParams = [
"docker run -d",
`--name ${args.containerName}`,
"--restart=unless-stopped",
// 处理platform,兼容arm64、arm架构
VipNodeJS.getCPUArch().includes("arm") ? "--platform linux/arm64" : "--platform linux/amd64",
`${networkParams}`,
portStr,
args.imageName
];
const command = runParams.filter((s) => s !== "").join(" ");
if (args.logger != null) {
vipLogger.log(`command\uFF1A${command}`);
}
await VipExecutor.commandStandardExecutor(command);
}
async function listContainer() {
const command = `docker ps -a`;
await scriptExecutor(command);
}
async function listRunningContainer() {
const command = `docker ps`;
await scriptExecutor(command);
}
async function listContainerNames() {
const containers = await listContainerStatus();
return containers.map((container) => container.name);
}
async function listRunningContainerNames() {
const containers = await listContainerStatus();
return containers.filter((c) => c.running).map((container) => container.name);
}
async function listNoRunningContainerNames() {
const containers = await listContainerStatus();
return containers.filter((c) => !c.running).map((container) => container.name);
}
async function listContainerStatus() {
const command = `docker ps -a --format "{{.Names}} &&& {{.Status}}"`;
const { code, stdout } = await VipExecutor.execCommand(command);
if (code !== 0) {
return [];
}
return stdout.trim().split("\n").map((line) => {
const [name, ...statusParts] = line.split(" &&& ");
const status = statusParts.join(" ");
return {
name,
running: status.includes("Up")
};
});
}
async function isExistNetwork(networkName) {
const names = await listNetworkNames();
return names.includes(networkName);
}
async function listNetworkNames() {
const command = `docker network ls --format "{{.Name}}"`;
const { code, stdout } = await VipExecutor.execCommand(command);
if (code !== 0) {
return [];
}
return stdout.split("\n").filter((v) => !!v);
}
async function createNetwork(options) {
if (options.gateway == null && options.subnet == null) {
options.gateway = openSource.OPEN_SOURCE_ADDRESS.DOCKER_NETWORK_GATEWAY;
options.subnet = openSource.OPEN_SOURCE_ADDRESS.DOCKER_NETWORK_SUBNET;
}
const command = `docker network create --subnet="${options.subnet}" --gateway="${options.gateway}" ${options.networkName}`;
const { code } = await VipExecutor.execCommand(command);
return code === 0;
}
const VipDocker = {
isExistDocker,
isExistDockerCompose,
isExistImage,
isExistContainer,
deleteImage,
deletePruneImages,
deleteContainer,
pullImage,
pushImage,
buildImage,
listPruneImages,
getImageAddress,
createContainer,
listContainer,
listRunningContainer,
deleteForceContainer,
userLogin,
listContainerStatus,
listContainerNames,
listRunningContainerNames,
listNoRunningContainerNames,
createNetwork,
listNetworkNames,
isExistNetwork,
scriptExecutor
};
function getPackageJSONPathList() {
const pnpmYamlFileName = "pnpm-workspace.yaml";
const pnpmWorkspace = VipNodeJS.existPath(pnpmYamlFileName);
const packageJSONList = [];
if (pnpmWorkspace) {
const pnpmWorkspace2 = VipNodeJS.readFileToStrByUTF8(pnpmYamlFileName);
const workspaces = VipYaml.load(pnpmWorkspace2);
const workspacesWithPackageJson = workspaces.packages.map((workspace) => `${workspace}/package.json`);
packageJSONList.concat(workspacesWithPackageJson.filter((workspace) => !workspace.startsWith("!")));
}
if (VipNodeJS.existPath("package.json")) {
packageJSONList.push("package.json");
}
return packageJSONList;
}
function getReleasePkgJSON(filter) {
let filterRgx = "";
if (filter == null || filter.length === 0) {
return [];
} else {
if (Array.isArray(filter)) {
for (const f of filter) {
filterRgx += `--filter "${f}" `;
}
} else {
filterRgx = `--filter "${filter}"`;
}
}
const command = `pnpm ls --json --only-projects ${filterRgx} --depth -1`;
return VipNpm.getPackageJSONByPnpm(command);
}
function getPkgJSONPath(pkgName, filter) {
const pkgJSON = getReleasePkgJSON(filter);
return pkgJSON.find((pkg) => pkg.name === pkgName);
}
function getPkgNames(filter) {
return getReleasePkgJSON(filter).map((pkg) => pkg.name);
}
const VipMonorepo = {
getPackageJSONPathList,
getPkgNames,
getReleasePkgJSON,
getPkgJSONPath
};
exports.CpuArchitectureEnum = enums_index.CpuArchitectureEnum;
exports.GitGeneralBranch = enums_index.GitGeneralBranch;
exports.HttpMethod = enums_index.HttpMethod;
exports.HttpStatus = enums_index.HttpStatus;
exports.ProcessExitCodeEnum = enums_index.ProcessExitCodeEnum;
exports.RegistryAddressEnum = enums_index.RegistryAddressEnum;
exports.ReleaseVersionTypeEnum