Skip to content

Commit

Permalink
Update execute.go
Browse files Browse the repository at this point in the history
provided real-time output(CanastaWiki#73)
  • Loading branch information
chl178 authored Mar 21, 2023
1 parent 57e3620 commit c88f0ce
Showing 1 changed file with 29 additions and 8 deletions.
37 changes: 29 additions & 8 deletions internal/execute/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,39 @@ package execute
import (
"bytes"
"fmt"
"github.com/CanastaWiki/Canasta-CLI-Go/internal/logging"
"io"
"os/exec"
"strings"

"github.com/CanastaWiki/Canasta-CLI-Go/internal/logging"
"sync"
)

type writerWithPrint struct {
buf bytes.Buffer
mu sync.Mutex
}

func (w *writerWithPrint) Write(p []byte) (n int, err error) {
w.mu.Lock()
defer w.mu.Unlock()
logging.Print(string(p))
return w.buf.Write(p)
}

func (w *writerWithPrint) String() string {
w.mu.Lock()
defer w.mu.Unlock()
return w.buf.String()
}

func Run(path, command string, cmdArgs ...string) (error, string) {
var stdout bytes.Buffer
var stderr bytes.Buffer
outWriter := &writerWithPrint{}
errWriter := &writerWithPrint{}

logging.Print(fmt.Sprint(command, " ", strings.Join(cmdArgs, " ")))
cmd := exec.Command("bash", "-c", command+" "+strings.Join(cmdArgs, " "))
cmd.Stdout = &stdout
cmd.Stderr = &stderr
cmd.Stdout = io.MultiWriter(outWriter)
cmd.Stderr = io.MultiWriter(errWriter)

if path != "" {
cmd.Dir = path
Expand All @@ -24,8 +44,9 @@ func Run(path, command string, cmdArgs ...string) (error, string) {
if err := cmd.Start(); err != nil {
logging.Fatal(err)
}

err := cmd.Wait()
output := stdout.String() + stderr.String()
logging.Print(output)
output := outWriter.String() + errWriter.String()

return err, output
}

0 comments on commit c88f0ce

Please sign in to comment.