secret/internal/cli/cli.go
clawbot 6be4601763 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.
2026-02-19 23:53:35 -08:00

73 lines
1.8 KiB
Go

// Package cli implements the command-line interface for the secret application.
package cli
import (
"fmt"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/spf13/afero"
"github.com/spf13/cobra"
)
// Instance encapsulates all CLI functionality and state
type Instance struct {
fs afero.Fs
stateDir string
cmd *cobra.Command
}
// NewCLIInstance creates a new CLI instance with the real filesystem
func NewCLIInstance() (*Instance, error) {
fs := afero.NewOsFs()
stateDir, err := secret.DetermineStateDir("")
if err != nil {
return nil, fmt.Errorf("cannot determine state directory: %w", err)
}
return &Instance{
fs: fs,
stateDir: stateDir,
}, nil
}
// NewCLIInstanceWithFs creates a new CLI instance with the given filesystem (for testing)
func NewCLIInstanceWithFs(fs afero.Fs) (*Instance, error) {
stateDir, err := secret.DetermineStateDir("")
if err != nil {
return nil, fmt.Errorf("cannot determine state directory: %w", err)
}
return &Instance{
fs: fs,
stateDir: stateDir,
}, nil
}
// NewCLIInstanceWithStateDir creates a new CLI instance with custom state directory (for testing)
func NewCLIInstanceWithStateDir(fs afero.Fs, stateDir string) *Instance {
return &Instance{
fs: fs,
stateDir: stateDir,
}
}
// SetFilesystem sets the filesystem for this CLI instance (for testing)
func (cli *Instance) SetFilesystem(fs afero.Fs) {
cli.fs = fs
}
// SetStateDir sets the state directory for this CLI instance (for testing)
func (cli *Instance) SetStateDir(stateDir string) {
cli.stateDir = stateDir
}
// GetStateDir returns the state directory for this CLI instance
func (cli *Instance) GetStateDir() string {
return cli.stateDir
}
// Print outputs to the command's configured output writer
func (cli *Instance) Print(a ...interface{}) (n int, err error) {
return fmt.Fprint(cli.cmd.OutOrStdout(), a...)
}