Skip to content

Commit

Permalink
Consistently redirect usage examples to stdout (#1105)
Browse files Browse the repository at this point in the history
* direct help texts to stdout

* set usage output for subcommands
  • Loading branch information
tinvaan authored Aug 31, 2024
1 parent 919e777 commit 95b5854
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions cmd/src/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"os"
"slices"
"strings"

"github.com/sourcegraph/sourcegraph/lib/errors"
Expand Down Expand Up @@ -56,6 +57,7 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args []

// Print usage if the command is "help".
if flagSet.Arg(0) == "help" || flagSet.NArg() == 0 {
flagSet.SetOutput(os.Stdout)
flagSet.Usage()
os.Exit(0)
}
Expand Down Expand Up @@ -93,10 +95,22 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args []
panic(fmt.Sprintf("all registered commands should use flag.ExitOnError: error: %s", err))
}

// Show usage examples for subcommand
if len(args) == 0 || slices.IndexFunc(args, func(s string) bool {
return s == "help" || s == "--help"
}) >= 0 {
cmd.flagSet.SetOutput(os.Stdout)
flag.CommandLine.SetOutput(os.Stdout)
cmd.flagSet.Usage()
os.Exit(0)
}

// Execute the subcommand.
if err := cmd.handler(flagSet.Args()[1:]); err != nil {
if _, ok := err.(*cmderrors.UsageError); ok {
log.Printf("error: %s\n\n", err)
cmd.flagSet.SetOutput(os.Stderr)
flag.CommandLine.SetOutput(os.Stderr)
cmd.flagSet.Usage()
os.Exit(2)
}
Expand Down

0 comments on commit 95b5854

Please sign in to comment.