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
Raw Permalink Normal View History

2021-03-24 11:21:06 +00:00
package tui
2021-03-25 10:21:12 +00:00
import (
"crypto/rand"
"fmt"
"os"
"os/exec"
"path/filepath"
)
2021-03-24 11:21:06 +00:00
2021-03-25 10:21:12 +00:00
// Readline reads a line of input from the user.
func Readline(prompt string) string {
2021-03-24 11:21:06 +00:00
t.SetPrompt(prompt)
s, err := t.ReadLine()
must(err)
return s
}
2021-03-25 10:21:12 +00:00
// ReadPassword reads a line of input from the user, but doesn't echo to the
// screen.
func ReadPassword(prompt string) string {
2021-03-24 11:24:17 +00:00
s, err := t.ReadPassword(prompt)
must(err)
return s
}
2021-03-25 10:21:12 +00:00
// 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
}
2021-03-24 11:21:06 +00:00
2021-03-25 10:21:12 +00:00
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "emacs"
}
2021-03-24 11:21:06 +00:00
2021-03-25 10:21:12 +00:00
cmd := exec.Command(editor, path)
if err := cmd.Run(); err != nil {
return s, err
2021-03-24 11:21:06 +00:00
}
2021-03-25 10:21:12 +00:00
buf, err := os.ReadFile(path)
if err != nil {
return s, err
}
return string(buf), nil
2021-03-24 11:21:06 +00:00
}