Skip to content

Commit

Permalink
Provided Real-Time Output for External Subcommands (#75)
Browse files Browse the repository at this point in the history
* Update execute.go

provided real-time output(#73)

* provided real-time output

* provided real-time output

* provid real-time output

* Delete .DS_Store

* Delete .DS_Store

* Further merge fix

* Remove stray tab

---------

Co-authored-by: Yaron Koren <[email protected]>
  • Loading branch information
chl178 and yaronkoren authored Feb 5, 2024
1 parent 1a27fc2 commit d871918
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions internal/execute/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,29 @@ package execute
import (
"bytes"
"fmt"
"io"
"os/exec"
"strings"

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

type writerWithPrint struct {
buf bytes.Buffer
}

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

func (w *writerWithPrint) String() string {
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{}

isVerbose := logging.GetVerbose()
if isVerbose {
Expand All @@ -22,8 +36,8 @@ func Run(path, command string, cmdArgs ...string) (error, string) {

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 @@ -32,8 +46,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 d871918

Please sign in to comment.