@@ -9,44 +9,39 @@ import (
9
9
"os"
10
10
"regexp"
11
11
12
+ "github.com/cockroachdb/errors"
12
13
"github.com/spf13/pflag"
13
14
)
14
15
15
16
// DoEnv calls Do with os.Args[1:] as the first argument.
16
- func DoEnv (name string , out * string ) error {
17
+ func DoEnv (name string , out interface {} ) error {
17
18
return Do (os .Args [1 :], name , out )
18
19
}
19
20
20
- // Do looks for the flags specified in `names` (no leading dashes) and
21
- // sets the corresponding `out` values to the values found in `args`. This only
22
- // works for string flags and in particular does not reliably work for
23
- // "presence" flags, such as bools, since these flags don't carry an explicit
24
- // value in the args.
21
+ // Do looks for the flag `name` (no leading dashes) and sets the corresponding
22
+ // `out` values to the value found in `args`.
23
+ // Currently, `out` must be of type `*string` or `*bool`, though additional
24
+ // types should be straightforward to add as needed.
25
25
//
26
- // This is a helper for benchmarks that want to react to flags from their
27
- // environment.
28
- func Do (inArgs []string , name string , out * string ) error {
26
+ // This is a helper for tests and benchmarks that want to react to flags from
27
+ // their environment.
28
+ func Do (args []string , name string , out interface {} ) error {
29
29
pf := pflag .NewFlagSet ("test" , pflag .ContinueOnError )
30
- pf .StringVar (out , name , "" , "" )
31
- var args []string
32
- var addNext bool
33
- for _ , arg := range inArgs {
34
- if addNext {
35
- addNext = false
36
- args = append (args , arg )
37
- }
30
+ switch t := out .(type ) {
31
+ case * string :
32
+ pf .StringVar (t , name , "" , "" )
33
+ case * bool :
34
+ pf .BoolVar (t , name , false , "" )
35
+ default :
36
+ return errors .Errorf ("unsupported type %T" , t )
37
+ }
38
+ pf .ParseErrorsWhitelist = pflag.ParseErrorsWhitelist {UnknownFlags : true }
39
+ args = append ([]string (nil ), args ... )
40
+ for i , arg := range args {
38
41
re := regexp .MustCompile (`^(-{1,2})` + regexp .QuoteMeta (name ) + `(=|$)` )
39
- if matches := re .FindStringSubmatch (arg ); len (matches ) > 0 {
40
- if len (matches [1 ]) == 1 {
41
- // Transform `-foo` into `--foo` for pflag-style flag.
42
- arg = "-" + arg
43
- }
44
- if len (matches [2 ]) == 0 {
45
- // The matched flag is of form `--foo bar` (vs `--foo=bar`), so value
46
- // is next arg.
47
- addNext = true
48
- }
49
- args = append (args , arg )
42
+ if matches := re .FindStringSubmatch (arg ); len (matches ) > 0 && len (matches [1 ]) == 1 {
43
+ // Transform `-foo` into `--foo` for pflag-style flag.
44
+ args [i ] = "-" + arg
50
45
}
51
46
}
52
47
return pf .Parse (args )
0 commit comments