streamwriter.go 1.1 KB

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