Skip to content

Instantly share code, notes, and snippets.

@nexpr

nexpr/cli.js Secret

Last active January 7, 2022 07:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nexpr/cc7ad5bc1a8417b57accb254f31be6a1 to your computer and use it in GitHub Desktop.
Save nexpr/cc7ad5bc1a8417b57accb254f31be6a1 to your computer and use it in GitHub Desktop.
ex-scripts of npm scripts
#!/usr/bin/env node
const fs = require("fs")
const path = require("path")
const findPackageJson = () => {
let dir = process.cwd()
while (true) {
const json_path = path.join(dir, "package.json")
if (fs.existsSync(json_path)) {
return require(json_path)
}
const parent = path.dirname(dir)
if (dir === parent) return null
dir = parent
}
}
const [name, ...raw_params] = process.argv.slice(2)
if (!name) {
console.error("Script name is required.")
console.error("Usage: exsc <name> <param1> <param2> ...")
process.exit(1)
}
const pkg = findPackageJson()
if (!pkg || !pkg.exsc || !pkg.exsc[name]) {
console.error(`"${name}" is not found in package.json.`)
process.exit(1)
}
const opt = pkg.exsc[name]
const { command, defaults } = typeof opt === "string" ? { command: opt } : opt
if (!command) {
console.error(`"command" property is required.`)
process.exit(1)
}
const { result: parsed_params } = raw_params.reduce(
(acc, value) => {
if (value.startsWith("-")) {
acc.ctx = value.replace(/^-+/g, "")
} else {
acc.result[acc.ctx || acc.index++] = value
acc.ctx = null
}
return acc
},
{
index: 1,
ctx: null,
result: {},
}
)
const comm = String(command).replace(/\{([a-zA-Z0-9_]+)\}/g, (_, p) => {
if (p in parsed_params) return parsed_params[p]
if (defaults && p in defaults) return defaults[p]
console.error(`"${p}" is not found in params and defaults.`)
process.exit(1)
})
require("child_process").spawnSync(comm, { shell: true, stdio: "inherit" })
{
"name": "exsc",
"version": "1.0.0",
"bin": "cli.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment