shell/linux/run.go

67 lines
1.3 KiB
Go
Raw Normal View History

2024-07-04 22:40:13 +02:00
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) {
2024-07-04 22:46:29 +02:00
fmt.Println(exitErr.ExitCode())
2024-07-04 22:40:13 +02:00
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) {
2024-07-04 22:46:29 +02:00
fmt.Println(exitErr.ExitCode())
2024-07-04 22:40:13 +02:00
if exitErr.ExitCode() == 127 {
return ErrCommandNotFound
} else {
return fmt.Errorf("%w: %w", ErrRunningCmd, err)
}
}
}
return nil
}