Skip to content

Commit

Permalink
feat: add stdin support into the Run methods
Browse files Browse the repository at this point in the history
Luks encryption is passing encryption keys using stdin.

Signed-off-by: Artem Chernyshev <artem.0xD2@gmail.com>
  • Loading branch information
Unix4ever authored and talos-bot committed Feb 16, 2021
1 parent c5c8f1c commit 333ccf1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
25 changes: 24 additions & 1 deletion pkg/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,28 @@ package cmd
import (
"context"
"fmt"
"io"
"os/exec"

"github.com/armon/circbuf"

"github.com/talos-systems/go-cmd/pkg/cmd/proc/reaper"
)

type stdinCtxKey string

// MaxStderrLen is maximum length of stderr output captured for error message.
const MaxStderrLen = 4096
const (
MaxStderrLen = 4096

stdin stdinCtxKey = "stdin"
)

// WithStdin creates a new context from the existing context
// and sets stdin value.
func WithStdin(ctx context.Context, stdinData io.Reader) context.Context {
return context.WithValue(ctx, stdin, stdinData)
}

// Run executes a command.
func Run(name string, args ...string) (string, error) {
Expand All @@ -37,6 +50,16 @@ func RunContext(ctx context.Context, name string, args ...string) (string, error
return stdout.String(), err
}

stdin := ctx.Value(stdin)
if stdin != nil {
var ok bool

cmd.Stdin, ok = stdin.(io.Reader)
if !ok {
return "", fmt.Errorf("failed to read stdin object from the context")
}
}

cmd.Stdout = stdout
cmd.Stderr = stderr

Expand Down
6 changes: 6 additions & 0 deletions pkg/cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
package cmd_test

import (
"context"
"fmt"
"strings"
"testing"

"github.com/stretchr/testify/suite"
Expand Down Expand Up @@ -109,6 +111,10 @@ func (suite *CmdSuite) TestRun() {
suite.Assert().NoError(err)
}
}

stdout, err := cmd.RunContext(cmd.WithStdin(context.Background(), strings.NewReader("hello")), "xargs", "echo")
suite.Assert().NoError(err)
suite.Assert().Equal(stdout, "hello\n")
}

func TestCmdSuite(t *testing.T) {
Expand Down

0 comments on commit 333ccf1

Please sign in to comment.