diff --git a/examples/repl-dynamic-prompt.ts b/examples/repl-dynamic-prompt.ts new file mode 100644 index 00000000..9545604e --- /dev/null +++ b/examples/repl-dynamic-prompt.ts @@ -0,0 +1,21 @@ +import { command, program } from "../src/index.js"; + +const app = program({ + prompt: () => `[${new Date().toLocaleTimeString()}] > `, +}); + +async function rng(bounds: [number, number]) { + const [min, max] = bounds; + return Math.floor(Math.random() * (max - min + 1)) + min; +} + +const dice = app.add( + command("roll") + .option("min", { default: 1 }) + .option("max", { default: 6 }) + .action(async (args) => { + console.log(await rng([args.min, args.max])); + }), +); + +app.runOrRepl(); diff --git a/src/program.ts b/src/program.ts index dfe4198c..3c7cca6f 100644 --- a/src/program.ts +++ b/src/program.ts @@ -31,7 +31,7 @@ type ProgramOptions = { * * Defaults to `> `. */ - prompt?: string; + prompt?: string | (() => string); /** * Whether or not to add a global help command that displays an overview of diff --git a/src/repl.ts b/src/repl.ts index 547fad68..c7dffebe 100644 --- a/src/repl.ts +++ b/src/repl.ts @@ -42,8 +42,9 @@ export class Repl { * @private */ public async start() { + const { prompt } = this.program.options; this.server = nodeRepl.start({ - prompt: this.program.options.prompt, + prompt: typeof prompt === "function" ? prompt() : prompt, eval: this.eval.bind(this), completer: this.completer.bind(this), ignoreUndefined: true,