mirror of
https://github.com/moby/moby.git
synced 2026-01-11 18:51:37 +00:00
The schema of a JSON-stream message is very pertinent to the api module. Provide a canonical definition in the api module and refactor the daemon code to use it. Drop the long-deprecated ErrorMessage field from the API definition, but have the daemon continue to emit it for compatibility with docker-py v7.1.0. Co-authored-by: Cory Snider <csnider@mirantis.com> Signed-off-by: Austin Vazquez <austin.vazquez@docker.com>
48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
package streamformatter
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
|
|
"github.com/moby/moby/api/types/jsonstream"
|
|
)
|
|
|
|
type streamWriter struct {
|
|
io.Writer
|
|
lineFormat func([]byte) string
|
|
}
|
|
|
|
func (sw *streamWriter) Write(buf []byte) (int, error) {
|
|
formattedBuf := sw.format(buf)
|
|
n, err := sw.Writer.Write(formattedBuf)
|
|
if n != len(formattedBuf) {
|
|
return n, io.ErrShortWrite
|
|
}
|
|
return len(buf), err
|
|
}
|
|
|
|
func (sw *streamWriter) format(buf []byte) []byte {
|
|
msg := &jsonstream.Message{Stream: sw.lineFormat(buf)}
|
|
b, err := json.Marshal(msg)
|
|
if err != nil {
|
|
return FormatError(err)
|
|
}
|
|
return appendNewline(b)
|
|
}
|
|
|
|
// NewStdoutWriter returns a writer which formats the output as json message
|
|
// representing stdout lines
|
|
func NewStdoutWriter(out io.Writer) io.Writer {
|
|
return &streamWriter{Writer: out, lineFormat: func(buf []byte) string {
|
|
return string(buf)
|
|
}}
|
|
}
|
|
|
|
// NewStderrWriter returns a writer which formats the output as json message
|
|
// representing stderr lines
|
|
func NewStderrWriter(out io.Writer) io.Writer {
|
|
return &streamWriter{Writer: out, lineFormat: func(buf []byte) string {
|
|
return "\033[91m" + string(buf) + "\033[0m"
|
|
}}
|
|
}
|