From a7b3220cb12a2a8a31699134661f5c66363643c7 Mon Sep 17 00:00:00 2001 From: Igor Ignatyev Date: Thu, 22 May 2025 17:31:06 +0300 Subject: [PATCH] #18: Replace error message of missing credential item by user prompt if tty available --- plugin.go | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/plugin.go b/plugin.go index da475d9..0a5511d 100644 --- a/plugin.go +++ b/plugin.go @@ -97,12 +97,36 @@ func processGetByKey(value any, opts GetKeyValueProcessorOptions, ctx action.Val } v, err := k.GetForKey(opts.Fields.Key) - if err != nil { - return value, buildNotFoundError(opts.Fields.Key, errTplNotFoundKey, err) + if err == nil { + return v.Value, nil } - return v.Value, nil + streams := ctx.Input.Streams() + isTerminal := streams != nil && streams.In().IsTerminal() + if errors.Is(err, ErrNotFound) && isTerminal { + item := KeyValueItem{Key: opts.Fields.Key} + err = RequestKeyValueFromTty(&item) + if err != nil { + return value, err + } + err = k.AddItem(item) + if err != nil { + return value, err + } + + // Ensure keyring storage will be accessible after save. + defer k.ResetStorage() + err = k.Save() + if err != nil { + return value, err + } + launchr.Term().Info().Printfln("Key %q has been added to keyring", item.Key) + + return item.Value, nil + } + + return value, buildNotFoundError(opts.Fields.Key, errTplNotFoundKey, err) } // DiscoverActions implements [launchr.ActionDiscoveryPlugin] interface. @@ -280,7 +304,9 @@ func RequestKeyValueFromTty(item *KeyValueItem) error { func keyValueFromTty(item *KeyValueItem, in *os.File, out *os.File) error { reader := bufio.NewReader(in) + showKeyHelp := true if item.Key == "" { + showKeyHelp = false fmt.Fprint(out, "Key: ") username, err := reader.ReadString('\n') if err != nil { @@ -290,7 +316,12 @@ func keyValueFromTty(item *KeyValueItem, in *os.File, out *os.File) error { } if item.Value == "" { - fmt.Fprint(out, "Value: ") + if showKeyHelp { + fmt.Fprint(out, fmt.Sprintf("Enter value of '%s':", item.Key)) + } else { + fmt.Fprint(out, "Value: ") + } + byteValue, err := term.ReadPassword(int(in.Fd())) fmt.Fprint(out, "\n") if err != nil {