Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
BolajiOlajide committed Jan 13, 2023
1 parent 54adfed commit 20ef19c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 22 deletions.
26 changes: 10 additions & 16 deletions internal/batches/ui/interval_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,23 +116,17 @@ type prefixedWriter struct {
prefix string
}

func (w *prefixedWriter) Write(p []byte) (int, error) {
var prefixedLines []byte
for _, line := range bytes.Split(p, []byte("\n")) {
// When we split a byte slice on every new line, we get atleast two sub-slice.
// I'll use a string to demonstrate, if I have a string "Peppermint\n", splitting
// this string on a new line will return a slice with two items: ["Peppermint", ""].
// Using this logic, we can then skip empty lines from being added to the log output.
// SideNote: This means when one logs an actual empty line, we'll also discard that.
if len(bytes.TrimSpace(line)) == 0 {
continue
}
prefixedLine := append([]byte(w.prefix), line...)
prefixedLine = append(prefixedLine, []byte("\n")...)
var newLineByteSlice = []byte("\n")

prefixedLines = append(prefixedLines, prefixedLine...)
}
w.writes <- prefixedLines
func (w *prefixedWriter) Write(p []byte) (int, error) {
var prefixedLine []byte
// We remove new lines appended to the log output so all of the stream can have
// only one new line separating them. This ensures the previous behavior for the log
// structure is preserved.
p = bytes.TrimRight(p, "\n")
prefixedLine = append([]byte(w.prefix), p...)
prefixedLine = append(prefixedLine, newLineByteSlice...)
w.writes <- prefixedLine
<-w.writesDone
return len(p), nil
}
12 changes: 6 additions & 6 deletions internal/batches/ui/interval_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ func TestIntervalWriter(t *testing.T) {
stderrWriter.Write([]byte("4"))
stdoutWriter.Write([]byte("5"))
stderrWriter.Write([]byte("5"))
stdoutWriter.Write([]byte(`Hello world: 772
`))
stderrWriter.Write([]byte(`Hello world: 772
`))
stdoutWriter.Write([]byte(`Hello world: 1
`))
stderrWriter.Write([]byte(`Hello world: 1
`))

select {
case <-ch:
Expand All @@ -70,10 +70,10 @@ func TestIntervalWriter(t *testing.T) {
"stdout: 3\nstderr: 3\n" +
"stdout: 4\nstderr: 4\n" +
"stdout: 5\nstderr: 5\n" +
"stdout: Hello world: 772\nstderr: Hello world: 772\n"
"stdout: Hello world: 1\nstderr: Hello world: 1\n"

if d != want {
t.Fatalf("wrong data in sink. want")
t.Fatalf("wrong data in sink. want=%q, have=%q", want, d)
}
case <-time.After(1 * time.Second):
t.Fatalf("ch has NO data")
Expand Down

0 comments on commit 20ef19c

Please sign in to comment.