summaryrefslogtreecommitdiff
path: root/internal/cli/cli.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/cli/cli.go')
-rw-r--r--internal/cli/cli.go245
1 files changed, 207 insertions, 38 deletions
diff --git a/internal/cli/cli.go b/internal/cli/cli.go
index dc1c2ba..9afdd9f 100644
--- a/internal/cli/cli.go
+++ b/internal/cli/cli.go
@@ -21,6 +21,7 @@ import (
"codeberg.org/snonux/foostore/internal/config"
"codeberg.org/snonux/foostore/internal/crypto"
"codeberg.org/snonux/foostore/internal/git"
+ "codeberg.org/snonux/foostore/internal/keepass"
"codeberg.org/snonux/foostore/internal/shell"
"codeberg.org/snonux/foostore/internal/store"
"codeberg.org/snonux/foostore/internal/version"
@@ -57,65 +58,95 @@ var SearchActions = map[string]store.Action{
// in without touching the dispatch or shell-loop logic. The current geheim
// backend is *store.Store, which satisfies Backend via the compile-time check
// in internal/backend/backend.go.
+//
+// g is declared as git.Gitter (interface) rather than *git.Git so that the
+// keepass backend can supply a git.NoOp when the kdbx file lives outside a git
+// repository. Dispatch code requires no nil checks; it always calls through the
+// interface regardless of whether real git operations or no-ops are performed.
+//
+// effectiveBackend is the resolved backend name (after applying the --backend
+// flag override on top of cfg.Backend). Guards such as cmdMigrateKDBX use
+// this field so they reflect the actual runtime backend, not just the config file value.
type CLI struct {
- cfg *config.Config
- st backend.Backend
- g *git.Git
- clip *clipboard.Clipboard
- sh *shell.Shell
- openKDBX func(string, string) (KDBXStore, error)
- now func() time.Time
- lastResult string // most recent search result description
+ cfg *config.Config
+ st backend.Backend
+ g git.Gitter // real *git.Git or *git.NoOp when kdbx is outside a repo
+ clip *clipboard.Clipboard
+ sh *shell.Shell
+ openKDBX func(string, string) (KDBXStore, error)
+ now func() time.Time
+ lastResult string // most recent search result description
+ effectiveBackend string // resolved backend: --backend flag > cfg.Backend > "geheim"
}
// New initialises all runtime dependencies (config, PIN, cipher, store, git,
-// clipboard, shell) and returns a ready-to-use CLI. cmd/foostore/main.go calls
-// New with a signal-cancellable context so that long-running operations (fzf,
-// external editors) are interrupted cleanly on SIGINT/SIGTERM.
-func New(ctx context.Context) (*CLI, error) {
- return newCLI(ctx)
+// clipboard, shell) and returns a ready-to-use CLI. argv (typically
+// os.Args[1:] after standard flags) is parsed for a --backend flag before
+// initialisation so the correct backend is instantiated from the start.
+// cmd/foostore/main.go calls New with a signal-cancellable context so that
+// long-running operations (fzf, external editors) are interrupted cleanly on
+// SIGINT/SIGTERM.
+func New(ctx context.Context, argv []string) (*CLI, error) {
+ backendName, _ := parseBackendFlag(argv)
+ return newCLI(ctx, backendName)
}
// Run dispatches argv (typically os.Args[1:]) to the appropriate handler or
-// enters the interactive shell loop. Returns an exit code suitable for
-// os.Exit. The caller is responsible for calling sh.Close() when done;
-// cmd/foostore/main.go does this via defer.
+// enters the interactive shell loop. The --backend flag is stripped from argv
+// before dispatch because it was already consumed by New. Returns an exit code
+// suitable for os.Exit. The caller is responsible for calling sh.Close() when
+// done; cmd/foostore/main.go does this via defer.
func (c *CLI) Run(ctx context.Context, argv []string) int {
defer c.sh.Close()
- return c.run(ctx, argv)
+ _, strippedArgv := parseBackendFlag(argv)
+ return c.run(ctx, strippedArgv)
}
-// newCLI initialises all dependencies: config, PIN, cipher, store, git,
-// clipboard, and interactive shell. Mirrors the Ruby CLI#initialize logic.
-func newCLI(ctx context.Context) (*CLI, error) {
- cfg := config.Load()
-
- pin, err := readPIN()
- if err != nil {
- return nil, fmt.Errorf("reading PIN: %w", err)
+// parseBackendFlag scans argv for a "--backend VALUE" pair and returns the
+// backend name and the remaining argv with that pair removed. Returns ("", argv)
+// when no --backend flag is present. The flag may appear anywhere in argv.
+//
+// Note: only the space-separated form "--backend VALUE" is supported.
+// The equals form "--backend=VALUE" is NOT parsed and will be silently ignored
+// (treated as an unknown argument that propagates to the command dispatcher).
+func parseBackendFlag(argv []string) (string, []string) {
+ for i, arg := range argv {
+ if arg == "--backend" && i+1 < len(argv) {
+ remaining := make([]string, 0, len(argv)-2)
+ remaining = append(remaining, argv[:i]...)
+ remaining = append(remaining, argv[i+2:]...)
+ return argv[i+1], remaining
+ }
}
+ return "", argv
+}
- ciph, err := crypto.NewCipher(cfg.KeyFile, cfg.KeyLength, pin, cfg.AddToIV)
- if err != nil {
- return nil, fmt.Errorf("initialising cipher: %w", err)
- }
+// newCLI initialises all dependencies: config, PIN/passphrase, cipher or
+// keepass credentials, store or keepass backend, git, clipboard, and
+// interactive shell. backendName overrides cfg.Backend when non-empty
+// (supplied from the --backend CLI flag); an empty string means "use
+// cfg.Backend". Mirrors the Ruby CLI#initialize logic.
+func newCLI(ctx context.Context, backendName string) (*CLI, error) {
+ cfg := config.Load()
- g := git.New(cfg.DataDir)
+ // Resolve the effective backend: flag overrides config, config defaults to "geheim".
+ effectiveBackend := resolveBackend(backendName, cfg.Backend)
- st, err := store.New(&cfg, ciph, g)
+ st, g, err := buildBackend(ctx, &cfg, effectiveBackend)
if err != nil {
- return nil, fmt.Errorf("initialising store: %w", err)
+ return nil, err
}
clip := clipboard.New(cfg.GnomeClipboardCmd, cfg.MacOSClipboardCmd)
c := &CLI{
- cfg: &cfg,
- st: st,
- g: g,
- clip: clip,
- openKDBX: OpenKDBXStore,
- now: time.Now,
+ cfg: &cfg,
+ st: st,
+ g: g,
+ clip: clip,
+ openKDBX: OpenKDBXStore,
+ now: time.Now,
+ effectiveBackend: effectiveBackend,
}
// Create the shell with a completion function that references the CLI.
@@ -130,6 +161,144 @@ func newCLI(ctx context.Context) (*CLI, error) {
return c, nil
}
+// resolveBackend returns the effective backend name given the flag override and
+// the config value. flag takes precedence; empty strings fall back to "geheim".
+func resolveBackend(flagValue, cfgValue string) string {
+ if flagValue != "" {
+ return flagValue
+ }
+ if cfgValue != "" {
+ return cfgValue
+ }
+ return "geheim"
+}
+
+// buildBackend constructs the Backend and its associated Gitter based on
+// effectiveBackend ("geheim" or "keepass"). Returns the Backend and git client
+// so the caller can wire them into the CLI struct.
+func buildBackend(ctx context.Context, cfg *config.Config, effectiveBackend string) (backend.Backend, git.Gitter, error) {
+ switch effectiveBackend {
+ case "keepass":
+ return buildKeepassBackend(ctx, cfg)
+ default:
+ return buildGeheimBackend(cfg)
+ }
+}
+
+// buildGeheimGit returns a *git.Git pointed at cfg.DataDir. The geheim data
+// directory is always a git repository (it is the store itself), so a real
+// git client is always appropriate here — unlike the keepass backend which
+// may live outside a repo and needs a NoOp fallback.
+func buildGeheimGit(cfg *config.Config) git.Gitter {
+ return git.New(cfg.DataDir)
+}
+
+// buildGeheimBackend initialises the original AES-encrypted geheim backend:
+// reads the PIN, builds the cipher, creates a *store.Store, and points git at
+// cfg.DataDir via buildGeheimGit.
+func buildGeheimBackend(cfg *config.Config) (backend.Backend, git.Gitter, error) {
+ pin, err := readPIN()
+ if err != nil {
+ return nil, nil, fmt.Errorf("reading PIN: %w", err)
+ }
+
+ ciph, err := crypto.NewCipher(cfg.KeyFile, cfg.KeyLength, pin, cfg.AddToIV)
+ if err != nil {
+ return nil, nil, fmt.Errorf("initialising cipher: %w", err)
+ }
+
+ g := buildGeheimGit(cfg)
+
+ st, err := store.New(cfg, ciph, g)
+ if err != nil {
+ return nil, nil, fmt.Errorf("initialising store: %w", err)
+ }
+
+ return st, g, nil
+}
+
+// buildKeepassBackend reads the KeePass passphrase and optional key-file bytes,
+// then instantiates a keepass.Backend. The git client is pointed at the
+// directory that contains the .kdbx file.
+//
+// If that directory is a git repository (detected via git rev-parse
+// --is-inside-work-tree), a real *git.Git is returned so that sync/status/
+// commit/reset operate normally against it. If the directory is not a git
+// repository, a *git.NoOp is returned instead — its methods print an
+// informational message ("kdbx file is not in a git repo; skipping") and return
+// nil, keeping the UX transparent without crashing.
+func buildKeepassBackend(ctx context.Context, cfg *config.Config) (backend.Backend, git.Gitter, error) {
+ passphrase, err := readKeepassPassphrase(cfg)
+ if err != nil {
+ return nil, nil, fmt.Errorf("reading keepass passphrase: %w", err)
+ }
+
+ keyFileData, err := readKeepassKeyFile(cfg)
+ if err != nil {
+ return nil, nil, fmt.Errorf("reading keepass key file: %w", err)
+ }
+
+ st, err := keepass.New(cfg, passphrase, keyFileData)
+ if err != nil {
+ return nil, nil, fmt.Errorf("initialising keepass backend: %w", err)
+ }
+
+ g := buildKeepassGit(cfg.KDBXPath)
+ return st, g, nil
+}
+
+// buildKeepassGit returns the appropriate Gitter for the directory containing
+// the kdbx file. When the directory is a git repository, a real *git.Git is
+// returned. Otherwise, a *git.NoOp is returned so that callers receive
+// informational messages rather than errors when running git commands.
+func buildKeepassGit(kdbxPath string) git.Gitter {
+ kdbxDir := filepath.Dir(kdbxPath)
+ if git.IsGitRepo(kdbxDir) {
+ return git.New(kdbxDir)
+ }
+ return git.NewNoOp()
+}
+
+// readKeepassPassphrase resolves the KeePass database passphrase using the
+// following priority: $PIN env var → cfg.KDBXPassFile → interactive prompt.
+// This mirrors the geheim readPIN() priority while accommodating the extra
+// KDBXPassFile option specific to the keepass backend.
+func readKeepassPassphrase(cfg *config.Config) (string, error) {
+ // 1. $PIN environment variable — same as geheim backend for symmetry.
+ if pin := os.Getenv("PIN"); pin != "" {
+ return pin, nil
+ }
+
+ // 2. KDBXPassFile — a file containing the password (trimmed of newlines).
+ if cfg.KDBXPassFile != "" {
+ pass, err := readPasswordFile(cfg.KDBXPassFile)
+ if err != nil {
+ return "", fmt.Errorf("reading KDBXPassFile: %w", err)
+ }
+ return pass, nil
+ }
+
+ // 3. Interactive prompt — same mechanism as geheim's PIN prompt.
+ pass, err := shell.ReadPassword("< KeePass passphrase: ")
+ if err != nil {
+ return "", fmt.Errorf("reading passphrase from terminal: %w", err)
+ }
+ return pass, nil
+}
+
+// readKeepassKeyFile reads the optional KeePass key-file bytes. Returns nil
+// when cfg.KDBXKeyFile is empty (password-only authentication).
+func readKeepassKeyFile(cfg *config.Config) ([]byte, error) {
+ if cfg.KDBXKeyFile == "" {
+ return nil, nil
+ }
+ data, err := os.ReadFile(cfg.KDBXKeyFile)
+ if err != nil {
+ return nil, fmt.Errorf("reading key file %q: %w", cfg.KDBXKeyFile, err)
+ }
+ return data, nil
+}
+
// readPIN returns the PIN string for encryption. If the $PIN environment
// variable is set, it is used directly (matching the Ruby ENV['PIN'] check).
// Otherwise the user is prompted with masked input via the shell package.