Try to avoid panicking in PosixParser if there's no /dev/tty.

When using go-prompt before /dev/ is populated, it will panic() from
NewStandardInputParser() because /dev/ isn't populated yet.

This will use stdin (fd 0) as a fallback if /dev/tty doesn't exist.

Furthermore GetWinSize() will return the default console size if the
IOCTL call fails. This can happen if the default stdin is not a
terminal, but a pipe as fixed in commit 846777c and described in
issue #88.
This commit is contained in:
Anders Brander 2020-08-14 15:37:59 +02:00
parent 8717360802
commit aba8e36cff
No known key found for this signature in database
GPG Key ID: B5BF53208B33C65D

View File

@ -3,6 +3,7 @@
package prompt
import (
"os"
"syscall"
"github.com/c-bata/go-prompt/internal/term"
@ -54,7 +55,12 @@ func (t *PosixParser) Read() ([]byte, error) {
func (t *PosixParser) GetWinSize() *WinSize {
ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
if err != nil {
panic(err)
// If this errors, we simply return the default window size as
// it's our best guess.
return &WinSize{
Row: 25,
Col: 80,
}
}
return &WinSize{
Row: ws.Row,
@ -67,7 +73,9 @@ var _ ConsoleParser = &PosixParser{}
// NewStandardInputParser returns ConsoleParser object to read from stdin.
func NewStandardInputParser() *PosixParser {
in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
if err != nil {
if os.IsNotExist(err) {
in = syscall.Stdin
} else if err != nil {
panic(err)
}