xenomachina / kotlin-argparser

Easy to use and concise yet powerful and robust command line argument parsing for Kotlin
GNU Lesser General Public License v2.1
485 stars 33 forks source link

Support to print usage explicitly or on error. #39

Open DALDEI opened 6 years ago

DALDEI commented 6 years ago

On any SystemExitException except for --help there is no obvious way I could find to print the help text. In general on error I'd like to print the help text.

The best I could do was to recursively call main("--help") then some ugly code to prevent infinte recursion.

snippet:


catch (h: SystemExitException)
  {
    var w = StringWriter()
    w.use {
      h.printUserMessage(it, progName="maildb-cli", columns=120)
    }
    System.out.println( w.toString() )
    if( h is ShowHelpException ) System.exit(0)
    main(arrayOf("--help"))
  }

Other libraries like JCommander, joptsimple etc provide some way to call the usage() method and/or some way to trigger it being displayed on an error.

The above code is embarrassingly ugly. I attempted something slightly less ugly - to create a ShowHelpMessageException() but the constructor is internal, plus I don't have access to the parsed help values.

xenomachina commented 6 years ago

This is a good idea!

Are you just asking for something you can call to display the help, or do you also want an easy way to enable help printing on error (like perhaps a "usageOnError" flag to mainBody)?

davidgodzsak commented 6 years ago

I think it would be nice to have something like ArgPareser(args).printHelp()

davidgodzsak commented 6 years ago

Any progress on this one?

xenomachina commented 6 years ago

Sorry, no, I haven't had a chance to work on this one yet.

I don't think it would be hard to implement though. If you're interested I'd be happy to review a pull request. I'm thinking a printHelp() method like you mentioned, and a way to tell mainBody that it should call printHelp() on error (ie: when handling a SystemExitException and returnCode != 0).