mkideal / cli

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

Fix issue #43 #45

Closed meisterluk closed 6 years ago

meisterluk commented 6 years ago

A failing CLI execution must return a non-zero exitcode.

It would be nice to call os.Exit automatically with proper exit codes, when execution fails. Features such as "different exitcode for errors 'value for given parameter invalid' and 'parameter missing'" would be nice. However, we can also keep it simple and just return 0 (success) and 1 (any error). If so, we don't call os.Exit automatically, keep testing simpler and do not break backwards compatibility.

This fix keeps its it very simple with minimal code change: Introduce an integer return value for func Run(...) in cli.go. This integer can be passed to os.Exit as recommended by all examples.

  % git diff -u cli.go
  diff --git a/cli.go b/cli.go
  index 41ce39e..64fb55c 100644
  --- a/cli.go
  +++ b/cli.go
  @@ -11,12 +11,12 @@ import (
   )

   // Run runs a single command app
  -func Run(argv interface{}, fn CommandFunc, descs ...string) {
  -       RunWithArgs(argv, os.Args, fn, descs...)
  +func Run(argv interface{}, fn CommandFunc, descs ...string) int {
  +       return RunWithArgs(argv, os.Args, fn, descs...)
   }

   // RunWithArgs is similar to Run, but with args instead of os.Args
  -func RunWithArgs(argv interface{}, args []string, fn CommandFunc, descs
  ...string) {
  +func RunWithArgs(argv interface{}, args []string, fn CommandFunc, descs
  ...string) int {
          desc := ""
          if len(descs) > 0 {
                  desc = strings.Join(descs, "\n")
  @@ -30,7 +30,9 @@ func RunWithArgs(argv interface{}, args []string, fn
  CommandFunc, descs ...strin
          }).Run(args[1:])
          if err != nil {
                  fmt.Fprintln(os.Stderr, err)
  +               return 1
          }
  +       return 0
   }

(Also fixes one typo in "run-examples.sh")

coveralls commented 6 years ago

Coverage Status

Coverage decreased (-0.02%) to 67.411% when pulling 2bd88dc6351590f031ada0227f72454accc687e8 on meisterluk:master into a9c1104566927924fdb041d198f05617492913f9 on mkideal:master.