Skip to content

Commit

Permalink
Fix issue with closing pager stream (#9020)
Browse files Browse the repository at this point in the history
Signed-off-by: Babak K. Shandiz <babak.k.shandiz@gmail.com>
  • Loading branch information
babakks committed Apr 29, 2024
1 parent 7d432bc commit 7c4e45c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 44 deletions.
36 changes: 9 additions & 27 deletions pkg/cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
Expand Down Expand Up @@ -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 != "" {
Expand Down Expand Up @@ -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()
}
}
17 changes: 0 additions & 17 deletions pkg/cmd/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 7c4e45c

Please sign in to comment.