UNPKG

cmd-ts

Version:

> 💻 A type-driven command line argument parser, with awesome error reporting 🤤

83 lines • 2.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = exports.dryRun = exports.runSafely = exports.run = void 0; const tokenizer_1 = require("./newparser/tokenizer"); const parser_1 = require("./newparser/parser"); const errorBox_1 = require("./errorBox"); const Result_1 = require("./Result"); const effects_1 = require("./effects"); async function run(ap, strings) { const result = await runSafely(ap, strings); if ((0, Result_1.isErr)(result)) { return result.error.run(); } else { return result.value; } } exports.run = run; /** * Runs a command but does not apply any effect */ async function runSafely(ap, strings) { const hotPath = []; const nodes = parseCommon(ap, strings); try { const result = await ap.run({ nodes, visitedNodes: new Set(), hotPath }); if ((0, Result_1.isErr)(result)) { throw new effects_1.Exit({ message: (0, errorBox_1.errorBox)(nodes, result.error.errors, hotPath), exitCode: 1, into: 'stderr', }); } else { return (0, Result_1.ok)(result.value); } } catch (e) { if (e instanceof effects_1.Exit) { return (0, Result_1.err)(e); } throw e; } } exports.runSafely = runSafely; /** * Run a command but don't quit. Returns an `Result` instead. */ async function dryRun(ap, strings) { const result = await runSafely(ap, strings); if ((0, Result_1.isErr)(result)) { return (0, Result_1.err)(result.error.dryRun()); } else { return result; } } exports.dryRun = dryRun; /** * Parse the command as if to run it, but only return the parse result and don't run the command. */ function parse(ap, strings) { const hotPath = []; const nodes = parseCommon(ap, strings); return ap.parse({ nodes, visitedNodes: new Set(), hotPath }); } exports.parse = parse; function parseCommon(ap, strings) { const longFlagKeys = new Set(); const shortFlagKeys = new Set(); const longOptionKeys = new Set(); const shortOptionKeys = new Set(); const registerContext = { forceFlagShortNames: shortFlagKeys, forceFlagLongNames: longFlagKeys, forceOptionShortNames: shortOptionKeys, forceOptionLongNames: longOptionKeys, }; ap.register(registerContext); const tokens = (0, tokenizer_1.tokenize)(strings); return (0, parser_1.parse)(tokens, registerContext); } //# sourceMappingURL=runner.js.map