From 3aff4dfe2f22c36911509cadf4c09ea70768adc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20=C5=A0tibran=C3=BD?= Date: Fri, 13 Dec 2019 01:55:18 +0100 Subject: [PATCH] pkg/cfg: print help only when requested, and print it on stdout (#1396) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When invalid parameter or value is provided, error is printed to stderr, together with message indicating how to get list of all parameters. Signed-off-by: Peter Štibraný --- pkg/cfg/files.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/pkg/cfg/files.go b/pkg/cfg/files.go index afd35a9850c2..4c6d2b67c899 100644 --- a/pkg/cfg/files.go +++ b/pkg/cfg/files.go @@ -3,7 +3,9 @@ package cfg import ( "encoding/json" "flag" + "fmt" "io/ioutil" + "os" "github.com/pkg/errors" "gopkg.in/yaml.v2" @@ -61,7 +63,21 @@ func dYAML(y []byte) Source { func YAMLFlag(name, value, help string) Source { return func(dst interface{}) error { f := flag.String(name, value, help) - flag.Parse() + + usage := flag.CommandLine.Usage + flag.CommandLine.Usage = func() { /* don't do anything by default, we will print usage ourselves, but only when requested. */ } + + flag.CommandLine.Init(flag.CommandLine.Name(), flag.ContinueOnError) + err := flag.CommandLine.Parse(os.Args[1:]) + if err == flag.ErrHelp { + // print available parameters to stdout, so that users can grep/less it easily + flag.CommandLine.SetOutput(os.Stdout) + usage() + os.Exit(2) + } else if err != nil { + fmt.Fprintln(flag.CommandLine.Output(), "Run with -help to get list of available parameters") + os.Exit(2) + } if *f == "" { f = nil