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

CLOUDP-270626 Fix executing "output" at <.Results> #3313

Merged
merged 3 commits into from
Oct 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions internal/cli/output_opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"fmt"
"io"
"os"
"reflect"
"strings"

"github.com/PaesslerAG/jsonpath"
Expand Down Expand Up @@ -108,6 +109,40 @@ func (opts *OutputOpts) IsCygwinTerminal() bool {
return terminal.IsCygwinTerminal(opts.OutWriter)
}

func isNil(o any) bool {
if o == nil {
return true
}
ot := reflect.TypeOf(o)
otk := ot.Kind()
switch otk { //nolint:exhaustive // clearer code
case reflect.Array, reflect.Slice, reflect.Map, reflect.Chan, reflect.Pointer, reflect.UnsafePointer, reflect.Interface:
return reflect.ValueOf(o).IsNil()
default:
return false
}
}

func isOrPtrToSliceOrArray(o any) bool {
ot := reflect.TypeOf(o)
if ot == nil {
return false
}
otk := ot.Kind()
switch otk { //nolint:exhaustive // clearer code
case reflect.Array, reflect.Slice:
return true
case reflect.Pointer:
opt := reflect.PointerTo(ot)
optk := opt.Kind()
switch optk { //nolint:exhaustive // clearer code
case reflect.Array, reflect.Slice:
return true
}
}
return false
}

// Print will evaluate the defined format and try to parse it accordingly outputting to the set writer.
func (opts *OutputOpts) Print(o any) error {
if opts.ConfigOutput() == jsonFormat {
Expand All @@ -125,6 +160,13 @@ func (opts *OutputOpts) Print(o any) error {
}

if t != "" {
if isNil(o) {
if isOrPtrToSliceOrArray(o) {
o = []map[string]any{}
} else {
o = map[string]any{}
}
}
return templatewriter.Print(opts.ConfigWriter(), t, o)
}
_, err = fmt.Fprintln(opts.ConfigWriter(), o)
Expand Down