Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue with closing pager stream #9020

Merged
merged 2 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}