-
-
Save nexpr/cc7ad5bc1a8417b57accb254f31be6a1 to your computer and use it in GitHub Desktop.
ex-scripts of npm scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" }) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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