Skip to content

Commit

Permalink
Honor IO errors in list-images sub-command
Browse files Browse the repository at this point in the history
Previously, the sub-command did not interrupt the loop and returned
successfully, even when it encountered IO errors while writing to
standard out.

Signed-off-by: Tom Wieczorek <[email protected]>
  • Loading branch information
twz123 committed Dec 9, 2024
1 parent 9e1249f commit 868a109
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion cmd/airgap/listimages.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,11 @@ func NewAirgapListImagesCmd() *cobra.Command {
return fmt.Errorf("failed to get config: %w", err)
}

out := cmd.OutOrStdout()
for _, uri := range airgap.GetImageURIs(clusterConfig.Spec, all) {
fmt.Fprintln(cmd.OutOrStdout(), uri)
if _, err := fmt.Fprintln(out, uri); err != nil {
return err
}
}
return nil
},
Expand Down
19 changes: 19 additions & 0 deletions cmd/airgap/listimages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ import (
"testing"
"testing/iotest"

internalio "github.com/k0sproject/k0s/internal/io"
"github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1"

"github.com/spf13/cobra"

"github.com/stretchr/testify/assert"
Expand All @@ -42,6 +44,23 @@ func TestAirgapListImages(t *testing.T) {

defaultImage := v1beta1.DefaultEnvoyProxyImage().URI()

t.Run("HonorsIOErrors", func(t *testing.T) {
var writes uint
underTest := NewAirgapListImagesCmd()
underTest.SetIn(iotest.ErrReader(errors.New("unexpected read from standard input")))
underTest.SilenceUsage = true // Cobra writes usage to stdout on errors 🤔
underTest.SetOut(internalio.WriterFunc(func(p []byte) (int, error) {
writes++
return 0, assert.AnError
}))
var stderr strings.Builder
underTest.SetErr(&stderr)

assert.Same(t, assert.AnError, underTest.Execute())
assert.Equal(t, uint(1), writes, "Expected a single write to stdout")
assert.Equal(t, fmt.Sprintf("Error: %v\n", assert.AnError), stderr.String())
})

t.Run("All", func(t *testing.T) {
underTest, out, err := newAirgapListImagesCmdWithConfig(t, "{}", "--all")

Expand Down

0 comments on commit 868a109

Please sign in to comment.