cli.Main no longer calls SetOut or SetErr. SetOut also moved the usage and an unknown help topic, which cobra writes to stderr, onto stdout. execute now takes the command tree, so the tests build it, set its arguments and output streams, and run it; the exit line goes to the command's error stream, which outside a test is stderr as before. Model: opus-5-5
This commit is contained in:
+11
-12
@@ -4,8 +4,8 @@ package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// appname is the name the program reports in its logs and its version.
|
||||
@@ -13,23 +13,22 @@ const appname = "simplexcalc"
|
||||
|
||||
// Main runs the command named on the command line and returns the exit
|
||||
// status for main to pass to os.Exit.
|
||||
//
|
||||
// It leaves cobra's output streams at their defaults. cobra writes the
|
||||
// usage and an unknown help topic to stderr, but SetOut moves them onto
|
||||
// the stream it is given.
|
||||
func Main(version string) int {
|
||||
return execute(version, os.Args[1:], os.Stdout, os.Stderr)
|
||||
return execute(rootCmd(version))
|
||||
}
|
||||
|
||||
// execute is Main with the arguments and the output passed in, so that
|
||||
// a test can supply them.
|
||||
func execute(version string, args []string, stdout, stderr io.Writer) int {
|
||||
root := rootCmd(version)
|
||||
root.SetArgs(args)
|
||||
root.SetOut(stdout)
|
||||
root.SetErr(stderr)
|
||||
|
||||
// execute runs root and returns the exit status. It takes the command
|
||||
// so that a test can set its arguments and output streams first.
|
||||
func execute(root *cobra.Command) int {
|
||||
err := root.Execute()
|
||||
if err != nil {
|
||||
// cobra has already printed the error; this only sets the exit
|
||||
// status, which is what a supervisor and a shell script read.
|
||||
_, _ = fmt.Fprintln(stderr, "exiting: "+err.Error())
|
||||
_, _ = fmt.Fprintln(root.ErrOrStderr(), "exiting: "+err.Error())
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user