keepass-cli/util/cli.go
2024-05-15 13:42:38 -05:00

102 lines
1.9 KiB
Go

/*
Copyright © 2024 Brian Buller <brian@bullercodeworks.com>
*/
package util
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"syscall"
//"golang.design/x/clipboard"
"github.com/atotto/clipboard"
"golang.org/x/term"
)
func WriteToClipboard(val string) error {
clipboard.WriteAll(val)
return nil
}
/*
func WriteToClipboard(val string) error {
return WriteToClipboardWithTimeout(val, time.Second*5)
}
func WriteToClipboardWithTimeout(val string, timeout time.Duration) error {
ct := make(chan struct{})
go func() {
time.Sleep(timeout)
ct <- struct{}{}
}()
select {
case <-clipboard.Write(clipboard.FmtText, []byte(val)):
fmt.Println("Clipboard Changed")
case <-ct:
fmt.Println("Clipboard Cleared")
}
return nil
}
*/
func PromptUserForPassword(label string) (string, error) {
fmt.Println(label)
bytePass, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", err
}
return string(bytePass), nil
}
func PromptUser(text string) string {
var resp string
fmt.Println(text)
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
resp = scanner.Text()
}
return resp
}
func PromptUserOptTrimmed(text string, def string) string {
var resp string
if def == "" {
resp = strings.TrimSpace(PromptUser(text))
} else {
resp = strings.TrimSpace(PromptUser(fmt.Sprintf("%s [%s]:", text, def)))
if resp == "" {
resp = def
}
}
for resp == "" {
resp = strings.TrimSpace(PromptUser(text))
if resp == "" {
fmt.Println("Cannot be blank")
}
}
return resp
}
func PromptUserTrimmed(text string) string {
return PromptUserOptTrimmed(text, "")
}
func PromptUserInt(text string) int {
var resp string
var i int
for resp == "" {
resp = strings.TrimSpace(PromptUser(text))
if resp == "" {
fmt.Println("Cannot be blank")
}
var err error
i, err = strconv.Atoi(resp)
if err != nil {
fmt.Println("Must be a number")
resp = ""
}
}
return i
}