wand/tools/exec.go

51 lines
1.2 KiB
Go
Raw Normal View History

2025-09-01 02:07:48 +02:00
package tools
import (
2025-09-01 04:10:35 +02:00
"bytes"
2025-12-10 20:31:10 +01:00
"fmt"
2025-09-01 02:07:48 +02:00
"io"
"os"
2025-09-01 04:10:35 +02:00
"os/exec"
"strings"
2025-09-01 02:07:48 +02:00
)
func execc(stdin io.Reader, stdout, stderr io.Writer, command string, args []string, env []string) error {
c := strings.Split(command, " ")
cmd := exec.Command(c[0], append(c[1:], args...)...)
cmd.Env = append(os.Environ(), env...)
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = stderr
return cmd.Run()
}
func execCommandDir(out io.Writer, commandDir string, env ...string) error {
2025-12-10 20:31:10 +01:00
if len(commandDir) > 0 && commandDir[0] != '/' && commandDir[0] != '.' {
commandDir = fmt.Sprintf("./%s", commandDir)
}
2025-09-01 02:07:48 +02:00
stderr := bytes.NewBuffer(nil)
if err := execc(nil, out, stderr, "go run", []string{commandDir}, env); err != nil {
io.Copy(os.Stderr, stderr)
return err
}
return nil
}
func execInternal(command string, args ...string) error {
stdout := bytes.NewBuffer(nil)
stderr := bytes.NewBuffer(nil)
if err := execc(nil, stdout, stderr, command, args, nil); err != nil {
io.Copy(os.Stderr, stdout)
io.Copy(os.Stderr, stderr)
return err
}
return nil
}
func execTransparent(command string, args ...string) error {
return execc(os.Stdin, os.Stdout, os.Stderr, command, args, nil)
}