diff --git a/pkg/cmd/api/api.go b/pkg/cmd/api/api.go index 7bd9fcd0d28..f835cec4501 100644 --- a/pkg/cmd/api/api.go +++ b/pkg/cmd/api/api.go @@ -318,13 +318,19 @@ 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(), } - defer w.Close() + deferQueue.Enqueue(func() { + _ = w.Close() + }) bodyWriter = w } @@ -376,7 +382,7 @@ func apiRun(opts *ApiOptions) error { if !opts.Silent { if err := opts.IO.StartPager(); err == nil { - defer opts.IO.StopPager() + deferQueue.Enqueue(opts.IO.StopPager) } else { fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err) } @@ -681,3 +687,15 @@ 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 5244f04d480..944eaa4c95a 100644 --- a/pkg/cmd/api/api_test.go +++ b/pkg/cmd/api/api_test.go @@ -1760,3 +1760,20 @@ 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) +}