skip format check for filenames ending with dot

also add a unit test for func FormatStringFromFilename to cover such case
This commit is contained in:
ryenus 2025-07-15 06:40:11 +08:00 committed by Mike Farah
parent 6e8cc00030
commit d0c897f5e6
2 changed files with 37 additions and 1 deletions

View File

@ -113,7 +113,7 @@ func FormatStringFromFilename(filename string) string {
if filename != "" { if filename != "" {
GetLogger().Debugf("checking filename '%s' for auto format detection", filename) GetLogger().Debugf("checking filename '%s' for auto format detection", filename)
ext := filepath.Ext(filename) ext := filepath.Ext(filename)
if ext != "" && ext[0] == '.' { if len(ext) >= 2 && ext[0] == '.' {
format := strings.ToLower(ext[1:]) format := strings.ToLower(ext[1:])
GetLogger().Debugf("detected format '%s'", format) GetLogger().Debugf("detected format '%s'", format)
return format return format

36
test/format_test.go Normal file
View File

@ -0,0 +1,36 @@
package test
import (
"testing"
"github.com/mikefarah/yq/v4/pkg/yqlib"
)
// only test format detection based on filename extension
func TestFormatStringFromFilename(t *testing.T) {
cases := []struct {
filename string
expected string
}{
// filenames that have extensions
{"file.yaml", "yaml"},
{"FILE.JSON", "json"},
{"file.properties", "properties"},
{"file.xml", "xml"},
{"file.unknown", "unknown"},
// filenames without extensions
{"file", "yaml"},
{"a.dir/file", "yaml"},
{"file.", "yaml"},
{".", "yaml"},
{"", "yaml"},
}
for _, c := range cases {
result := yqlib.FormatStringFromFilename(c.filename)
if result != c.expected {
t.Errorf("FormatStringFromFilename(%q) = %q, wanted: %q", c.filename, result, c.expected)
}
}
}