Skip to content

Commit

Permalink
fix: Correctly return errors from command run function
Browse files Browse the repository at this point in the history
Cobra will print a stacktrace if you forcibly close the process
from within a cmd.Run function.
Using RunE and return errors will prevent this.
Cobra will print errors returned this way for you, so the
fmt.Println(err) in rootCmd was redundant.

Signed-off-by: Wouter Dullaert <[email protected]>
  • Loading branch information
wdullaer authored and andrewrynhard committed Jan 22, 2020
1 parent 01f87b9 commit 59f365a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 11 deletions.
20 changes: 11 additions & 9 deletions cmd/enforce.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
package cmd

import (
"errors"
"fmt"
"log"
"os"

"github.com/spf13/cobra"
"github.com/talos-systems/conform/internal/enforcer"
Expand All @@ -19,16 +18,18 @@ var enforceCmd = &cobra.Command{
Use: "enforce",
Short: "",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
fmt.Println("The enforce command does not take arguments")
os.Exit(1)
return errors.New("the enforce command does not take arguments")
}
// Done validating the arguments, do not print usage for errors
// after this point
cmd.SilenceUsage = true

summarizer := cmd.Flags().Lookup("summary").Value.String()
e, err := enforcer.New(summarizer)
if err != nil {
log.Printf("failed to create enforcer: %+v\n", err)
os.Exit(1)
return fmt.Errorf("failed to create enforcer: %+v", err)
}

opts := []policy.Option{}
Expand All @@ -38,9 +39,10 @@ var enforceCmd = &cobra.Command{
}

if err := e.Enforce(opts...); err != nil {
log.Printf("%+v\n", err)
os.Exit(1)
return err
}

return nil
},
}

Expand Down
2 changes: 0 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"
Expand All @@ -22,7 +21,6 @@ var rootCmd = &cobra.Command{
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

0 comments on commit 59f365a

Please sign in to comment.