Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom split char #49

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ type Options struct {
// faster and more efficient than polling Cmd.Status. The caller must read both
// streaming channels, else lines are dropped silently.
Streaming bool

// If Streaming is true and SplitChar is set, Cmd.Stdout and Cmd.Stderr
// channels will be split using this char instead of the default '\n'.
SplitChar *byte
}

// NewCmdOptions creates a new Cmd with options. The command is not started
Expand Down Expand Up @@ -157,6 +161,11 @@ func NewCmdOptions(options Options, name string, args ...string) *Cmd {

c.Stderr = make(chan string, DEFAULT_STREAM_CHAN_SIZE)
c.stderrStream = NewOutputStream(c.Stderr)

if options.SplitChar != nil {
c.stdoutStream.splitChar = *options.SplitChar
c.stderrStream.splitChar = *options.SplitChar
}
}

return c
Expand Down Expand Up @@ -554,6 +563,7 @@ type OutputStream struct {
bufSize int
buf []byte
lastChar int
splitChar byte
}

// NewOutputStream creates a new streaming output on the given channel. The
Expand All @@ -563,9 +573,10 @@ func NewOutputStream(streamChan chan string) *OutputStream {
out := &OutputStream{
streamChan: streamChan,
// --
bufSize: DEFAULT_LINE_BUFFER_SIZE,
buf: make([]byte, DEFAULT_LINE_BUFFER_SIZE),
lastChar: 0,
bufSize: DEFAULT_LINE_BUFFER_SIZE,
buf: make([]byte, DEFAULT_LINE_BUFFER_SIZE),
lastChar: 0,
splitChar: '\n',
}
return out
}
Expand All @@ -581,7 +592,7 @@ func (rw *OutputStream) Write(p []byte) (n int, err error) {
// can contain multiple lines, like "foo\nbar". So in that case nextLine
// will be 0 ("foo\nbar\n") then 4 ("bar\n") on next iteration. And i
// will be 3 and 7, respectively. So lines are [0:3] are [4:7].
newlineOffset := bytes.IndexByte(p[firstChar:], '\n')
newlineOffset := bytes.IndexByte(p[firstChar:], rw.splitChar)
if newlineOffset < 0 {
break // no newline in stream, next line incomplete
}
Expand Down