mirror of
https://github.com/mikefarah/yq.git
synced 2026-09-01 05:34:51 +08:00
Detect input format based on file name extension (#1582)
* detect inputFormat from filename * refactor and extract func InputFormatFromFilename * detect inputFormat only when file is provided * add test for automatic input format detection
This commit is contained in:
+18
-2
@@ -3,6 +3,7 @@ package yqlib
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type InputFormat uint
|
||||
@@ -25,11 +26,11 @@ type Decoder interface {
|
||||
|
||||
func InputFormatFromString(format string) (InputFormat, error) {
|
||||
switch format {
|
||||
case "yaml", "y":
|
||||
case "yaml", "yml", "y":
|
||||
return YamlInputFormat, nil
|
||||
case "xml", "x":
|
||||
return XMLInputFormat, nil
|
||||
case "props", "p":
|
||||
case "properties", "props", "p":
|
||||
return PropertiesInputFormat, nil
|
||||
case "json", "ndjson", "j":
|
||||
return JsonInputFormat, nil
|
||||
@@ -41,3 +42,18 @@ func InputFormatFromString(format string) (InputFormat, error) {
|
||||
return 0, fmt.Errorf("unknown format '%v' please use [yaml|xml|props]", format)
|
||||
}
|
||||
}
|
||||
|
||||
func InputFormatFromFilename(filename string, defaultFormat string) string {
|
||||
if filename != "" {
|
||||
GetLogger().Debugf("checking filename '%s' for inputFormat", filename)
|
||||
nPos := strings.LastIndex(filename, ".")
|
||||
if nPos > -1 {
|
||||
inputFormat := filename[nPos+1:]
|
||||
GetLogger().Debugf("detected inputFormat '%s'", inputFormat)
|
||||
return inputFormat
|
||||
}
|
||||
}
|
||||
|
||||
GetLogger().Debugf("using default inputFormat '%s'", defaultFormat)
|
||||
return defaultFormat
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user