UNPKG

daizong

Version:

`package.json` script runner for ES Modules

113 lines 3.55 kB
export var Command; (function (Command) { Command[Command["version"] = 0] = "version"; Command[Command["help"] = 1] = "help"; Command[Command["run"] = 2] = "run"; })(Command || (Command = {})); var BuilderNextValue; (function (BuilderNextValue) { BuilderNextValue[BuilderNextValue["taskPath"] = 0] = "taskPath"; BuilderNextValue[BuilderNextValue["configFile"] = 1] = "configFile"; BuilderNextValue[BuilderNextValue["taskArgs"] = 2] = "taskArgs"; })(BuilderNextValue || (BuilderNextValue = {})); class ArgsBuilder { result = { command: Command.run, taskName: '', taskArgs: [], }; nextValue = BuilderNextValue.taskPath; handleArg(s) { const { result, nextValue } = this; if (nextValue === BuilderNextValue.taskArgs) { result.taskArgs.push(s); return true; } if (s.startsWith('-')) { if (nextValue === BuilderNextValue.configFile) { this.throwConfigFileNotSet(); } switch (s) { case '-v': case '--version': { result.command = Command.version; return false; } case '--help': { result.command = Command.help; return false; } case '--verbose': { result.verbose = true; break; } case '--private': { result.private = true; break; } case '--config': { this.nextValue = BuilderNextValue.configFile; break; } default: { throw new Error(`Unknown option \`${s}\`.`); } } } else { switch (nextValue) { case BuilderNextValue.configFile: { result.configFile = s; this.nextValue = BuilderNextValue.taskPath; break; } case BuilderNextValue.taskPath: { result.taskName = s; this.nextValue = BuilderNextValue.taskArgs; break; } default: { throw new Error(`Unexpected value ${nextValue}`); } } } return true; } getResult() { const { result, nextValue } = this; if (result.command !== Command.run) { return result; } if (nextValue === BuilderNextValue.configFile) { this.throwConfigFileNotSet(); } if (nextValue === BuilderNextValue.taskPath) { throw new Error('No task specified.'); } return result; } throwConfigFileNotSet() { throw new Error("`--config` doesn't have a valid value set."); } } export function parseArgs(args) { try { const builder = new ArgsBuilder(); for (const s of args) { const shouldContinue = builder.handleArg(s); if (!shouldContinue) { break; } } return builder.getResult(); } catch (err) { return { error: err instanceof Error ? err.message : `${err}`, command: Command.version, taskName: '', taskArgs: [], }; } } //# sourceMappingURL=argsParser.js.map