Skip to content

Commit

Permalink
Carry custom status code for commands to os.Exit()
Browse files Browse the repository at this point in the history
  • Loading branch information
francislavoie committed Oct 10, 2023
1 parent a35c1d4 commit 34b2b96
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
21 changes: 20 additions & 1 deletion cmd/cobra.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package caddycmd

import (
"fmt"

"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -123,7 +125,24 @@ func caddyCmdToCobra(caddyCmd Command) *cobra.Command {
// in a cobra command's RunE field.
func WrapCommandFuncForCobra(f CommandFunc) func(cmd *cobra.Command, _ []string) error {
return func(cmd *cobra.Command, _ []string) error {
_, err := f(Flags{cmd.Flags()})
status, err := f(Flags{cmd.Flags()})
if status > 1 {
cmd.SilenceErrors = true
return &exitError{ExitCode: status, Err: err}
}
return err
}
}

// exitError carries the exit code from CommandFunc to Main()
type exitError struct {
ExitCode int
Err error
}

func (e *exitError) Error() string {
if e.Err == nil {
return fmt.Sprintf("exiting with status %d", e.ExitCode)
}
return e.Err.Error()
}
5 changes: 5 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package caddycmd
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io"
Expand Down Expand Up @@ -63,6 +64,10 @@ func Main() {
}

if err := rootCmd.Execute(); err != nil {
var exitError *exitError
if errors.As(err, &exitError) {
os.Exit(exitError.ExitCode)
}
os.Exit(1)
}
}
Expand Down

0 comments on commit 34b2b96

Please sign in to comment.