forked from mh-cbon/go-bin-rpm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringexec.go
45 lines (39 loc) · 1.12 KB
/
stringexec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"os"
"os/exec"
"runtime"
"github.com/pkg/errors"
)
// Command Return a new exec.Cmd object for the given command string
func Command(cwd string, cmd string) (*exec.Cmd, error) {
if runtime.GOOS == "windows" {
return ExecStringWindows(cwd, cmd)
}
return ExecStringFriendlyUnix(cwd, cmd)
}
// ExecStringWindows exec given string on cmd
func ExecStringWindows(cwd string, cmd string) (*exec.Cmd, error) {
dir, err := os.MkdirTemp("", "stringexec")
if err != nil {
return nil, errors.WithStack(err)
}
err = os.WriteFile(dir+"/some.bat", []byte(cmd), 0766)
if err != nil {
return nil, errors.WithStack(err)
}
oCmd := exec.Command("cmd", []string{"/C", dir + "/some.bat"}...)
oCmd.Dir = cwd
oCmd.Stdout = os.Stdout
oCmd.Stderr = os.Stderr
// defer os.Remove(tmpfile.Name()) // clean up // not sure how to clean it :x
return oCmd, nil
}
// ExecStringFriendlyUnix exec given string on sh
func ExecStringFriendlyUnix(cwd string, cmd string) (*exec.Cmd, error) {
oCmd := exec.Command("sh", []string{"-c", cmd}...)
oCmd.Dir = cwd
oCmd.Stdout = os.Stdout
oCmd.Stderr = os.Stderr
return oCmd, nil
}