mkideal / cli

CLI - A package for building command line app with go
MIT License
730 stars 43 forks source link

Terminate with non-zero exit code in case of an error #43

Closed meisterluk closed 6 years ago

meisterluk commented 6 years ago

Consider the following example:

package main

import (
    "fmt"

    "github.com/mkideal/cli"
)

type args struct {
    cli.Helper
    Param string `cli:"*p,param" usage:"whatever"`
}

func main() {
    cli.Run(new(args), func(ctx *cli.Context) error {
        argv := ctx.Argv().(*args)
        ctx.String("parameter was %s\n", argv.Param)
        return fmt.Errorf("Some random error")
    })
}

Now let us run this example:

ryu@gaku ~ % go build test.go
ryu@gaku ~ % ./test
ERR! required parameter --param missing
ryu@gaku ~ % echo $?
0
ryu@gaku ~ % ./test --param 1
parameter was 1
Some random error
ryu@gaku ~ % echo $?
0
ryu@gaku ~ % 

So apparently in case of ./test, the exit code was 0. The same holds true for ./text --param 1. In both cases, something went wrong (invalid parameter values, CommandFunc returned an error). It is common practice (and necessary requirement for every sysadmin to detect problems by looking for non-zero exit codes) to return non-zero if the software could not complete its main task correctly.

Technically, it seems to be the responsibility of the main routine to return the exit code. However, the whole information regarding the exit code is lost in the abstractions of cli. Therefore I am requesting for appropriate fixes to give a proper exit code.

suntong commented 6 years ago

Hi @meisterluk, would you take a look at #46, and tell me what do you think please?

meisterluk commented 6 years ago

LGTM.

Glad to see some improvements. Thank you, @suntong! Feel free to apply the merge request to your repository.