npx-run
Version:
Easily run scripts using npx.
79 lines (59 loc) • 2.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseArgs = exports.splitByScripts = exports.isPattern = exports.scriptKeys = void 0;
var _stringArgv = _interopRequireDefault(require("string-argv"));
var _iterables = require("./iterables");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const scriptKeys = scripts => Object.keys(scripts);
exports.scriptKeys = scriptKeys;
const isPattern = scriptOrPattern => scriptOrPattern.includes('*');
exports.isPattern = isPattern;
function* getMatchingScripts(scriptOrPattern, scripts) {
if (scripts[scriptOrPattern]) {
yield scriptOrPattern;
return;
}
if (!isPattern(scriptOrPattern)) {
return;
}
const pattern = new RegExp(`^${scriptOrPattern.replace(/\*/g, '.*?')}$`);
for (const script of scriptKeys(scripts)) {
if (script.match(pattern)) {
yield script;
}
}
}
const isScriptOrPattern = scripts => pattern => {
const [first] = getMatchingScripts(pattern, scripts);
return first !== undefined;
};
function* expandScriptPatterns(runArgs, [pattern, ...scriptArgs], scripts) {
for (const matchedScript of getMatchingScripts(pattern, scripts)) {
const command = (0, _stringArgv.default)(scripts[matchedScript]);
yield [runArgs, matchedScript, [...command, ...scriptArgs]];
}
}
const splitByScripts = (args, scripts) => (0, _iterables.groups)(args, isScriptOrPattern(scripts));
exports.splitByScripts = splitByScripts;
function* getTasks(args, scripts) {
const [runArgs, scriptsAndArgs] = (0, _iterables.headTail)(splitByScripts(args, scripts));
for (const argGroup of scriptsAndArgs) {
yield* expandScriptPatterns(runArgs, argGroup, scripts);
}
}
const parseArgs = (args, scripts) => {
const [arg] = args;
const dryRun = arg === '--dry-run';
const help = arg === '--help';
const remainingArgs = dryRun ? args.slice(1) : args;
const finalArgs = remainingArgs.length ? remainingArgs : ['default'];
const tasks = getTasks(finalArgs, scripts);
return {
tasks,
dryRun,
help
};
};
exports.parseArgs = parseArgs;