Skip to content

Commit

Permalink
pkg/cfg: print help only when requested, and print it on stdout (#1396)
Browse files Browse the repository at this point in the history
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ý <peter.stibrany@grafana.com>
  • Loading branch information
pstibrany authored and cyriltovena committed Dec 13, 2019
1 parent c4e669d commit 3aff4df
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion pkg/cfg/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package cfg
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"

"github.com/pkg/errors"
"gopkg.in/yaml.v2"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 3aff4df

Please sign in to comment.