Skip to content

Commit 9427167

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 <[email protected]>
1 parent f6e3846 commit 9427167

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

cmd/shp/main.go

Lines changed: 14 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,19 @@ 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+
if err = rootCmd.Help(); err != nil {
46+
fmt.Fprintf(os.Stderr, "ERROR: %v\n\n", err)
47+
}
4048
os.Exit(1)
4149
}
4250
initPFlags()
4351

44-
streams := genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}
45-
rootCmd := cmd.NewCmdSHP(&streams)
4652
if err := rootCmd.Execute(); err != nil {
4753
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
4854
os.Exit(1)
@@ -53,9 +59,13 @@ func main() {
5359
// Any flags for "-h" or "--help" are ignored because pflag will show the usage later with all subcommands.
5460
func initGoFlags() error {
5561
flagset := goflag.NewFlagSet(ApplicationName, goflag.ContinueOnError)
62+
63+
// Discard usage and error message written to stdout and stderr in the "goflag" library.
64+
// Instead, return the error only.
65+
flagset.SetOutput(io.Discard)
66+
5667
goflag.CommandLine = flagset
5768
klog.InitFlags(flagset)
58-
5969
args := []string{}
6070
for _, arg := range os.Args[1:] {
6171
if arg != "-h" && arg != "--help" {

0 commit comments

Comments
 (0)