keepass-cli/util/cli.go

83 lines
1.5 KiB
Go

/*
Copyright © 2024 Brian Buller <brian@bullercodeworks.com>
*/
package util
import (
"bufio"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"github.com/spf13/viper"
"golang.org/x/term"
)
func WriteToClipboard(val string) error {
cmd := exec.Command(viper.GetString("clipboard-command"), val)
return cmd.Run()
}
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
}