@magicdawn/x-args
Version:
play with cli commands like a composer
223 lines (218 loc) • 8.29 kB
JavaScript
import { Command, Option } from "clipanion";
import path from "node:path";
import chalk from "chalk";
import { execSync } from "node:child_process";
import { watch } from "chokidar";
import Emittery from "emittery";
import { delay, once } from "es-toolkit";
import ms from "ms";
import { escapeShellArg } from "needle-kit";
import superjson from "superjson";
import { z } from "zod";
import boxen$1 from "boxen";
import fse from "fs-extra";
//#region src/util/BaseCommand.ts
var BaseCommand = class extends Command {
/**
* glob
*/
files = Option.String("-f,--files", {
required: true,
description: "files as input"
});
ignoreCase = Option.Boolean("--ignore-case", true, { description: "ignore case for -f,--files, default true" });
globCwd = Option.String("--glob-cwd", { description: "cwd used in glob" });
yes = Option.Boolean("-y,--yes", false, { description: "exec commands, default false(only preview commands, aka dry run)" });
showTokens = Option.Boolean("-t,--tokens,--show-tokens", false, { description: "show available tokens" });
};
//#endregion
//#region src/util/file.ts
function getFilenameTokens(item) {
const fullpath = path.resolve(item);
const dir = path.dirname(fullpath);
const file = path.basename(fullpath);
let ext = path.extname(fullpath);
const name = path.basename(fullpath, ext);
ext = ext.slice(1);
const pdir = path.basename(dir);
return {
fullpath,
dir,
file,
name,
ext,
pdir,
rname: item
};
}
function renderFilenameTokens(template, options) {
const tokens = [
":pdir",
":rname",
":fullpath",
":dir",
":file",
":name",
":ext"
];
let result = template;
for (const t of tokens) {
const val = options[t.slice(1)];
if (!val) continue;
result = result.replaceAll(new RegExp(t, "g"), val);
}
return result;
}
function printFilenameTokens(tokens) {
const { fullpath, dir, file, name, ext, pdir, rname } = tokens;
console.log(` token ${chalk.green(":fullpath")} ${chalk.cyan(fullpath)}`);
console.log(` token ${chalk.green(":dir")} ${chalk.cyan(dir)}`);
console.log(` token ${chalk.green(":file")} ${chalk.cyan(file)}`);
console.log(` token ${chalk.green(":name")} ${chalk.cyan(name)}`);
console.log(` token ${chalk.green(":ext")} ${chalk.cyan(ext)}`);
console.log(` token ${chalk.green(":pdir")} ${chalk.cyan(pdir)}`);
console.log(` token ${chalk.green(":rname")} ${chalk.cyan(rname)}`);
}
//#endregion
//#region src/util/parse-line.ts
function parseLineToArgs(line) {
const result = [];
const regex = /'([^']*)'|"([^"]*)"|\S+/g;
let match;
while ((match = regex.exec(line)) !== null) if (match[1] !== void 0) result.push(match[1]);
else if (match[2] === void 0) result.push(match[0]);
else result.push(match[2]);
return result;
}
//#endregion
//#region src/commands/txt.ts
function inspectArray(arr) {
return arr.map((x) => `\`${x.toString()}\``).join(" | ");
}
var TxtCommand = class extends Command {
static paths = [["txt"]];
static usage = { description: "xargs txt <txt-file>, use `:line` as placeholder of a line of txt file, use (`:arg0` or `:args0`) ... to replace a single value" };
txt = Option.String({
name: "txt",
required: true
});
command = Option.String("-c,--command", {
required: true,
description: "the command to execute"
});
yes = Option.Boolean("-y,--yes", false, { description: "exec commands, default false(only preview commands, aka dry run)" });
wait = Option.Boolean("-w,--wait", false, { description: "wait new items when queue empty" });
waitTimeout = Option.String("--wait-timeout,--WT", { description: "wait timeout, will pass to ms()" });
session = Option.String("--session", SessionControl.Continue, { description: `session handling: default \`${SessionControl.Continue}\`; allowed values: ${inspectArray(Object.values(SessionControl))};` });
execute() {
return startTxtCommand({
...this,
session: z.nativeEnum(SessionControl).parse(this.session)
});
}
};
let SessionControl = /* @__PURE__ */ function(SessionControl$1) {
SessionControl$1["Start"] = "start";
SessionControl$1["ReStart"] = "restart";
SessionControl$1["Continue"] = "continue";
return SessionControl$1;
}({});
const defaultTxtCommandContext = { session: SessionControl.Continue };
const lognsp = "x-args:txt-command";
async function startTxtCommand(ctx) {
const { txt, command, wait, waitTimeout, yes, execOptions } = ctx;
const txtFile = path.resolve(txt);
console.log("");
console.log(`${chalk.green("[x-args]")}: received`);
console.log(` ${chalk.cyan("txt file")}: ${chalk.yellow(txtFile)}`);
console.log(` ${chalk.cyan("command")}: ${chalk.yellow(command)}`);
console.log("");
const sessionControl = ctx.session;
const sessionFile = path.join(path.dirname(txtFile), `.x-args-session.${path.basename(txtFile)}`);
let processed = /* @__PURE__ */ new Set();
if (sessionControl === SessionControl.Start) {
if (fse.existsSync(sessionFile) && fse.readFileSync(sessionFile, "utf-8").length) {
console.error(`session already exists, use \`${SessionControl.Continue}\` or \`${SessionControl.ReStart}\``);
process.exit(1);
}
} else if (sessionControl === SessionControl.ReStart) {
if (fse.existsSync(sessionFile)) fse.removeSync(sessionFile);
} else if (sessionControl === SessionControl.Continue && fse.existsSync(sessionFile)) {
const content = fse.readFileSync(sessionFile, "utf-8");
if (content) {
let _processed;
try {
_processed = superjson.parse(content).processed;
} catch {}
if (_processed) {
processed = new Set(_processed);
console.info(`${chalk.green(`[${lognsp}:session]`)} loaded from file %s`, sessionFile);
}
}
}
function saveProcessed() {
fse.outputFileSync(sessionFile, superjson.stringify({ processed }));
}
function getTxtNextLine() {
const lines = fse.readFileSync(txtFile, "utf-8").split("\n").map((line) => line.trim()).filter(Boolean).filter((line) => !(line.startsWith("//") || line.startsWith("#"))).filter((line) => !processed.has(line));
if (lines.length) return lines[0];
}
function getLineThenRunCommand() {
let worked = false;
let line;
while (line = getTxtNextLine()) {
worked = true;
const splitedArgs = parseLineToArgs(line);
const cmd = command.replaceAll(/:rawLine/gi, line).replaceAll(/:line/gi, escapeShellArg(line)).replaceAll(/:rawArgs?(\d)/gi, (match, index) => splitedArgs[index] || "").replaceAll(/:args?(\d)/gi, (match, index) => splitedArgs[index] ? escapeShellArg(splitedArgs[index]) : "");
console.log("");
console.log(boxen$1([`${chalk.green(" line =>")} ${chalk.yellow(line.padEnd(70, " "))}`, `${chalk.green(" cmd =>")} ${chalk.yellow(cmd)}`].join("\n"), {
borderColor: "green",
title: chalk.green(`${lognsp}:line`)
}));
if (yes) execSync(cmd, {
stdio: "inherit",
...execOptions
});
processed.add(line);
if (yes) {
saveProcessed();
setProgramExitTs();
}
}
return worked;
}
const waitTimeoutMs = waitTimeout ? ms(waitTimeout) : 0;
if (Number.isNaN(waitTimeoutMs)) throw new TypeError("unrecognized --wait-timeout format, pls check https://npm.im/ms");
let exitTs = Infinity;
function setProgramExitTs() {
if (waitTimeout) exitTs = Date.now() + waitTimeoutMs;
}
getLineThenRunCommand();
if (wait) {
const emitter = new Emittery();
const watcher = watch(txtFile).on("change", () => emitter.emit("change"));
const unsubscribe = once(() => watcher.close());
process.on("SIGINT", unsubscribe);
process.on("SIGTERM", unsubscribe);
process.on("exit", unsubscribe);
function waitChanged() {
return Promise.race([emitter.once("change"), waitTimeoutMs ? delay(waitTimeoutMs + 1e3) : void 0].filter(Boolean));
}
function printNoNewItems() {
console.log();
console.info(`${chalk.green(`[${lognsp}:wait]`)} no new items, waiting for changes ...`);
console.log();
}
let prevWorked = true;
while (Date.now() <= exitTs) {
if (prevWorked) {
if (!!!getTxtNextLine()) printNoNewItems();
}
await waitChanged();
prevWorked = getLineThenRunCommand();
}
unsubscribe();
}
}
//#endregion
export { getFilenameTokens as a, BaseCommand as c, startTxtCommand as i, TxtCommand as n, printFilenameTokens as o, defaultTxtCommandContext as r, renderFilenameTokens as s, SessionControl as t };