File: streamwriter.go

package info (click to toggle)
docker.io 28.5.2%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 69,048 kB
  • sloc: sh: 5,867; makefile: 863; ansic: 184; python: 162; asm: 159
file content (47 lines) | stat: -rw-r--r-- 1,144 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package streamformatter

import (
	"encoding/json"
	"io"

	"github.com/docker/docker/pkg/jsonmessage"
)

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 := &jsonmessage.JSONMessage{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"
	}}
}