clikt
clikt copied to clipboard
Add possibility to do custom action on the option parsing exceptions
When I run my application with unknown option, like --nonsense
, I get error Error: no such option: "--nonsense"
, and that's ok:
$ java -jar myapp.jar --nonsense
Error: no such option: "--nonsense"
But I'd like to print help message after that, but it seems like clikt doesn't do this, and there is no way to do it manually.
I've found this code:
/**
* Parse the command line and print helpful output if any errors occur.
*
* This function calls [parse] and catches and [CliktError]s that are thrown. Other errors are allowed to
* pass through.
*/
fun main(argv: List<String>) {
try {
parse(argv)
} catch (e: ProgramResult) {
exitProcessMpp(e.statusCode)
} catch (e: PrintHelpMessage) {
echo(e.command.getFormattedHelp())
exitProcessMpp(if (e.error) 1 else 0)
} catch (e: PrintCompletionMessage) {
val s = if (e.forceUnixLineEndings) "\n" else currentContext.console.lineSeparator
echo(e.message, lineSeparator = s)
exitProcessMpp(0)
} catch (e: PrintMessage) {
echo(e.message)
exitProcessMpp(if (e.error) 1 else 0)
} catch (e: UsageError) {
echo(e.helpMessage(), err = true)
exitProcessMpp(e.statusCode)
} catch (e: CliktError) {
echo(e.message, err = true)
exitProcessMpp(1)
} catch (e: Abort) {
echo(currentContext.localization.aborted(), err = true)
exitProcessMpp(if (e.error) 1 else 0)
}
}
which prints out exception and exits program right away. I'd like there to be customization point:
} catch (e: UsageError) {
echo(e.helpMessage(), err = true)
onUsageError(e) // <<< ADD THIS
exitProcessMpp(e.statusCode)
} catch (e: CliktError) {
// later on, something like this
protected open fun onUsageError(e: UsageError) {
// no action right here, customization point
}
I even can try to implement this and send PR.