Skip to content

Commit d0c897f

Browse files
ryenusmikefarah
authored andcommitted
skip format check for filenames ending with dot
also add a unit test for func FormatStringFromFilename to cover such case
1 parent 6e8cc00 commit d0c897f

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

pkg/yqlib/format.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ func FormatStringFromFilename(filename string) string {
113113
if filename != "" {
114114
GetLogger().Debugf("checking filename '%s' for auto format detection", filename)
115115
ext := filepath.Ext(filename)
116-
if ext != "" && ext[0] == '.' {
116+
if len(ext) >= 2 && ext[0] == '.' {
117117
format := strings.ToLower(ext[1:])
118118
GetLogger().Debugf("detected format '%s'", format)
119119
return format

test/format_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/mikefarah/yq/v4/pkg/yqlib"
7+
)
8+
9+
// only test format detection based on filename extension
10+
func TestFormatStringFromFilename(t *testing.T) {
11+
cases := []struct {
12+
filename string
13+
expected string
14+
}{
15+
// filenames that have extensions
16+
{"file.yaml", "yaml"},
17+
{"FILE.JSON", "json"},
18+
{"file.properties", "properties"},
19+
{"file.xml", "xml"},
20+
{"file.unknown", "unknown"},
21+
22+
// filenames without extensions
23+
{"file", "yaml"},
24+
{"a.dir/file", "yaml"},
25+
{"file.", "yaml"},
26+
{".", "yaml"},
27+
{"", "yaml"},
28+
}
29+
30+
for _, c := range cases {
31+
result := yqlib.FormatStringFromFilename(c.filename)
32+
if result != c.expected {
33+
t.Errorf("FormatStringFromFilename(%q) = %q, wanted: %q", c.filename, result, c.expected)
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)