Skip to content

Commit 1f65bed

Browse files
committed
Fix Shipwright CLI output message when incorrect flag is passed
Fixes #346 # Changes: - Discard any messages or error written to stdio or stderr by goflag library. Return the error only. - In case of error while parsing the goflags, print the error, then print the CLI help and then exit with 1. Signed-off-by: Sayan Biswas <sayan-biswas@live.com>
1 parent f6e3846 commit 1f65bed

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

cmd/shp/main.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
goflag "flag"
55
"fmt"
6+
"io"
67
"os"
78

89
"github.com/spf13/pflag"
@@ -35,14 +36,17 @@ var hiddenLogFlags = []string{
3536
}
3637

3738
func main() {
39+
streams := genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}
40+
rootCmd := cmd.NewCmdSHP(&streams)
41+
3842
if err := initGoFlags(); err != nil {
39-
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
43+
fmt.Fprintf(os.Stderr, "ERROR: %v\n\n", err)
44+
// Print the CLI help in case of error.
45+
rootCmd.Help()
4046
os.Exit(1)
4147
}
4248
initPFlags()
4349

44-
streams := genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}
45-
rootCmd := cmd.NewCmdSHP(&streams)
4650
if err := rootCmd.Execute(); err != nil {
4751
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
4852
os.Exit(1)
@@ -53,9 +57,13 @@ func main() {
5357
// Any flags for "-h" or "--help" are ignored because pflag will show the usage later with all subcommands.
5458
func initGoFlags() error {
5559
flagset := goflag.NewFlagSet(ApplicationName, goflag.ContinueOnError)
60+
61+
// Discard usage and error message written to stdout and stderr in the "goflag" library.
62+
// Instead, return the error only.
63+
flagset.SetOutput(io.Discard)
64+
5665
goflag.CommandLine = flagset
5766
klog.InitFlags(flagset)
58-
5967
args := []string{}
6068
for _, arg := range os.Args[1:] {
6169
if arg != "-h" && arg != "--help" {

0 commit comments

Comments
 (0)