Move the command tree into internal/cli (closes #8)
check / check (push) Successful in 1m40s
check / check (push) Successful in 1m40s
`cmd/simplexcalc/` now holds only `main.go`, whose body is one call, `os.Exit(cli.Main(version))`, as the Go style guide requires. The command tree and the `run` and `version` commands moved unchanged into `internal/cli`, with tests for `version` and for an unknown command. Output streams, exit statuses and the `-X main.version` build flag are as before. Disclosure: the comment in `execute` saying cobra has already printed the error is false, since the root command silences cobra's errors; it moved unchanged and is left for a follow-up. Model: opus-5-5
This commit was merged in pull request #9.
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
// Package cli is the simplexcalc command tree: the run and version
|
||||
// commands, and the exit status the program ends with.
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// appname is the name the program reports in its logs and its version.
|
||||
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(rootCmd(version))
|
||||
}
|
||||
|
||||
// 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(root.ErrOrStderr(), "exiting: "+err.Error())
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package cli_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"sneak.berlin/go/simplexcalc/internal/cli"
|
||||
)
|
||||
|
||||
func TestVersionPrintsVersion(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
root := cli.RootCmd("1.2.3")
|
||||
root.SetArgs([]string{"version"})
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
|
||||
status := cli.Execute(root)
|
||||
if status != 0 {
|
||||
t.Fatalf("status = %d, want 0; stderr: %q", status, stderr.String())
|
||||
}
|
||||
|
||||
want := "simplexcalc 1.2.3 " + runtime.GOOS + "/" + runtime.GOARCH + "\n"
|
||||
if stdout.String() != want {
|
||||
t.Errorf("stdout = %q, want %q", stdout.String(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownCommandFails(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
root := cli.RootCmd("1.2.3")
|
||||
root.SetArgs([]string{"frobnicate"})
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
|
||||
status := cli.Execute(root)
|
||||
if status == 0 {
|
||||
t.Fatal("status = 0, want non-zero")
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(stderr.String(), "exiting: ") {
|
||||
t.Errorf("stderr = %q, want the error after \"exiting: \"", stderr.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cli
|
||||
|
||||
// RootCmd and Execute are rootCmd and execute, exported for the external
|
||||
// test package, which builds the command tree itself so that it can
|
||||
// supply the arguments and read the output.
|
||||
//
|
||||
//nolint:gochecknoglobals // test seams, not mutable state.
|
||||
var (
|
||||
RootCmd = rootCmd
|
||||
Execute = execute
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// rootCmd builds the command tree. Configuration comes from the
|
||||
// environment (see internal/config), not from flags: the bot runs in a
|
||||
// container, where the environment is the interface, and one source of
|
||||
// truth means there is no precedence rule to get wrong.
|
||||
func rootCmd(version string) *cobra.Command {
|
||||
root := &cobra.Command{
|
||||
Use: appname,
|
||||
Short: appname + " — a SimpleX Chat bot that answers arithmetic",
|
||||
Long: appname + " is a SimpleX Chat bot that answers arithmetic.\n\n" +
|
||||
"It runs the simplex-chat command-line client, which must be on\n" +
|
||||
"PATH. Configuration is read from the environment and from an\n" +
|
||||
"optional .env file in the working directory. See README.md\n" +
|
||||
"for the full list of variables.",
|
||||
SilenceUsage: true,
|
||||
// Without this, cobra prints the error itself and main prints
|
||||
// it again.
|
||||
SilenceErrors: true,
|
||||
}
|
||||
|
||||
root.AddCommand(runCmd(version), versionCmd(version))
|
||||
|
||||
return root
|
||||
}
|
||||
|
||||
func versionCmd(version string) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "print the version and exit",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
_, err := fmt.Fprintf(cmd.OutOrStdout(), "%s %s %s/%s\n",
|
||||
appname, version, runtime.GOOS, runtime.GOARCH)
|
||||
if err != nil {
|
||||
return fmt.Errorf("writing version: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"syscall"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"sneak.berlin/go/simplexcalc/internal/bot"
|
||||
"sneak.berlin/go/simplexcalc/internal/config"
|
||||
"sneak.berlin/go/simplexcalc/internal/logger"
|
||||
)
|
||||
|
||||
func runCmd(version string) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "run",
|
||||
Short: "run the bot",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return run(cmd.Context(), version)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// run reads the configuration and runs the bot until SIGINT or SIGTERM,
|
||||
// or until it fails. A failure is the process's exit status, so a
|
||||
// supervisor restarts it.
|
||||
func run(ctx context.Context, version string) error {
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading configuration: %w", err)
|
||||
}
|
||||
|
||||
log := logger.New(os.Stdout, cfg.Debug)
|
||||
log.Info("starting",
|
||||
"appname", appname,
|
||||
"version", version,
|
||||
"arch", runtime.GOARCH,
|
||||
"data_dir", cfg.DataDir,
|
||||
)
|
||||
|
||||
ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
err = bot.Run(ctx, log, cfg.DataDir)
|
||||
if err != nil {
|
||||
log.Error("stopped", "error", err)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
log.Info("stopped")
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user