2023-09-27 09:04:44 +00:00
|
|
|
package process
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os/exec"
|
2024-10-24 12:03:12 +00:00
|
|
|
"sync"
|
2023-09-27 09:04:44 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type execOption func(context.Context, *exec.Cmd) error
|
|
|
|
|
|
|
|
func WithEnv(key, value string) execOption {
|
|
|
|
return func(ctx context.Context, c *exec.Cmd) error {
|
|
|
|
v := fmt.Sprintf("%s=%s", key, value)
|
|
|
|
c.Env = append(c.Env, v)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithEnvs(envs map[string]string) execOption {
|
|
|
|
return func(ctx context.Context, c *exec.Cmd) error {
|
|
|
|
for k, v := range envs {
|
|
|
|
err := WithEnv(k, v)(ctx, c)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithDir(dir string) execOption {
|
|
|
|
return func(_ context.Context, c *exec.Cmd) error {
|
|
|
|
c.Dir = dir
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithStdoutPipe(dst *io.ReadCloser) execOption {
|
|
|
|
return func(_ context.Context, c *exec.Cmd) error {
|
|
|
|
outPipe, err := c.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
*dst = outPipe
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-20 08:43:08 +00:00
|
|
|
func WithStdinReader(src io.Reader) execOption {
|
|
|
|
return func(_ context.Context, c *exec.Cmd) error {
|
|
|
|
c.Stdin = src
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithStderrWriter(dst io.Writer) execOption {
|
|
|
|
return func(_ context.Context, c *exec.Cmd) error {
|
|
|
|
c.Stderr = dst
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithStdoutWriter(dst io.Writer) execOption {
|
|
|
|
return func(_ context.Context, c *exec.Cmd) error {
|
|
|
|
c.Stdout = dst
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-24 12:03:12 +00:00
|
|
|
// safeWriter is a writer that is safe to use concurrently.
|
|
|
|
// It serializes writes to the underlying writer.
|
|
|
|
type safeWriter struct {
|
|
|
|
w io.Writer
|
|
|
|
m sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *safeWriter) Write(p []byte) (n int, err error) {
|
|
|
|
s.m.Lock()
|
|
|
|
defer s.m.Unlock()
|
|
|
|
return s.w.Write(p)
|
|
|
|
}
|
|
|
|
|
2023-09-27 09:04:44 +00:00
|
|
|
func WithCombinedOutput(buf *bytes.Buffer) execOption {
|
2024-10-24 12:03:12 +00:00
|
|
|
sw := &safeWriter{w: buf}
|
2023-09-27 09:04:44 +00:00
|
|
|
return func(_ context.Context, c *exec.Cmd) error {
|
2024-10-24 12:03:12 +00:00
|
|
|
c.Stdout = io.MultiWriter(sw, c.Stdout)
|
|
|
|
c.Stderr = io.MultiWriter(sw, c.Stderr)
|
2023-09-27 09:04:44 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|