run-script-cli
Version:
<p align="center"> <a href="https://www.npmjs.com/package/run-script-cli" target="_blank" rel="noopener noreferrer"> <img src="https://github.com/hunghg255/run-script-cli/blob/main/assets/icon.png?raw=true" alt="logo" width='100'/></a> </p>
161 lines (155 loc) • 4.61 kB
JavaScript
import process from 'node:process';
import { $, d as detectAgent, t as te, H, n as ne, o as oe, e as execaCommand } from './shared/run-script-cli.f5e6c5d4.mjs';
import fs, { existsSync, promises } from 'node:fs';
import { resolve, join, dirname } from 'node:path';
import os from 'node:os';
import 'node:util';
import 'node:child_process';
import 'node:buffer';
import 'child_process';
import 'path';
import 'fs';
import 'node:url';
import 'node:timers/promises';
import 'stream';
import 'tty';
import 'node:readline';
import 'node:tty';
import 'events';
function getPackageJSON(cwdParams) {
const cwd = cwdParams ?? process.cwd();
const path = resolve(cwd, "package.json");
if (fs.existsSync(path)) {
try {
const raw = fs.readFileSync(path, "utf8");
const data = JSON.parse(raw);
return data;
} catch {
console.warn("Failed to parse package.json");
process.exit(1);
}
}
}
const CLI_TEMP_DIR = join(os.tmpdir(), "run-script-cli");
const storagePath = resolve(CLI_TEMP_DIR, "_storage.json");
let storage;
let counter = 0;
async function openTemp() {
if (!existsSync(CLI_TEMP_DIR)) {
await promises.mkdir(CLI_TEMP_DIR, { recursive: true });
}
const competitivePath = join(CLI_TEMP_DIR, `.${process.pid}.${counter}`);
counter++;
return promises.open(competitivePath, "wx").then((fd) => ({
fd,
path: competitivePath,
cleanup() {
fd.close().then(() => {
if (existsSync(competitivePath)) {
promises.unlink(competitivePath);
}
});
}
})).catch((error) => {
return error && error.code === "EEXIST" ? openTemp() : void 0;
});
}
async function writeFileSafe(path, data = "") {
const temp = await openTemp();
if (temp) {
promises.writeFile(temp.path, data).then(() => {
const directory = dirname(path);
if (!existsSync(directory)) {
promises.mkdir(directory, { recursive: true });
}
return promises.rename(temp.path, path).then(() => true).catch(() => false);
}).catch(() => false).finally(temp.cleanup);
}
return false;
}
async function load(fn) {
if (!storage) {
storage = existsSync(storagePath) ? JSON.parse(await promises.readFile(storagePath, "utf8") || "{}") || {} : {};
}
if (fn && await fn(storage)) {
await dump();
}
return storage;
}
async function dump() {
if (storage) {
await writeFileSafe(storagePath, JSON.stringify(storage));
}
}
function limitText(text, maxWidth) {
if (text.length <= maxWidth) {
return text;
}
return `${text.slice(0, maxWidth)}${$.dim("\u2026")}`;
}
const niCli = async (cwd = process.cwd(), argv = process.argv) => {
try {
const storage = await load();
const pkg = getPackageJSON(cwd);
const scripts = pkg.scripts || {};
const scriptsInfo = pkg["scripts-info"] || {};
let scriptValue = "";
const names = Object.entries(scripts);
if (names.length === 0) {
return process.exit(0);
}
const raw = names.filter((i) => !i[0].startsWith("?")).map(([key, cmd]) => ({
key,
cmd,
description: scriptsInfo[key] || scripts[`?${key}`] || cmd
}));
const agent = await detectAgent(cwd);
if (!agent?.name) {
return process.exit(0);
}
if (argv?.length > 2) {
scriptValue = argv.slice(2).join(" ");
} else {
const initialValue = storage.lastRunCommand;
scriptValue = await te({
message: $.bgCyan(" Run script "),
options: raw.map((scriptItem) => ({
label: `${$.green(scriptItem.key)}: ${$.dim(limitText(scriptItem.description, 50))}`,
value: scriptItem.key
})),
initialValue
});
if (H(scriptValue)) {
ne("Run script cancelled");
return process.exit(0);
}
}
if (storage.lastRunCommand !== scriptValue) {
storage.lastRunCommand = scriptValue;
dump();
}
if (agent.name === "bun") {
oe($.bold($.green(`bun run ${scriptValue}
`)));
await execaCommand(`bun run ${scriptValue}`, { stdio: "inherit", cwd });
}
if (agent.name === "pnpm") {
oe($.bold($.green(`pnpm ${scriptValue}
`)));
await execaCommand(`pnpm ${scriptValue}`, { stdio: "inherit", cwd });
}
if (agent.name === "npm") {
oe($.bold($.green(`npm run ${scriptValue}
`)));
await execaCommand(`npm run ${scriptValue}`, { stdio: "inherit", cwd });
}
if (agent.name === "yarn") {
oe($.bold($.green(`yarn ${scriptValue}
`)));
await execaCommand(`yarn ${scriptValue}`, { stdio: "inherit", cwd });
}
} catch {
}
};
niCli();
export { niCli };