refactor: return errors from NewCLIInstance instead of panicking

Change NewCLIInstance() and NewCLIInstanceWithFs() to return
(*Instance, error) instead of panicking on DetermineStateDir failure.

Callers in RunE contexts propagate the error. Callers in command
construction (for shell completion) use log.Fatalf. Test callers
use t.Fatalf.

Addresses review feedback on PR #18.
This commit is contained in:
clawbot
2026-02-19 23:53:29 -08:00
parent 36ece2fca7
commit 6be4601763
12 changed files with 156 additions and 42 deletions

View File

@@ -1,6 +1,7 @@
package cli
import (
"log"
"encoding/json"
"fmt"
"os"
@@ -96,7 +97,10 @@ func newUnlockerListCmd() *cobra.Command {
RunE: func(cmd *cobra.Command, _ []string) error {
jsonOutput, _ := cmd.Flags().GetBool("json")
cli := NewCLIInstance()
cli, err := NewCLIInstance()
if err != nil {
return fmt.Errorf("failed to initialize CLI: %w", err)
}
cli.cmd = cmd
return cli.UnlockersList(jsonOutput)
@@ -153,7 +157,10 @@ to access the same vault. This provides flexibility and backup access options.`,
Args: cobra.ExactArgs(1),
ValidArgs: strings.Split(supportedTypes, ", "),
RunE: func(cmd *cobra.Command, args []string) error {
cli := NewCLIInstance()
cli, err := NewCLIInstance()
if err != nil {
return fmt.Errorf("failed to initialize CLI: %w", err)
}
unlockerType := args[0]
// Validate unlocker type
@@ -186,7 +193,10 @@ to access the same vault. This provides flexibility and backup access options.`,
}
func newUnlockerRemoveCmd() *cobra.Command {
cli := NewCLIInstance()
cli, err := NewCLIInstance()
if err != nil {
log.Fatalf("failed to initialize CLI: %v", err)
}
cmd := &cobra.Command{
Use: "remove <unlocker-id>",
Aliases: []string{"rm"},
@@ -198,7 +208,10 @@ func newUnlockerRemoveCmd() *cobra.Command {
ValidArgsFunction: getUnlockerIDsCompletionFunc(cli.fs, cli.stateDir),
RunE: func(cmd *cobra.Command, args []string) error {
force, _ := cmd.Flags().GetBool("force")
cli := NewCLIInstance()
cli, err := NewCLIInstance()
if err != nil {
return fmt.Errorf("failed to initialize CLI: %w", err)
}
return cli.UnlockersRemove(args[0], force, cmd)
},
@@ -210,7 +223,10 @@ func newUnlockerRemoveCmd() *cobra.Command {
}
func newUnlockerSelectCmd() *cobra.Command {
cli := NewCLIInstance()
cli, err := NewCLIInstance()
if err != nil {
log.Fatalf("failed to initialize CLI: %v", err)
}
return &cobra.Command{
Use: "select <unlocker-id>",
@@ -218,7 +234,10 @@ func newUnlockerSelectCmd() *cobra.Command {
Args: cobra.ExactArgs(1),
ValidArgsFunction: getUnlockerIDsCompletionFunc(cli.fs, cli.stateDir),
RunE: func(_ *cobra.Command, args []string) error {
cli := NewCLIInstance()
cli, err := NewCLIInstance()
if err != nil {
return fmt.Errorf("failed to initialize CLI: %w", err)
}
return cli.UnlockerSelect(args[0])
},