add commands support

Signed-off-by: Casey Lee <cplee@nektos.com>
This commit is contained in:
Casey Lee
2020-02-11 23:38:30 -08:00
parent 033168228b
commit f7252cbcf9
12 changed files with 303 additions and 33 deletions

47
pkg/common/line_writer.go Normal file
View File

@@ -0,0 +1,47 @@
package common
import (
"bytes"
"io"
)
// LineHandler is a callback function for handling a line
type LineHandler func(line string)
type lineWriter struct {
buffer bytes.Buffer
handlers []LineHandler
}
// NewLineWriter creates a new instance of a line writer
func NewLineWriter(handlers ...LineHandler) io.Writer {
w := new(lineWriter)
w.handlers = handlers
return w
}
func (lw *lineWriter) Write(p []byte) (n int, err error) {
pBuf := bytes.NewBuffer(p)
written := 0
for {
line, err := pBuf.ReadString('\n')
w, _ := lw.buffer.WriteString(line)
written += w
if err == nil {
lw.handleLine(lw.buffer.String())
lw.buffer.Reset()
} else if err == io.EOF {
break
} else {
return written, err
}
}
return written, nil
}
func (lw *lineWriter) handleLine(line string) {
for _, h := range lw.handlers {
h(line)
}
}

View File

@@ -0,0 +1,36 @@
package common
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestLineWriter(t *testing.T) {
lines := make([]string, 0)
lineHandler := func(s string) {
lines = append(lines, s)
}
lineWriter := NewLineWriter(lineHandler)
assert := assert.New(t)
write := func(s string) {
n, err := lineWriter.Write([]byte(s))
assert.NoError(err)
assert.Equal(len(s), n, s)
}
write("hello")
write(" ")
write("world!!\nextra")
write(" line\n and another\nlast")
write(" line\n")
write("no newline here...")
assert.Len(lines, 4)
assert.Equal("hello world!!\n", lines[0])
assert.Equal("extra line\n", lines[1])
assert.Equal(" and another\n", lines[2])
assert.Equal("last line\n", lines[3])
}