diff --git a/package.json b/package.json index 6fb6f8c..cefec7a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@paolo-projects/terminal-emulator", - "version": "0.2.0", + "version": "0.2.1", "description": "", "main": "build/index.js", "types": "build/index.d.ts", diff --git a/src/CommandScheme/index.ts b/src/CommandScheme/index.ts index 7fa469c..d314d1e 100644 --- a/src/CommandScheme/index.ts +++ b/src/CommandScheme/index.ts @@ -3,6 +3,7 @@ import FlagArgument from '../Argument/FlagArgument'; import PositionalArgument from '../Argument/PositionalArgument'; import ValueArgument from '../Argument/ValueArgument'; import Command from '../Command'; +import OutputStream from '../OutputStream'; import ArgumentScheme, { FlagArgumentScheme, PositionalArgumentScheme, @@ -15,16 +16,24 @@ export type CommandSchemeMatchCallback = ( ) => Promise; export default class CommandScheme { + private outputStream?: OutputStream; + private constructor( public name: string, public argSchemes: ArgumentScheme[], - public matchCallback: CommandSchemeMatchCallback + public matchCallback: CommandSchemeMatchCallback, + public helpMessage?: string ) {} + setOutputStream(stream: OutputStream) { + this.outputStream = stream; + } + static Builder = class { name: string; args: ArgumentScheme[] = []; schemeCallback?: CommandSchemeMatchCallback; + helpMsg?: string; constructor(commandName: string) { this.name = commandName; @@ -56,6 +65,11 @@ export default class CommandScheme { return this; } + withHelpMessage(helpMessage: string) { + this.helpMsg = helpMessage; + return this; + } + callback(callback: CommandSchemeMatchCallback) { this.schemeCallback = callback; return this; @@ -65,7 +79,8 @@ export default class CommandScheme { return new CommandScheme( this.name, this.args, - this.schemeCallback!! + this.schemeCallback!!, + this.helpMsg ); } }; @@ -75,6 +90,16 @@ export default class CommandScheme { return false; } + if ( + this.helpMessage && + command.args.filter( + (arg) => arg instanceof FlagArgument && arg.name === 'help' + ).length + ) { + this.outputStream?.writeLine(this.helpMessage); + return true; + } + for (const argScheme of this.argSchemes) { switch (argScheme.argType) { case 'positional': diff --git a/src/TerminalEmulator/index.ts b/src/TerminalEmulator/index.ts index 23b4338..26205d5 100644 --- a/src/TerminalEmulator/index.ts +++ b/src/TerminalEmulator/index.ts @@ -17,6 +17,7 @@ export default class TerminalEmulator { private commandNotFoundHandler: CommandCallback | null = null; command(scheme: CommandScheme): TerminalEmulator { + scheme.setOutputStream(this.outputStream); this.commandSchemes.push(scheme); return this; }