Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added 'SeparatedOutput' command to capture stdout and stderr separately #41

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 46 additions & 0 deletions cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package goph

import (
"bytes"
"context"
"fmt"
"github.com/pkg/errors"
Expand Down Expand Up @@ -41,6 +42,22 @@ func (c *Cmd) CombinedOutput() ([]byte, error) {
})
}

// SeparatedOutput runs cmd on the remote host and returns its stdout and stderr.
func (c *Cmd) SeparatedOutput() ([]byte, []byte, error) {
var stdout_buff, stderr_buff bytes.Buffer
c.Session.Stdout = &stdout_buff
c.Session.Stderr = &stderr_buff

if err := c.init(); err != nil {
return nil, nil, errors.Wrap(err, "cmd init")
}

return c.runWithContextAndErr(func() ([]byte, []byte, error) {
err := c.Session.Run(c.String())
return stdout_buff.Bytes(), stderr_buff.Bytes(), err
})
}

// Output runs cmd on the remote host and returns its stdout.
func (c *Cmd) Output() ([]byte, error) {
if err := c.init(); err != nil {
Expand Down Expand Up @@ -93,6 +110,13 @@ func (c *Cmd) init() (err error) {
return nil
}

// Command with context output.
type ctxCmdOutputAndErr struct {
stdout []byte
stderr []byte
err error
}

// Command with context output.
type ctxCmdOutput struct {
output []byte
Expand All @@ -119,3 +143,25 @@ func (c *Cmd) runWithContext(callback func() ([]byte, error)) ([]byte, error) {
return result.output, result.err
}
}

// Executes the given callback within session. Sends SIGINT when the context is canceled.
func (c *Cmd) runWithContextAndErr(callback func() ([]byte, []byte, error)) ([]byte, []byte, error) {
outputChan := make(chan ctxCmdOutputAndErr)
go func() {
stdout, stderr, err := callback()
outputChan <- ctxCmdOutputAndErr{
stdout: stdout,
stderr: stderr,
err: err,
}
}()

select {
case <-c.Context.Done():
_ = c.Session.Signal(ssh.SIGINT)

return nil, nil, c.Context.Err()
case result := <-outputChan:
return result.stdout, result.stderr, result.err
}
}