Skip to content

Commit

Permalink
feat(core): enhance repl 'help' command with nestjs functions
Browse files Browse the repository at this point in the history
  • Loading branch information
micalevisk committed Nov 28, 2022
1 parent 220b098 commit d8ece48
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
51 changes: 51 additions & 0 deletions packages/core/repl/repl-native-commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { REPLServer } from 'repl';

/**
* Displays the list of available commands in the REPL alonside with their
* descriptions.
* (c) This code was inspired by the 'help' command from Node.js core:
* {@link https://github.com/nodejs/node/blob/58b60c1393dd65cd228a8b0084a19acd2c1d16aa/lib/repl.js#L1741-L1759}
*/
/* istanbul ignore next */
function listAllCommands(replServer: REPLServer) {
Object.keys(replServer.commands)
.sort()
.forEach(name => {
const cmd = replServer.commands[name];
if (cmd) {
replServer.output.write(`${name}\t${cmd.help || ''}\n`);
}
});
}

export function defineDefaultCommandsOnRepl(replServer: REPLServer): void {
replServer.defineCommand('help', {
help: 'Show REPL options',
action(name?: string) {
this.clearBufferedCommand();

if (name) {
// Considering native commands before native nestjs injected functions.
const nativeCommandOrFunction =
this.commands[name] || this.context[name];
// NOTE: If the command was retrieve from the context, it will have a `help`
// getter property that outputs the helper message and returns undefined.
// But if the command was retrieve from the `commands` object, it will
// have a `help` property that returns the helper message.
const helpMessage = nativeCommandOrFunction?.help;
if (helpMessage) {
this.output.write(`${helpMessage}\n`);
}
} else {
listAllCommands(this);
this.output.write('\n\n');
this.context.help();
this.output.write(
'\nPress Ctrl+C to abort current expression, Ctrl+D to exit the REPL\n',
);
}

this.displayPrompt();
},
});
}
3 changes: 3 additions & 0 deletions packages/core/repl/repl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { assignToObject } from './assign-to-object.util';
import { REPL_INITIALIZED_MESSAGE } from './constants';
import { ReplContext } from './repl-context';
import { ReplLogger } from './repl-logger';
import { defineDefaultCommandsOnRepl } from './repl-native-commands';

export async function repl(module: Type | DynamicModule) {
const app = await NestFactory.createApplicationContext(module, {
Expand All @@ -23,5 +24,7 @@ export async function repl(module: Type | DynamicModule) {
});
assignToObject(replServer.context, replContext.globalScope);

defineDefaultCommandsOnRepl(replServer);

return replServer;
}

0 comments on commit d8ece48

Please sign in to comment.