Files
ProjectOctopus/agent-go/executor/RealTimeExecutor.go
2023-06-28 16:33:06 +08:00

82 lines
1.9 KiB
Go

package executor
import (
"bufio"
"fmt"
"io"
"os/exec"
)
func ReadTimeCommandExecutor(singleLineCommand []string) {
cmd := exec.Command(singleLineCommand[0], singleLineCommand[1:]...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.ErrorF("command %v stdout error => %v", singleLineCommand, err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.ErrorF("command %v stderr error => %v", singleLineCommand, err)
}
if err := cmd.Start(); err != nil {
log.ErrorF("command %v runtime error => %v", singleLineCommand, err)
}
go realTimeOutput(stdout)
go realTimeOutput(stderr)
if err := cmd.Wait(); err != nil {
log.ErrorF("command %v result error => %v", singleLineCommand, err)
}
}
func AllOutputCommandExecutor(singleLineCommand []string) []string {
cmd := exec.Command(singleLineCommand[0], singleLineCommand[1:]...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.ErrorF("command %v stdout error => %v", singleLineCommand, err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.ErrorF("command %v stderr error => %v", singleLineCommand, err)
}
if err := cmd.Start(); err != nil {
log.ErrorF("command %v runtime error => %v", singleLineCommand, err)
}
var resultSlice []string
resultSlice = append(resultSlice, collectOutput(stdout, resultSlice)...)
resultSlice = append(resultSlice, collectOutput(stderr, resultSlice)...)
if err := cmd.Wait(); err != nil {
log.ErrorF("command %v result error => %v", singleLineCommand, err)
}
//log.DebugF("real time exec result are %v", resultSlice)
return resultSlice
}
func realTimeOutput(r io.Reader) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
func collectOutput(r io.Reader, resultSlice []string) []string {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
resultLine := scanner.Text()
resultSlice = append(resultSlice, resultLine)
// debug usage
//fmt.Println(resultLine)
}
return resultSlice
}