toolbox/tui/input.go

55 lines
1.0 KiB
Go
Raw Normal View History

2021-03-31 08:27:54 +00:00
package tui
import (
"crypto/rand"
"fmt"
"os"
"os/exec"
"path/filepath"
)
// Readline reads a line of input from the user.
func Readline(prompt string) string {
t.SetPrompt(prompt)
s, err := t.ReadLine()
must(err)
return s
}
// ReadPassword reads a line of input from the user, but doesn't echo to the
// screen.
func ReadPassword(prompt string) string {
s, err := t.ReadPassword(prompt)
must(err)
return s
}
// Edit the string s using the editor defined by the environment variable
// EDITOR.
func EditInEditor(s string) (string, error) {
buf := make([]byte, 16)
rand.Read(buf)
path := filepath.Join(os.TempDir(), fmt.Sprintf("tui.%x", buf))
defer os.RemoveAll(path)
if err := os.WriteFile(path, []byte(s), 0600); err != nil {
return s, err
}
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "emacs"
}
cmd := exec.Command(editor, path)
if err := cmd.Run(); err != nil {
return s, err
}
buf, err := os.ReadFile(path)
if err != nil {
return s, err
}
return string(buf), nil
}