grim/convey

0ec51ea78397
Parents 26b80367b6ed
Children 294418a850fe
add exec.RunWithStdin so we can pass stdin to our commands
  • +28 -3
    exec/exec.go
  • --- a/exec/exec.go Sun Oct 10 22:06:26 2021 -0500
    +++ b/exec/exec.go Sun Oct 10 22:07:00 2021 -0500
    @@ -20,6 +20,7 @@
    import (
    "bufio"
    "fmt"
    + "io"
    "os/exec"
    "sync"
    "time"
    @@ -38,7 +39,19 @@
    errCollector = newLogCollector(logger, log.ErrorLevel)
    )
    - return run(name, cmdv, timeout, &sync.WaitGroup{}, outCollector, errCollector)
    + return run(name, cmdv, nil, timeout, &sync.WaitGroup{}, outCollector, errCollector)
    +}
    +
    +// RunWithStdin runs the command specified in argv and passes stdin to the
    +// process's stdin. stderr and stdout are logged to a new log adapter.
    +func RunWithStdin(name string, cmdv []string, stdin io.Reader, timeout time.Duration) error {
    + var (
    + logger = logging.NewAdapter(name)
    + outCollector = newLogCollector(logger, log.InfoLevel)
    + errCollector = newLogCollector(logger, log.ErrorLevel)
    + )
    +
    + return run(name, cmdv, stdin, timeout, &sync.WaitGroup{}, outCollector, errCollector)
    }
    // RunOutput works just like Run but returns stdout and stderr instead of
    @@ -50,13 +63,13 @@
    errCollector = newStringCollector(wg)
    )
    - err := run(name, cmdv, timeout, wg, outCollector.handler, errCollector.handler)
    + err := run(name, cmdv, nil, timeout, wg, outCollector.handler, errCollector.handler)
    wg.Wait()
    return outCollector.output, errCollector.output, err
    }
    -func run(name string, cmdv []string, timeout time.Duration, wg *sync.WaitGroup, outHandler, errHandler collector) error {
    +func run(name string, cmdv []string, stdin io.Reader, timeout time.Duration, wg *sync.WaitGroup, outHandler, errHandler collector) error {
    logger := logging.NewAdapter(name)
    logger.Debugf("running command \"%v\"", cmdv)
    @@ -75,6 +88,18 @@
    return err
    }
    + if stdin != nil {
    + stdinPipe, err := cmd.StdinPipe()
    + if err != nil {
    + return err
    + }
    +
    + go func() {
    + defer stdinPipe.Close()
    + io.Copy(stdinPipe, stdin)
    + }()
    + }
    +
    // at this point we're committed to running the log handlers so increment
    // the waitgroup
    wg.Add(2)