Skip to content

Commit

Permalink
Run defers in queue
Browse files Browse the repository at this point in the history
  • Loading branch information
heaths committed Apr 4, 2024
1 parent f276971 commit 7ae6798
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
22 changes: 20 additions & 2 deletions pkg/cmd/api/api.go
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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()
}
}
17 changes: 17 additions & 0 deletions pkg/cmd/api/api_test.go
Expand Up @@ -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)
}

0 comments on commit 7ae6798

Please sign in to comment.