Skip to content

Commit

Permalink
change the logic little bit
Browse files Browse the repository at this point in the history
Signed-off-by: Andrea Waltlova <[email protected]>
  • Loading branch information
andywaltlova committed Oct 26, 2023
1 parent 405ff80 commit ce4ef02
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions src/runner.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"bufio"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -109,26 +110,28 @@ func runCommandWithOutput(cmd *exec.Cmd, outputCh chan string, doneCh chan bool)
return
}

dataReadCh := make(chan bool)
defer close(dataReadCh)

go func() {
// NOTE: This could be set by config or by env variable in received yaml
var bufferSize = 256
buf := make([]byte, bufferSize)
defer func() {
dataReadCh <- true
}()

reader := bufio.NewReader(cmdOutput)

for {
log.Infoln("Writing to buffer ...")
n, err := cmdOutput.Read(buf)
log.Infoln("Buffer full ...")

if err != nil {
if errors.Is(err, io.EOF) {
log.Infoln("Command stdout closed")
return
}
log.Infoln("Error after buffer closed")
line, err := reader.ReadString('\n')
if errors.Is(err, io.EOF) {
log.Infoln("Read ended with EOF")
break
} else if err != nil {
log.Infoln("Read ended with error", err)
outputCh <- fmt.Sprintf("Error reading from stdout: %v", err)
return
}
log.Infoln("Writing data to output channel ...")
outputCh <- string(buf[:n])
buf = make([]byte, bufferSize)
log.Infoln("Read line: ", line)
outputCh <- line
}
}()

Expand All @@ -138,6 +141,10 @@ func runCommandWithOutput(cmd *exec.Cmd, outputCh chan string, doneCh chan bool)
return
}

// NOTE: need to block here before goroutine finishes so wait doesn't close the stdout pipe
log.Infoln("Waiting to collect all stdout from running command")
<-dataReadCh

if err := cmd.Wait(); err != nil {
log.Errorln("Failed to execute script: ", err)
outputCh <- fmt.Sprintf("Error: %v", err)
Expand Down

0 comments on commit ce4ef02

Please sign in to comment.