File: display.go

package info (click to toggle)
docker.io 28.5.2%2Bdfsg3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 68,176 kB
  • sloc: sh: 5,867; makefile: 863; ansic: 184; python: 162; asm: 159
file content (68 lines) | stat: -rw-r--r-- 1,487 bytes parent folder | download
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package jsonstream

import (
	"context"
	"io"

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

type (
	Stream       = jsonmessage.Stream
	JSONMessage  = jsonmessage.JSONMessage
	JSONError    = jsonmessage.JSONError
	JSONProgress = jsonmessage.JSONProgress
)

type ctxReader struct {
	err chan error
	r   io.Reader
}

func (r *ctxReader) Read(p []byte) (n int, err error) {
	select {
	case err = <-r.err:
		return 0, err
	default:
		return r.r.Read(p)
	}
}

type Options func(*options)

type options struct {
	AuxCallback func(JSONMessage)
}

func WithAuxCallback(cb func(JSONMessage)) Options {
	return func(o *options) {
		o.AuxCallback = cb
	}
}

// Display prints the JSON messages from the given reader to the given stream.
//
// It wraps the [jsonmessage.DisplayJSONMessagesStream] function to make it
// "context aware" and appropriately returns why the function was canceled.
//
// It returns an error if the context is canceled, but not if the input reader / stream is closed.
func Display(ctx context.Context, in io.Reader, stream Stream, opts ...Options) error {
	if ctx.Err() != nil {
		return ctx.Err()
	}

	reader := &ctxReader{err: make(chan error, 1), r: in}
	stopFunc := context.AfterFunc(ctx, func() { reader.err <- ctx.Err() })
	defer stopFunc()

	o := options{}
	for _, opt := range opts {
		opt(&o)
	}

	if err := jsonmessage.DisplayJSONMessagesStream(reader, stream, stream.FD(), stream.IsTerminal(), o.AuxCallback); err != nil {
		return err
	}

	return ctx.Err()
}