Skip to content

Commit

Permalink
convert file ext to lowercase for format detection (#2121)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
ryenus committed Aug 5, 2024
1 parent b80e1cb commit b9c3ff6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
10 changes: 5 additions & 5 deletions pkg/yqlib/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package yqlib

import (
"fmt"
"path/filepath"
"strings"
)

Expand Down Expand Up @@ -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
}
Expand Down
10 changes: 10 additions & 0 deletions pkg/yqlib/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(""))
}

0 comments on commit b9c3ff6

Please sign in to comment.