microsoft / rushstack

Monorepo for tools developed by the Rush Stack community
https://rushstack.io/
Other
5.81k stars 592 forks source link

[ts-command-line] get help text programmatically #2366

Open mmkal opened 3 years ago

mmkal commented 3 years ago

Summary

It'd be good to have a way to get help text from a CommandLineParser (or Action) subclass without having to run the CLI. The text could be used in markdown doc generation and/or snapshot testing.

Repro steps

Not a bug. But it'd be good if we could do something like

const {CommandLineAction, CommandLineParser, CommandLineFlagParameter, CommandLineChoiceParameter} = require("@rushstack/ts-command-line")

class WidgetCommandLine extends CommandLineParser {
  constructor() {
    super({
      toolFilename: 'widget',
      toolDescription: 'blah blah'
    });
 }

  onDefineParameters() {
  }

  onExecute() {
    return super.onExecute();
  }
}

test('snapshot help text', () => {
  const cli = new WidgetCommandLine()
  expect(cli.getHelpText()).toMatchInlineSnapshot()
})

Expected result:

Synchronously return the help text that is normally printed to the console when running a CLI with --help.

Actual result:

We have to do things like const mockStdout = jest.mock(process.stdout, 'write'), which has other side-effects, and the ANSI color codes have to be manually stripped.

Details

Not sure exactly how this help text is generated - is that handled by argparse?

Standard questions

Question Answer
Package name: @rushstack/ts-command-line
Package version? 4.7.7
Operating system? any
Would you consider contributing a PR? Sure
Node.js version (node -v)? 12.18.0
mmkal commented 3 years ago

On further digging, new WidgetCommandLine()._argumentParser.formatHelp() gets most of the way there/works at runtime, if type errors are suppressed. This request might can just be to expose that functionality not via a private member.

mmkal commented 3 years ago

On further further digging, this exists, under renderHelpText()! I guess this is just a docs request.

octogonz commented 3 years ago

Cool, we can update the docs.

Longer term I'd really like to rewrite the ts-command-line implementation so that it does not depend on argparse. The kind of parsing we need to do is rather easy, and a custom implementation would make it easier to fix certain issues such as word-wrapping bugs.

Just haven't had time to get around to working on it. :-)