Run defers in queue

This commit is contained in:
Heath Stewart 2024-04-04 01:05:10 -07:00
parent a76af8588c
commit 4ea7bcacb3
No known key found for this signature in database
2 changed files with 37 additions and 2 deletions

View file

@ -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()
}
}

View file

@ -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)
}