From 7c4e45cc9dd39764a7d11ae206dd011c885d2759 Mon Sep 17 00:00:00 2001 From: "Babak K. Shandiz" Date: Mon, 29 Apr 2024 14:48:08 +0100 Subject: [PATCH] Fix issue with closing pager stream (#9020) Signed-off-by: Babak K. Shandiz --- pkg/cmd/api/api.go | 36 +++++++++--------------------------- pkg/cmd/api/api_test.go | 17 ----------------- 2 files changed, 9 insertions(+), 44 deletions(-) diff --git a/pkg/cmd/api/api.go b/pkg/cmd/api/api.go index dc80298b2..8184065ca 100644 --- a/pkg/cmd/api/api.go +++ b/pkg/cmd/api/api.go @@ -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() - } -} diff --git a/pkg/cmd/api/api_test.go b/pkg/cmd/api/api_test.go index 38218fcaf..55138b3c7 100644 --- a/pkg/cmd/api/api_test.go +++ b/pkg/cmd/api/api_test.go @@ -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) -}