Skip to content

Commit

Permalink
Rework pseudo tty feature
Browse files Browse the repository at this point in the history
  • Loading branch information
larrabee committed May 23, 2018
1 parent b655ee0 commit 03e10b9
Showing 1 changed file with 19 additions and 28 deletions.
47 changes: 19 additions & 28 deletions ewn/ewn.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@ import (
"syscall"
"time"
"github.com/kr/pty"
"fmt"
"golang.org/x/crypto/ssh/terminal"
)

// Retry contains command execution result
//Retry contains command execution result
type Retry struct {
ExitCode int
Output string
Expand All @@ -23,63 +21,56 @@ type Retry struct {
Retry int
}

// Message is output message structure
//Message is output message structure
type Message struct {
Args Args
Host string
Retries []Retry
GeneralError error
}

// Popen execute given command and return retry structure
//Popen execute given command and return retry structure
func Popen(command string, timeout time.Duration, tty bool) (result Retry, err error) {
var outB bytes.Buffer
var timer *time.Timer
result.StartTime = time.Now().UTC()
cmd := exec.Command("/bin/bash", "-c", command)

if isatty.IsTerminal(os.Stdout.Fd()) {
cmd.Stdout = io.MultiWriter(os.Stdout, &outB)
cmd.Stderr = io.MultiWriter(os.Stdout, &outB)
} else {
cmd.Stdout = &outB
cmd.Stderr = &outB
if timeout > time.Duration(0) {
timer = time.AfterFunc(timeout, func() {
cmd.Process.Kill()
})
}

if tty {
if isatty.IsTerminal(os.Stdout.Fd()) && !tty {
cmd.Stdout = io.MultiWriter(os.Stdout, &outB)
cmd.Stderr = io.MultiWriter(os.Stdout, &outB)
} else if isatty.IsTerminal(os.Stdout.Fd()) && tty {
ptmx, err := pty.Start(cmd)
if err != nil {
return result, err
}
defer ptmx.Close()

if err := pty.InheritSize(os.Stdin, ptmx); err != nil {
fmt.Printf("error resizing pty: %s", err)
}

oldState, err := terminal.MakeRaw(int(os.Stdin.Fd()))
go func() { io.Copy(io.MultiWriter(os.Stdout, &outB), ptmx) }()
} else if tty {
ptmx, err := pty.Start(cmd)
if err != nil {
return result, err
}
defer terminal.Restore(int(os.Stdin.Fd()), oldState)
go func() { io.Copy(cmd.Stdout, ptmx) }()
cmd.Stdout = io.MultiWriter(os.Stdout, &outB)
cmd.Stderr = io.MultiWriter(os.Stdout, &outB)
defer ptmx.Close()
go func() { io.Copy(&outB, ptmx) }()
}else {
cmd.Stdout = &outB
cmd.Stderr = &outB
}

if timeout > time.Duration(0) {
timer = time.AfterFunc(timeout, func() {
cmd.Process.Kill()
})
}
if !tty {
err = cmd.Start()
if err != nil {
return
}
}


err = cmd.Wait()

if timeout > time.Duration(0) {
Expand Down

0 comments on commit 03e10b9

Please sign in to comment.