2017-03-12 17:18:59 -03:00
|
|
|
package execext
|
|
|
|
|
|
|
|
import (
|
2017-04-12 20:32:56 -03:00
|
|
|
"context"
|
2017-04-22 15:46:29 -03:00
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/mvdan/sh/interp"
|
|
|
|
"github.com/mvdan/sh/syntax"
|
2017-03-12 17:18:59 -03:00
|
|
|
)
|
|
|
|
|
2017-04-24 10:25:38 -03:00
|
|
|
// RunCommandOptions is the options for the RunCommand func
|
2017-04-22 15:46:29 -03:00
|
|
|
type RunCommandOptions struct {
|
|
|
|
Context context.Context
|
|
|
|
Command string
|
|
|
|
Dir string
|
|
|
|
Env []string
|
|
|
|
Stdin io.Reader
|
|
|
|
Stdout io.Writer
|
|
|
|
Stderr io.Writer
|
|
|
|
}
|
|
|
|
|
2017-03-12 17:18:59 -03:00
|
|
|
var (
|
2017-04-22 15:46:29 -03:00
|
|
|
// ErrNilOptions is returned when a nil options is given
|
|
|
|
ErrNilOptions = errors.New("execext: nil options given")
|
2017-03-12 17:18:59 -03:00
|
|
|
)
|
|
|
|
|
2017-04-22 15:46:29 -03:00
|
|
|
// RunCommand runs a shell command
|
|
|
|
func RunCommand(opts *RunCommandOptions) error {
|
|
|
|
if opts == nil {
|
|
|
|
return ErrNilOptions
|
|
|
|
}
|
|
|
|
|
2017-05-17 16:16:03 -03:00
|
|
|
p, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), "")
|
2017-04-22 15:46:29 -03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-03-12 17:18:59 -03:00
|
|
|
|
2017-04-22 15:46:29 -03:00
|
|
|
r := interp.Runner{
|
|
|
|
Context: opts.Context,
|
|
|
|
File: p,
|
|
|
|
Dir: opts.Dir,
|
|
|
|
Env: opts.Env,
|
|
|
|
Stdin: opts.Stdin,
|
|
|
|
Stdout: opts.Stdout,
|
|
|
|
Stderr: opts.Stderr,
|
|
|
|
}
|
2017-07-08 15:08:44 -03:00
|
|
|
return r.Run()
|
2017-03-12 17:18:59 -03:00
|
|
|
}
|