Skip to content

Commit 85fc546

Browse files
authored
Fix: -h / --help now show usage text for subcommands (#1195)
Previously we special cased --help only for the first level of subcommands. However, this broke for example if you did "src snapshot upload --help". So instead we normalize our command line arguments so that if a user does "--help" we see "-help". We can then rely on go's stdlib flag parser to do the right thing w.r.t. sub commands/etc. Test Plan: ran with --help in a few different places and observed good behaviour.
1 parent 6dfcb47 commit 85fc546

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

cmd/src/cmd.go

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"fmt"
66
"log"
77
"os"
8-
"slices"
98

109
"github.com/sourcegraph/src-cli/internal/cmderrors"
1110
)
@@ -86,16 +85,6 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args []
8685
log.Fatal("reading config: ", err)
8786
}
8887

89-
// Print help to stdout if requested
90-
if slices.IndexFunc(args, func(s string) bool {
91-
return s == "--help"
92-
}) >= 0 {
93-
cmd.flagSet.SetOutput(os.Stdout)
94-
flag.CommandLine.SetOutput(os.Stdout)
95-
cmd.flagSet.Usage()
96-
os.Exit(0)
97-
}
98-
9988
// Parse subcommand flags.
10089
args := flagSet.Args()[1:]
10190
if err := cmd.flagSet.Parse(args); err != nil {

cmd/src/main.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"net/url"
1010
"os"
1111
"path/filepath"
12+
"slices"
1213
"strings"
1314

1415
"github.com/sourcegraph/sourcegraph/lib/errors"
@@ -89,7 +90,21 @@ func main() {
8990
log.SetFlags(0)
9091
log.SetPrefix("")
9192

92-
commands.run(flag.CommandLine, "src", usageText, os.Args[1:])
93+
commands.run(flag.CommandLine, "src", usageText, normalizeDashHelp(os.Args[1:]))
94+
}
95+
96+
// normalizeDashHelp converts --help to -help since Go's flag parser only supports single dash.
97+
func normalizeDashHelp(args []string) []string {
98+
args = slices.Clone(args)
99+
for i, arg := range args {
100+
if arg == "--" {
101+
break
102+
}
103+
if arg == "--help" {
104+
args[i] = "-help"
105+
}
106+
}
107+
return args
93108
}
94109

95110
var cfg *config

0 commit comments

Comments
 (0)