1
0
mirror of https://github.com/go-task/task.git synced 2025-01-14 04:35:50 +02:00
task/internal/execext/exec.go

84 lines
1.6 KiB
Go
Raw Normal View History

2017-03-12 22:18:59 +02:00
package execext
import (
"context"
"errors"
"io"
"os"
"strings"
2018-12-15 19:43:40 +02:00
"mvdan.cc/sh/expand"
"mvdan.cc/sh/interp"
"mvdan.cc/sh/shell"
"mvdan.cc/sh/syntax"
2017-03-12 22:18:59 +02:00
)
2017-04-24 15:25:38 +02:00
// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
Command string
Dir string
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
2017-03-12 22:18:59 +02:00
var (
// ErrNilOptions is returned when a nil options is given
ErrNilOptions = errors.New("execext: nil options given")
2017-03-12 22:18:59 +02:00
)
// RunCommand runs a shell command
2018-09-01 16:02:23 +02:00
func RunCommand(ctx context.Context, opts *RunCommandOptions) error {
if opts == nil {
return ErrNilOptions
}
p, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), "")
if err != nil {
return err
}
2017-03-12 22:18:59 +02:00
environ := opts.Env
if len(environ) == 0 {
environ = os.Environ()
}
2018-09-01 16:02:23 +02:00
r, err := interp.New(
interp.Dir(opts.Dir),
2018-12-15 19:43:40 +02:00
interp.Env(expand.ListEnviron(environ...)),
2018-09-01 16:02:23 +02:00
interp.Module(interp.DefaultExec),
interp.Module(interp.OpenDevImpls(interp.DefaultOpen)),
2018-09-01 16:02:23 +02:00
interp.StdIO(opts.Stdin, opts.Stdout, opts.Stderr),
)
if err != nil {
2017-08-05 19:20:44 +02:00
return err
}
2018-09-01 16:02:23 +02:00
return r.Run(ctx, p)
}
// IsExitError returns true the given error is an exis status error
func IsExitError(err error) bool {
switch err.(type) {
case interp.ExitStatus, interp.ShellExitStatus:
return true
default:
return false
}
2017-03-12 22:18:59 +02:00
}
// Expand is a helper to mvdan.cc/shell.Fields that returns the first field
// if available.
func Expand(s string) (string, error) {
fields, err := shell.Fields(s, nil)
if err != nil {
return "", err
}
if len(fields) > 0 {
return fields[0], nil
}
return "", nil
}