2024-07-30 14:43:54 -04:00
|
|
|
// Package prompt implements prompt functions for runes and strings.
|
2024-06-28 14:26:30 -04:00
|
|
|
package prompt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2024-06-30 18:03:43 -04:00
|
|
|
"log"
|
2024-06-28 14:26:30 -04:00
|
|
|
"os"
|
|
|
|
|
2024-07-27 19:42:23 -04:00
|
|
|
"github.com/charmbracelet/huh"
|
2024-06-28 14:26:30 -04:00
|
|
|
"golang.org/x/term"
|
|
|
|
)
|
|
|
|
|
|
|
|
// TODO: use charm stuff for this
|
|
|
|
|
|
|
|
func YesNo(prompt string) bool {
|
|
|
|
return AskRune(prompt, "y/n") == 'y'
|
|
|
|
}
|
|
|
|
|
|
|
|
func AskRune(prompt, options string) byte {
|
|
|
|
// switch stdin into 'raw' mode
|
|
|
|
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
|
|
|
|
if err != nil {
|
2024-06-30 18:03:43 -04:00
|
|
|
log.Fatal(err)
|
2024-06-28 14:26:30 -04:00
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err := term.Restore(int(os.Stdin.Fd()), oldState); err != nil {
|
2024-06-30 18:03:43 -04:00
|
|
|
log.Fatal(err)
|
2024-06-28 14:26:30 -04:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-07-30 14:43:54 -04:00
|
|
|
fmt.Fprintf(os.Stdout, "%s [%s]: ", prompt, options)
|
2024-06-28 14:26:30 -04:00
|
|
|
|
|
|
|
// read one byte from stdin
|
2024-07-30 14:43:54 -04:00
|
|
|
one := make([]byte, 1)
|
|
|
|
_, err = os.Stdin.Read(one)
|
2024-06-28 14:26:30 -04:00
|
|
|
if err != nil {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2024-07-30 14:43:54 -04:00
|
|
|
return bytes.ToLower(one)[0]
|
2024-06-28 14:26:30 -04:00
|
|
|
}
|
2024-07-27 19:42:23 -04:00
|
|
|
|
|
|
|
func NewPath(path string) (string, bool) {
|
|
|
|
for {
|
|
|
|
answer := AskRune(fmt.Sprintf("file %s exists, overwrite, rename, or cancel?", path), "o/r/c")
|
|
|
|
switch answer {
|
|
|
|
case 'o', 'O':
|
|
|
|
return path, false
|
|
|
|
case 'r', 'R':
|
|
|
|
if err := huh.NewInput().
|
|
|
|
Title("input a new filename").
|
|
|
|
Value(&path).
|
|
|
|
Run(); err != nil {
|
|
|
|
return path, false
|
|
|
|
}
|
|
|
|
if _, e := os.Stat(path); e != nil {
|
|
|
|
return path, false
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return path, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|