From 28c406706ab7e7fb91149033a5e3c43808af3475 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sat, 30 Mar 2024 14:00:40 +1100 Subject: [PATCH] Fixes npe when given filename ending with "." #1994 --- pkg/yqlib/format.go | 8 ++++--- pkg/yqlib/format_test.go | 52 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 pkg/yqlib/format_test.go diff --git a/pkg/yqlib/format.go b/pkg/yqlib/format.go index a1b35226..49c47dfd 100644 --- a/pkg/yqlib/format.go +++ b/pkg/yqlib/format.go @@ -123,9 +123,11 @@ func FormatStringFromFilename(filename string) string { } func FormatFromString(format string) (*Format, error) { - for _, printerFormat := range Formats { - if printerFormat.MatchesName(format) { - return printerFormat, nil + if format != "" { + for _, printerFormat := range Formats { + if printerFormat.MatchesName(format) { + return printerFormat, nil + } } } return nil, fmt.Errorf("unknown format '%v' please use [%v]", format, GetAvailableOutputFormatString()) diff --git a/pkg/yqlib/format_test.go b/pkg/yqlib/format_test.go new file mode 100644 index 00000000..e6db1644 --- /dev/null +++ b/pkg/yqlib/format_test.go @@ -0,0 +1,52 @@ +package yqlib + +import ( + "fmt" + "strings" + "testing" + + "github.com/mikefarah/yq/v4/test" +) + +type formatStringScenario struct { + description string + input string + expectedFormat *Format + expectedError string +} + +var formatStringScenarios = []formatStringScenario{ + { + description: "yaml", + input: "yaml", + expectedFormat: YamlFormat, + }, + { + description: "Unknown format type", + input: "doc", + expectedError: "unknown format 'doc' please use", + }, + { + description: "blank should error", + input: "", + expectedError: "unknown format '' please use", + }, +} + +func TestFormatFromString(t *testing.T) { + for _, tt := range formatStringScenarios { + actualFormat, actualError := FormatFromString(tt.input) + + if tt.expectedError != "" { + if actualError == nil { + t.Errorf("Expected [%v] error but found none", tt.expectedError) + } else { + test.AssertResultWithContext(t, true, strings.Contains(actualError.Error(), tt.expectedError), + fmt.Sprintf("Expected [%v] to contain [%v]", actualError.Error(), tt.expectedError), + ) + } + } else { + test.AssertResult(t, tt.expectedFormat, actualFormat) + } + } +}