mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-12 20:13:59 +02:00
@@ -17,6 +17,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gohugoio/hugo/media"
|
||||
|
||||
"github.com/gohugoio/hugo/parser/pageparser"
|
||||
)
|
||||
|
||||
@@ -55,6 +57,18 @@ func FormatFromString(formatStr string) Format {
|
||||
|
||||
}
|
||||
|
||||
// FormatFromMediaType gets the Format given a MIME type, empty string
|
||||
// if unknown.
|
||||
func FormatFromMediaType(m media.Type) Format {
|
||||
for _, suffix := range m.Suffixes {
|
||||
if f := FormatFromString(suffix); f != "" {
|
||||
return f
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// FormatFromFrontMatterType will return empty if not supported.
|
||||
func FormatFromFrontMatterType(typ pageparser.ItemType) Format {
|
||||
switch typ {
|
||||
@@ -70,3 +84,39 @@ func FormatFromFrontMatterType(typ pageparser.ItemType) Format {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// FormatFromContentString tries to detect the format (JSON, YAML or TOML)
|
||||
// in the given string.
|
||||
// It return an empty string if no format could be detected.
|
||||
func FormatFromContentString(data string) Format {
|
||||
jsonIdx := strings.Index(data, "{")
|
||||
yamlIdx := strings.Index(data, ":")
|
||||
tomlIdx := strings.Index(data, "=")
|
||||
|
||||
if isLowerIndexThan(jsonIdx, yamlIdx, tomlIdx) {
|
||||
return JSON
|
||||
}
|
||||
|
||||
if isLowerIndexThan(yamlIdx, tomlIdx) {
|
||||
return YAML
|
||||
}
|
||||
|
||||
if tomlIdx != -1 {
|
||||
return TOML
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func isLowerIndexThan(first int, others ...int) bool {
|
||||
if first == -1 {
|
||||
return false
|
||||
}
|
||||
for _, other := range others {
|
||||
if other != -1 && other < first {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
Reference in New Issue
Block a user