UNPKG

@magicdawn/x-args

Version:

play with cli commands like a composer

103 lines (99 loc) 3.08 kB
#!/usr/bin/env node import { BaseCommand, TxtCommand, getFilenameTokens, printFilenameTokens, renderFilenameTokens } from "./chunk-UYSQCFDA.js"; // src/bin.ts import { Builtins, Cli } from "clipanion"; import { createRequire } from "module"; // src/commands/default.ts import chalk from "chalk"; import { execSync } from "child_process"; import { Command, Option } from "clipanion"; import fg from "fast-glob"; import { PathFinder } from "mac-helper"; var DefaultCommand = class extends BaseCommand { static paths = [Command.Default]; static usage = { description: "xargs" }; command = Option.String("-c,--command", "", { description: "the command to execute" }); execute() { return this.run(); } async run() { const { files, command } = this; console.log(""); console.log(`${chalk.green("[x-args]")}: received`); console.log(` ${chalk.cyan("files")}: ${chalk.yellow(files)}`); console.log(`${chalk.cyan("command")}: ${chalk.yellow(command)}`); console.log(""); let resolvedFiles = []; if (files === "$PF") { resolvedFiles = await PathFinder.allSelected(); if (!resolvedFiles.length) { console.error("$PF has no selected files"); process.exit(1); } } else { resolvedFiles = fg.sync(files, { caseSensitiveMatch: !this.ignoreCase }); console.log( `${chalk.green("[globby]")}: docs ${chalk.blue( "https://github.com/mrmlnc/fast-glob#pattern-syntax" )}` ); } console.log( `${chalk.green("[files]")}: mapping ${chalk.yellow(files)} to ${chalk.yellow( resolvedFiles.length )} files ->` ); resolvedFiles.forEach((f) => { console.log(` ${chalk.cyan(f)}`); }); for (let item of resolvedFiles) { const tokens = getFilenameTokens(item); const usingCommand = renderFilenameTokens(this.command, tokens); console.log(""); console.log(`${chalk.green("[exec]")} for ${chalk.yellow(item)}`); this.command && console.log(` ${chalk.green("command")}: ${chalk.yellow(usingCommand)}`); if (this.showTokens || !this.command) { printFilenameTokens(tokens); } if (this.yes) { execSync(usingCommand, { stdio: "inherit" }); } } if (!this.yes) { console.log(""); console.log("-".repeat(80)); console.log( ` current ${chalk.yellow("previewing")} commands. After comfirmed, append ${chalk.green( "-y or --yes" )} flag to execute` ); console.log("-".repeat(80)); console.log(""); } } }; // src/bin.ts var require2 = createRequire(import.meta.url); var { version, name, bin } = require2("../package"); var [node, app, ...args] = process.argv; var cli = new Cli({ binaryLabel: name, binaryName: Object.keys(bin)[0], binaryVersion: version }); cli.register(Builtins.HelpCommand); cli.register(Builtins.VersionCommand); cli.register(Builtins.DefinitionsCommand); cli.register(TxtCommand); cli.register(DefaultCommand); cli.runExit(args, Cli.defaultContext);