harness-drone/stream/stream.go

61 lines
1.4 KiB
Go
Raw Normal View History

2016-04-13 00:27:24 +00:00
package stream
import (
"bufio"
"io"
"strconv"
"golang.org/x/net/context"
)
2016-04-23 00:35:32 +00:00
// Stream manages the stream of build logs.
type Stream interface {
Create(string) error
Delete(string) error
Reader(string) (io.ReadCloser, error)
2016-04-23 00:35:32 +00:00
Writer(string) (io.WriteCloser, error)
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
// Create creates a new stream.
func Create(c context.Context, key string) error {
2016-04-13 00:27:24 +00:00
return FromContext(c).Create(key)
}
2016-04-23 00:35:32 +00:00
// Reader opens the stream for reading.
func Reader(c context.Context, key string) (io.ReadCloser, error) {
2016-04-23 00:35:32 +00:00
return FromContext(c).Reader(key)
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
// Writer opens the stream for writing.
func Writer(c context.Context, key string) (io.WriteCloser, error) {
return FromContext(c).Writer(key)
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
// Delete deletes the stream by key.
func Delete(c context.Context, key string) error {
return FromContext(c).Delete(key)
2016-04-13 00:27:24 +00:00
}
// ToKey is a helper function that converts a unique identifier
// of type int64 into a string.
func ToKey(i int64) string {
return strconv.FormatInt(i, 10)
}
2016-04-23 00:35:32 +00:00
// Copy copies the stream from the source to the destination in valid JSON
// format. This converts the logs, which are per-line JSON objects, to a
// proper JSON array.
2016-04-13 00:27:24 +00:00
func Copy(dest io.Writer, src io.Reader) error {
io.WriteString(dest, "[")
scanner := bufio.NewScanner(src)
for scanner.Scan() {
io.WriteString(dest, scanner.Text())
io.WriteString(dest, ",\n")
}
io.WriteString(dest, "{}]")
return nil
}