Skip to content

Commit 1435c1a

Browse files
committed
sniffarg: unconditionally convert to double-dash args
The old code was being dumb while trying to be too clever - it tried to do only the minimal amount of rewriting, but really should've just rewritten all the flags to `--format` instead.
1 parent 0fa914d commit 1435c1a

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

pkg/testutils/sniffarg/sniffarg.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ package sniffarg
77

88
import (
99
"os"
10-
"regexp"
10+
"strings"
1111

1212
"github.com/cockroachdb/errors"
1313
"github.com/spf13/pflag"
@@ -38,9 +38,15 @@ func Do(args []string, name string, out interface{}) error {
3838
pf.ParseErrorsWhitelist = pflag.ParseErrorsWhitelist{UnknownFlags: true}
3939
args = append([]string(nil), args...)
4040
for i, arg := range args {
41-
re := regexp.MustCompile(`^(-{1,2})` + regexp.QuoteMeta(name) + `(=|$)`)
42-
if matches := re.FindStringSubmatch(arg); len(matches) > 0 && len(matches[1]) == 1 {
43-
// Transform `-foo` into `--foo` for pflag-style flag.
41+
if !strings.HasPrefix(arg, "-") {
42+
continue
43+
}
44+
45+
// Single-dash flags are not supported by pflag. It will parse them as
46+
// shorthands. In particular, anything containing `h` (like `-show-logs`)
47+
// will trigger the "help" flag and causes an error.
48+
// Transform single-dash args into double-dash args.
49+
if !strings.HasPrefix(arg, "--") {
4450
args[i] = "-" + arg
4551
}
4652
}

pkg/testutils/sniffarg/sniffarg_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,18 @@ func TestDo(t *testing.T) {
4646
assert.Zero(t, notFound)
4747

4848
}
49+
50+
func TestDoBoolUnknownSingleDashFlag(t *testing.T) {
51+
defer leaktest.AfterTest(t)()
52+
53+
// This is a regression test: in the past, `-show-logs` would trigger pflag to
54+
// output the help and return an error, due to the `-h` shorthand in
55+
// `-show-logs`.
56+
57+
args := []string{
58+
"-show-logs", "-rewrite",
59+
}
60+
var rewrite bool
61+
require.NoError(t, Do(args, "rewrite", &rewrite))
62+
require.True(t, rewrite)
63+
}

0 commit comments

Comments
 (0)