From aba8e36cffba678ff22d58e39ea9bed105d9f90c Mon Sep 17 00:00:00 2001 From: Anders Brander Date: Fri, 14 Aug 2020 15:37:59 +0200 Subject: [PATCH] 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. --- input_posix.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/input_posix.go b/input_posix.go index f1043031..46004ee0 100644 --- a/input_posix.go +++ b/input_posix.go @@ -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) }