import * as meant from 'meant'; import { CliProgram } from './program'; import { ParserErrors as IParserErrors, ParserErrorType } from './types'; export class ParserErrors implements IParserErrors { private _errors: Map = new Map(); private _unknownCommand: string; constructor(private program: CliProgram) { } public get unknownCommand(): string { return this._unknownCommand; } public get unknownCommandSuggestions(): string[] { if (this.unknownCommand) { const commandNames = this.program.commands.map(p => p.name); return meant(this.unknownCommand, commandNames) || []; } return []; } public get commandErrors(): string[] { return this.getErrors('command'); } public get argumentErrors(): string[] { return this.getErrors('argument'); } public get optionErrors(): string[] { return this.getErrors('option'); } public get allErrors(): string[] { return [...this.commandErrors, ...this.argumentErrors, ...this.optionErrors]; } public getErrors = (type?: ParserErrorType) => { if (type) { if (!this._errors.has(type)) { this._errors.set(type, []); } return this._errors.get(type); } else { return this.allErrors; } }; public clearErrors = (type?: ParserErrorType) => { if (type) { this._errors.set(type, []); } else { this._errors.clear(); } if (type === 'command' || !type) { this._unknownCommand = undefined; } }; public pushUnknownCommand = (commandName: string) => { this._unknownCommand = commandName; this.push('command', `Unknown Command: '${commandName}'`); }; public push = (type: ParserErrorType, message: string) => { const errs = this.getErrors(type); errs.push(message); this._errors.set(type, errs); }; public get hasErrors(): boolean { return this.allErrors.length > 0; } public get hasNonArgOrOptionErrors(): boolean { return this.commandErrors.length > 0; } }