Skip to content

Commit 3aff4df

Browse files
pstibranycyriltovena
authored andcommitted
pkg/cfg: print help only when requested, and print it on stdout (#1396)
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ý <[email protected]>
1 parent c4e669d commit 3aff4df

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

pkg/cfg/files.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ package cfg
33
import (
44
"encoding/json"
55
"flag"
6+
"fmt"
67
"io/ioutil"
8+
"os"
79

810
"github.com/pkg/errors"
911
"gopkg.in/yaml.v2"
@@ -61,7 +63,21 @@ func dYAML(y []byte) Source {
6163
func YAMLFlag(name, value, help string) Source {
6264
return func(dst interface{}) error {
6365
f := flag.String(name, value, help)
64-
flag.Parse()
66+
67+
usage := flag.CommandLine.Usage
68+
flag.CommandLine.Usage = func() { /* don't do anything by default, we will print usage ourselves, but only when requested. */ }
69+
70+
flag.CommandLine.Init(flag.CommandLine.Name(), flag.ContinueOnError)
71+
err := flag.CommandLine.Parse(os.Args[1:])
72+
if err == flag.ErrHelp {
73+
// print available parameters to stdout, so that users can grep/less it easily
74+
flag.CommandLine.SetOutput(os.Stdout)
75+
usage()
76+
os.Exit(2)
77+
} else if err != nil {
78+
fmt.Fprintln(flag.CommandLine.Output(), "Run with -help to get list of available parameters")
79+
os.Exit(2)
80+
}
6581

6682
if *f == "" {
6783
f = nil

0 commit comments

Comments
 (0)