2020-08-31 09:22:09 +00:00
|
|
|
package input
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"syscall"
|
|
|
|
|
2021-02-10 08:53:01 +00:00
|
|
|
"golang.org/x/term"
|
2020-08-31 09:22:09 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Terminal is a terminal used for input. If `nil`, stdin is used.
|
2021-02-10 08:53:01 +00:00
|
|
|
var Terminal *term.Terminal
|
|
|
|
|
|
|
|
// ReadWriter combiner reader and writer.
|
|
|
|
type ReadWriter struct {
|
|
|
|
io.Reader
|
|
|
|
io.Writer
|
|
|
|
}
|
2020-08-31 09:22:09 +00:00
|
|
|
|
|
|
|
// ReadLine reads line from the input without trailing '\n'
|
2021-02-10 08:53:01 +00:00
|
|
|
func ReadLine(prompt string) (string, error) {
|
|
|
|
trm := Terminal
|
|
|
|
if trm == nil {
|
|
|
|
s, err := term.MakeRaw(syscall.Stdin)
|
2020-08-31 09:22:09 +00:00
|
|
|
if err != nil {
|
2021-02-10 08:53:01 +00:00
|
|
|
panic(err)
|
2020-08-31 09:22:09 +00:00
|
|
|
}
|
2021-02-10 08:53:01 +00:00
|
|
|
defer term.Restore(syscall.Stdin, s)
|
|
|
|
trm = term.NewTerminal(ReadWriter{
|
|
|
|
Reader: os.Stdin,
|
|
|
|
Writer: os.Stdout,
|
|
|
|
}, "")
|
2020-08-31 09:22:09 +00:00
|
|
|
}
|
2021-02-10 08:53:01 +00:00
|
|
|
return readLine(trm, prompt)
|
2020-08-31 09:22:09 +00:00
|
|
|
}
|
|
|
|
|
2021-02-10 08:53:01 +00:00
|
|
|
func readLine(trm *term.Terminal, prompt string) (string, error) {
|
|
|
|
_, err := trm.Write([]byte(prompt))
|
2020-08-31 09:22:09 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2021-02-10 08:53:01 +00:00
|
|
|
return trm.ReadLine()
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReadPassword reads user password with prompt.
|
|
|
|
func ReadPassword(prompt string) (string, error) {
|
|
|
|
trm := Terminal
|
|
|
|
if trm == nil {
|
|
|
|
s, err := term.MakeRaw(syscall.Stdin)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
defer term.Restore(syscall.Stdin, s)
|
|
|
|
trm = term.NewTerminal(ReadWriter{os.Stdin, os.Stdout}, prompt)
|
|
|
|
}
|
|
|
|
return trm.ReadPassword(prompt)
|
2020-08-31 09:22:09 +00:00
|
|
|
}
|