Skip to content

Commit 810f501

Browse files
committed
fix(cmdutil): return converted YAML bytes directly in formatJSON and prevent nil-pointer panic
1 parent 18663c1 commit 810f501

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

‎pkg/cmd/cmdutil.go‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -355,8 +355,7 @@ func formatJSON(res gjson.Result, opts ShowJSONOpts) ([]byte, error) {
355355
if err := json2yaml.Convert(&yaml, input); err != nil {
356356
return nil, err
357357
}
358-
_, err := opts.Stdout.Write([]byte(yaml.String()))
359-
return nil, err
358+
return []byte(yaml.String()), nil
360359
default:
361360
return nil, fmt.Errorf("Invalid format: %s, valid formats are: %s", opts.Format, strings.Join(OutputFormats, ", "))
362361
}

‎pkg/cmd/cmdutil_test.go‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,18 @@ func TestFormatJSON(t *testing.T) {
220220
require.NoError(t, err)
221221
require.Equal(t, `{"a":1}`+"\n", string(formatted))
222222
})
223+
224+
t.Run("YAMLFormat", func(t *testing.T) {
225+
t.Parallel()
226+
227+
res := gjson.Parse(`{"name":"alice","age":30}`)
228+
// Test with Stdout: nil to ensure it does not panic on nil Stdout
229+
formatted, err := formatJSON(res, ShowJSONOpts{Format: "yaml"})
230+
require.NoError(t, err)
231+
require.NotEmpty(t, formatted)
232+
require.Contains(t, string(formatted), "name: alice")
233+
require.Contains(t, string(formatted), "age: 30")
234+
})
223235
}
224236

225237
func TestShowJSONIterator(t *testing.T) {

0 commit comments

Comments
 (0)