From b9c3ff6f0a758a347cc014bf587bdff997cdb6a3 Mon Sep 17 00:00:00 2001 From: ryenus Date: Mon, 5 Aug 2024 13:14:43 +0800 Subject: [PATCH] convert file ext to lowercase for format detection (#2121) * convert file ext to lowercase for format detection To ensure proper file format detection with case-insensitive file systems. * use filepath.Ext for more reliable file ext detection especially for paths like index.js/foo * add a test for file ext based format detection --- pkg/yqlib/format.go | 10 +++++----- pkg/yqlib/format_test.go | 10 ++++++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/pkg/yqlib/format.go b/pkg/yqlib/format.go index 49c47dfd..144aac08 100644 --- a/pkg/yqlib/format.go +++ b/pkg/yqlib/format.go @@ -2,6 +2,7 @@ package yqlib import ( "fmt" + "path/filepath" "strings" ) @@ -107,12 +108,11 @@ func (f *Format) GetConfiguredEncoder() Encoder { } func FormatStringFromFilename(filename string) string { - if filename != "" { - GetLogger().Debugf("checking file extension '%s' for auto format detection", filename) - nPos := strings.LastIndex(filename, ".") - if nPos > -1 { - format := filename[nPos+1:] + GetLogger().Debugf("checking filename '%s' for auto format detection", filename) + ext := filepath.Ext(filename) + if ext != "" && ext[0] == '.' { + format := strings.ToLower(ext[1:]) GetLogger().Debugf("detected format '%s'", format) return format } diff --git a/pkg/yqlib/format_test.go b/pkg/yqlib/format_test.go index e6db1644..6060ccdf 100644 --- a/pkg/yqlib/format_test.go +++ b/pkg/yqlib/format_test.go @@ -50,3 +50,13 @@ func TestFormatFromString(t *testing.T) { } } } + +func TestFormatStringFromFilename(t *testing.T) { + test.AssertResult(t, "yaml", FormatStringFromFilename("test.Yaml")) + test.AssertResult(t, "yaml", FormatStringFromFilename("test.index.Yaml")) + test.AssertResult(t, "yaml", FormatStringFromFilename("test")) + test.AssertResult(t, "json", FormatStringFromFilename("test.json")) + test.AssertResult(t, "json", FormatStringFromFilename("TEST.JSON")) + test.AssertResult(t, "yaml", FormatStringFromFilename("test.json/foo")) + test.AssertResult(t, "yaml", FormatStringFromFilename("")) +}