shell/linux/run.go

64 lines
1.2 KiB
Go

package linux
import (
"errors"
"fmt"
"os"
"os/exec"
)
func NewCommand(options CommandOptions) (*LinuxCommand, error) {
if len(options.Shell) == 0 {
options.Shell = "/bin/bash"
}
if len(options.Cwd) == 0 {
cwd, err := os.Getwd()
if err != nil {
return nil, ErrFetchingCwd
}
options.Cwd = cwd
}
return &LinuxCommand{
Options: options,
}, nil
}
func (cmd *LinuxCommand) Run() error {
command := exec.Command(cmd.Options.Shell, "-c", cmd.Options.Command)
command.Args = append(command.Args, cmd.Options.Args...)
// Loop through env to format and add them to the command.
for key, value := range cmd.Options.Env {
command.Env = append(command.Env, fmt.Sprintf("%s=%s", key, value))
}
if err := command.Start(); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if exitErr.ExitCode() == 127 {
return ErrCommandNotFound
} else {
return fmt.Errorf("%w: %w", ErrRunningCmd, err)
}
}
}
if err := command.Start(); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if exitErr.ExitCode() == 127 {
return ErrCommandNotFound
} else {
return fmt.Errorf("%w: %w", ErrRunningCmd, err)
}
}
}
return nil
}