This repository has been archived on 2021-03-25. You can view files and clone it, but cannot push or open issues/pull-requests.
tui/input.go

55 lines
1.0 KiB
Go

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
}