github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/pkg/streamformatter/streamwriter.go (about)

     1  package streamformatter
     2  
     3  import (
     4  	"encoding/json"
     5  	"io"
     6  
     7  	"github.com/docker/docker/pkg/jsonmessage"
     8  )
     9  
    10  type streamWriter struct {
    11  	io.Writer
    12  	lineFormat func([]byte) string
    13  }
    14  
    15  func (sw *streamWriter) Write(buf []byte) (int, error) {
    16  	formattedBuf := sw.format(buf)
    17  	n, err := sw.Writer.Write(formattedBuf)
    18  	if n != len(formattedBuf) {
    19  		return n, io.ErrShortWrite
    20  	}
    21  	return len(buf), err
    22  }
    23  
    24  func (sw *streamWriter) format(buf []byte) []byte {
    25  	msg := &jsonmessage.JSONMessage{Stream: sw.lineFormat(buf)}
    26  	b, err := json.Marshal(msg)
    27  	if err != nil {
    28  		return FormatError(err)
    29  	}
    30  	return appendNewline(b)
    31  }
    32  
    33  // NewStdoutWriter returns a writer which formats the output as json message
    34  // representing stdout lines
    35  func NewStdoutWriter(out io.Writer) io.Writer {
    36  	return &streamWriter{Writer: out, lineFormat: func(buf []byte) string {
    37  		return string(buf)
    38  	}}
    39  }
    40  
    41  // NewStderrWriter returns a writer which formats the output as json message
    42  // representing stderr lines
    43  func NewStderrWriter(out io.Writer) io.Writer {
    44  	return &streamWriter{Writer: out, lineFormat: func(buf []byte) string {
    45  		return "\033[91m" + string(buf) + "\033[0m"
    46  	}}
    47  }