add stdin remapping support

This commit is contained in:
Ryan Hileman 2015-12-22 21:39:23 -08:00
parent 76dfcd2e50
commit 05d3fbcc2a
3 changed files with 17 additions and 6 deletions

View File

@ -4,7 +4,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"os"
"golang.org/x/crypto/ssh/terminal" "golang.org/x/crypto/ssh/terminal"
) )
@ -330,7 +329,7 @@ func (o *Operation) Password(prompt string) ([]byte, error) {
o.t.EnterRawMode() o.t.EnterRawMode()
defer o.t.ExitRawMode() defer o.t.ExitRawMode()
b, err := terminal.ReadPassword(int(os.Stdin.Fd())) b, err := terminal.ReadPassword(int(o.cfg.Stdin.Fd()))
fmt.Fprint(w, "\r\n") fmt.Fprint(w, "\r\n")
return b, err return b, err
} }

View File

@ -1,6 +1,9 @@
package readline package readline
import "io" import (
"io"
"os"
)
type Instance struct { type Instance struct {
Config *Config Config *Config
@ -8,6 +11,11 @@ type Instance struct {
Operation *Operation Operation *Operation
} }
type FdReader interface {
io.Reader
Fd() uintptr
}
type Config struct { type Config struct {
// prompt supports ANSI escape sequence, so we can color some characters even in windows // prompt supports ANSI escape sequence, so we can color some characters even in windows
Prompt string Prompt string
@ -30,6 +38,7 @@ type Config struct {
InterruptPrompt string InterruptPrompt string
EOFPrompt string EOFPrompt string
Stdin FdReader
Stdout io.Writer Stdout io.Writer
Stderr io.Writer Stderr io.Writer
@ -46,6 +55,9 @@ func (c *Config) Init() error {
return nil return nil
} }
c.inited = true c.inited = true
if c.Stdin == nil {
c.Stdin = os.Stdin
}
if c.Stdout == nil { if c.Stdout == nil {
c.Stdout = Stdout c.Stdout = Stdout
} }

View File

@ -36,7 +36,7 @@ func NewTerminal(cfg *Config) (*Terminal, error) {
} }
func (t *Terminal) EnterRawMode() (err error) { func (t *Terminal) EnterRawMode() (err error) {
t.state, err = MakeRaw(StdinFd) t.state, err = MakeRaw(int(t.cfg.Stdin.Fd()))
return err return err
} }
@ -44,7 +44,7 @@ func (t *Terminal) ExitRawMode() (err error) {
if t.state == nil { if t.state == nil {
return return
} }
err = Restore(StdinFd, t.state) err = Restore(int(t.cfg.Stdin.Fd()), t.state)
if err == nil { if err == nil {
t.state = nil t.state = nil
} }
@ -91,7 +91,7 @@ func (t *Terminal) ioloop() {
expectNextChar bool expectNextChar bool
) )
buf := bufio.NewReader(Stdin) buf := bufio.NewReader(t.cfg.Stdin)
for { for {
if !expectNextChar { if !expectNextChar {
atomic.StoreInt32(&t.isReading, 0) atomic.StoreInt32(&t.isReading, 0)