Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cmd/specter/commands/root.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package commands

import (
"encoding/json"
"fmt"
"io"

"github.com/ghostwright/specter/internal/tui"
"github.com/ghostwright/specter/pkg/version"
Expand Down Expand Up @@ -42,3 +44,14 @@ func init() {
func Execute() error {
return rootCmd.Execute()
}

func WriteError(w io.Writer, err error) {
if jsonOutput {
_ = json.NewEncoder(w).Encode(map[string]string{
"error": err.Error(),
})
return
}

fmt.Fprintln(w, err)
}
63 changes: 63 additions & 0 deletions cmd/specter/commands/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package commands

import (
"bytes"
"encoding/json"
"errors"
"testing"

"github.com/spf13/cobra"
)

func TestRootCommandErrorOutputJSON(t *testing.T) {
err := executeFailingRootCommand(t, "--json", "fail")

var buf bytes.Buffer
WriteError(&buf, err)

var got map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("error output is not valid JSON: %v", err)
}
if got["error"] != "boom" {
t.Fatalf("error = %q, want %q", got["error"], "boom")
}
}

func TestRootCommandErrorOutputPlainText(t *testing.T) {
err := executeFailingRootCommand(t, "fail")

var buf bytes.Buffer
WriteError(&buf, err)

if got, want := buf.String(), "boom\n"; got != want {
t.Fatalf("error output = %q, want %q", got, want)
}
}

func executeFailingRootCommand(t *testing.T, args ...string) error {
t.Helper()

oldJSONOutput := jsonOutput
failCmd := &cobra.Command{
Use: "fail",
RunE: func(cmd *cobra.Command, args []string) error {
return errors.New("boom")
},
}

rootCmd.AddCommand(failCmd)
rootCmd.SetArgs(args)
t.Cleanup(func() {
rootCmd.RemoveCommand(failCmd)
rootCmd.SetArgs(nil)
jsonOutput = oldJSONOutput
})

err := Execute()
if err == nil {
t.Fatal("Execute() error = nil, want error")
}

return err
}
2 changes: 1 addition & 1 deletion cmd/specter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func main() {
runDashboard()
} else {
if err := commands.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
commands.WriteError(os.Stderr, err)
os.Exit(1)
}
}
Expand Down