Skip to content

Commit d4dc259

Browse files
committed
fix: incorrect shell command parse
1 parent 4ce4f7a commit d4dc259

File tree

1 file changed

+47
-13
lines changed

1 file changed

+47
-13
lines changed

main.go

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"fmt"
5+
"io"
56
"os"
67
"os/exec"
78
"path"
@@ -88,25 +89,58 @@ func execute(cmdMap map[string][]string, contextDir string) (err error) {
8889
for _, title := range titles {
8990
cmds := cmdMap[title]
9091
for _, cmdLine := range cmds {
91-
fmt.Println("start to run:", cmdLine)
92-
93-
args := strings.Split(cmdLine, " ")
94-
cmd := strings.TrimSpace(args[0])
95-
if cmd, err = exec.LookPath(cmd); err != nil {
96-
fmt.Println("failed to find", cmd)
97-
continue
92+
var shellFile string
93+
if shellFile, err = writeAsShell(cmdLine, contextDir); err != nil {
94+
fmt.Println(err)
95+
break
9896
}
97+
defer func() {
98+
_ = os.RemoveAll(shellFile)
99+
}()
100+
101+
cmd := exec.Command("bash", path.Base(shellFile))
102+
cmd.Dir = contextDir
103+
cmd.Env = os.Environ()
99104

100105
var output []byte
101-
cmdRun := exec.Command(cmd, args[1:]...)
102-
cmdRun.Dir = contextDir
103-
cmdRun.Env = os.Environ()
104-
if output, err = cmdRun.CombinedOutput(); err == nil {
105-
fmt.Print(string(output))
106-
} else {
106+
if output, err = cmd.CombinedOutput(); err != nil {
107107
fmt.Println(string(output), err)
108+
break
108109
}
110+
fmt.Print(string(output))
109111
}
110112
}
111113
return
112114
}
115+
116+
func writeAsShell(content, dir string) (targetPath string, err error) {
117+
var f *os.File
118+
if f, err = os.CreateTemp(dir, "sh"); err == nil {
119+
defer func() {
120+
_ = f.Close()
121+
}()
122+
123+
targetPath = f.Name()
124+
_, err = io.WriteString(f, content)
125+
}
126+
return
127+
}
128+
129+
func runAsInlineCommand(cmdLine, contextDir string) (err error) {
130+
args := strings.Split(cmdLine, " ")
131+
cmd := strings.TrimSpace(args[0])
132+
if cmd, err = exec.LookPath(cmd); err != nil {
133+
err = fmt.Errorf("failed to find '%s'", cmd)
134+
return
135+
}
136+
137+
fmt.Printf("start to run: %s %v\n", cmd, args[1:])
138+
var output []byte
139+
cmdRun := exec.Command(cmd, args[1:]...)
140+
cmdRun.Dir = contextDir
141+
cmdRun.Env = os.Environ()
142+
if output, err = cmdRun.CombinedOutput(); err == nil {
143+
fmt.Print(string(output))
144+
}
145+
return
146+
}

0 commit comments

Comments
 (0)