Fix issue with closing pager stream (#9020)

Signed-off-by: Babak K. Shandiz <babak.k.shandiz@gmail.com>
This commit is contained in:
Babak K. Shandiz 2024-04-29 14:48:08 +01:00 committed by GitHub
parent 7d432bcd3a
commit 7c4e45cc9d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 9 additions and 44 deletions

View file

@ -309,6 +309,14 @@ func apiRun(opts *ApiOptions) error {
method = "POST"
}
if !opts.Silent {
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
}
var bodyWriter io.Writer = opts.IO.Out
var headersWriter io.Writer = opts.IO.Out
if opts.Silent {
@ -324,19 +332,13 @@ func apiRun(opts *ApiOptions) error {
requestPath = addPerPage(requestPath, 100, params)
}
// Execute defers in FIFO order.
deferQueue := queue{}
defer deferQueue.Close()
// Similar to `jq --slurp`, write all pages JSON arrays or objects into a JSON array.
if opts.Paginate && opts.Slurp {
w := &jsonArrayWriter{
Writer: bodyWriter,
color: opts.IO.ColorEnabled(),
}
deferQueue.Enqueue(func() {
_ = w.Close()
})
defer w.Close()
bodyWriter = w
}
@ -386,14 +388,6 @@ func apiRun(opts *ApiOptions) error {
return err
}
if !opts.Silent {
if err := opts.IO.StartPager(); err == nil {
deferQueue.Enqueue(opts.IO.StopPager)
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
}
host, _ := cfg.Authentication().DefaultHost()
if opts.Hostname != "" {
@ -693,15 +687,3 @@ func previewNamesToMIMETypes(names []string) string {
}
return strings.Join(types, ", ")
}
type queue []func()
func (q *queue) Enqueue(f func()) {
*q = append(*q, f)
}
func (q *queue) Close() {
for _, f := range *q {
f()
}
}

View file

@ -1761,20 +1761,3 @@ func Test_apiRun_acceptHeader(t *testing.T) {
})
}
}
func TestQueue_Close(t *testing.T) {
sut := queue{}
actual := make([]int, 0, 2)
func() {
defer sut.Close()
sut.Enqueue(func() {
actual = append(actual, 0)
})
sut.Enqueue(func() {
actual = append(actual, 1)
})
}()
assert.Equal(t, []int{0, 1}, actual)
}