Move the command tree into internal/cli (closes #8)
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:
2026-09-29 01:51:34 +02:00
parent 16649e0f2f
commit 09a5caa8ab
8 changed files with 116 additions and 21 deletions
+3 -2
View File
@@ -1,6 +1,6 @@
--- ---
title: Agent Guidance title: Agent Guidance
last_modified: 2026-09-26 last_modified: 2026-09-28
--- ---
This file is the single source of guidance for any automated agent This file is the single source of guidance for any automated agent
@@ -118,9 +118,10 @@ Do not weaken them.
## Layout ## Layout
``` ```
cmd/simplexcalc/ cobra command tree; main(), run and version cmd/simplexcalc/ main(), a single call into internal/cli
internal/bot/ startup, address setup, and the reply to a message internal/bot/ startup, address setup, and the reply to a message
internal/calc/ the arithmetic: go/parser and go/constant internal/calc/ the arithmetic: go/parser and go/constant
internal/cli/ cobra command tree: run and version
internal/config/ viper-backed configuration; the abort-on-garbage rule internal/config/ viper-backed configuration; the abort-on-garbage rule
internal/logger/ log/slog, JSON always internal/logger/ log/slog, JSON always
internal/simplex/ the simplex-chat child process and its WebSocket API internal/simplex/ the simplex-chat child process and its WebSocket API
+3 -11
View File
@@ -2,12 +2,10 @@
package main package main
import ( import (
"fmt"
"os" "os"
)
// appname is the name the program reports in its logs and its version. "sneak.berlin/go/simplexcalc/internal/cli"
const appname = "simplexcalc" )
// version is injected at build time with -ldflags "-X main.version=...". // version is injected at build time with -ldflags "-X main.version=...".
// The Dockerfile passes VERSION; a `go build` without it says "dev", // The Dockerfile passes VERSION; a `go build` without it says "dev",
@@ -16,11 +14,5 @@ const appname = "simplexcalc"
var version = "dev" var version = "dev"
func main() { func main() {
err := rootCmd().Execute() os.Exit(cli.Main(version))
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(os.Stderr, "exiting: "+err.Error())
os.Exit(1)
}
} }
+3
View File
@@ -27,6 +27,9 @@ with no deprecation warning.
# Completed Steps # Completed Steps
- 2026-09-28 Moved the command tree and the `run` and `version` commands
from `cmd/simplexcalc/` into `internal/cli`; `cmd/simplexcalc/main.go`
is now a single call to `cli.Main`
- 2026-09-26 Seeded from `go-template-repo` (renamed, its HTTP service - 2026-09-26 Seeded from `go-template-repo` (renamed, its HTTP service
removed) and built the bot: `internal/calc` for the arithmetic, removed) and built the bot: `internal/calc` for the arithmetic,
`internal/simplex` for the chat client process and its WebSocket API, `internal/simplex` for the chat client process and its WebSocket API,
+37
View File
@@ -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
}
+51
View File
@@ -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())
}
}
+11
View File
@@ -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
)
@@ -1,4 +1,4 @@
package main package cli
import ( import (
"fmt" "fmt"
@@ -11,7 +11,7 @@ import (
// environment (see internal/config), not from flags: the bot runs in a // environment (see internal/config), not from flags: the bot runs in a
// container, where the environment is the interface, and one source of // container, where the environment is the interface, and one source of
// truth means there is no precedence rule to get wrong. // truth means there is no precedence rule to get wrong.
func rootCmd() *cobra.Command { func rootCmd(version string) *cobra.Command {
root := &cobra.Command{ root := &cobra.Command{
Use: appname, Use: appname,
Short: appname + " — a SimpleX Chat bot that answers arithmetic", Short: appname + " — a SimpleX Chat bot that answers arithmetic",
@@ -26,12 +26,12 @@ func rootCmd() *cobra.Command {
SilenceErrors: true, SilenceErrors: true,
} }
root.AddCommand(runCmd(), versionCmd()) root.AddCommand(runCmd(version), versionCmd(version))
return root return root
} }
func versionCmd() *cobra.Command { func versionCmd(version string) *cobra.Command {
return &cobra.Command{ return &cobra.Command{
Use: "version", Use: "version",
Short: "print the version and exit", Short: "print the version and exit",
@@ -1,4 +1,4 @@
package main package cli
import ( import (
"context" "context"
@@ -14,13 +14,13 @@ import (
"sneak.berlin/go/simplexcalc/internal/logger" "sneak.berlin/go/simplexcalc/internal/logger"
) )
func runCmd() *cobra.Command { func runCmd(version string) *cobra.Command {
return &cobra.Command{ return &cobra.Command{
Use: "run", Use: "run",
Short: "run the bot", Short: "run the bot",
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error { RunE: func(cmd *cobra.Command, _ []string) error {
return run(cmd.Context()) return run(cmd.Context(), version)
}, },
} }
} }
@@ -28,7 +28,7 @@ func runCmd() *cobra.Command {
// run reads the configuration and runs the bot until SIGINT or SIGTERM, // 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 // or until it fails. A failure is the process's exit status, so a
// supervisor restarts it. // supervisor restarts it.
func run(ctx context.Context) error { func run(ctx context.Context, version string) error {
cfg, err := config.New() cfg, err := config.New()
if err != nil { if err != nil {
return fmt.Errorf("reading configuration: %w", err) return fmt.Errorf("reading configuration: %w", err)