github.com/graemephi/kahugo@v0.62.3-0.20211121071557-d78c0423784d/parser/metadecoders/format.go (about) 1 // Copyright 2018 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package metadecoders 15 16 import ( 17 "path/filepath" 18 "strings" 19 20 "github.com/gohugoio/hugo/media" 21 ) 22 23 type Format string 24 25 const ( 26 // These are the supported metdata formats in Hugo. Most of these are also 27 // supported as /data formats. 28 ORG Format = "org" 29 JSON Format = "json" 30 TOML Format = "toml" 31 YAML Format = "yaml" 32 CSV Format = "csv" 33 ) 34 35 // FormatFromString turns formatStr, typically a file extension without any ".", 36 // into a Format. It returns an empty string for unknown formats. 37 func FormatFromString(formatStr string) Format { 38 formatStr = strings.ToLower(formatStr) 39 if strings.Contains(formatStr, ".") { 40 // Assume a filename 41 formatStr = strings.TrimPrefix(filepath.Ext(formatStr), ".") 42 } 43 switch formatStr { 44 case "yaml", "yml": 45 return YAML 46 case "json": 47 return JSON 48 case "toml": 49 return TOML 50 case "org": 51 return ORG 52 case "csv": 53 return CSV 54 } 55 56 return "" 57 } 58 59 // FormatFromMediaType gets the Format given a MIME type, empty string 60 // if unknown. 61 func FormatFromMediaType(m media.Type) Format { 62 for _, suffix := range m.Suffixes() { 63 if f := FormatFromString(suffix); f != "" { 64 return f 65 } 66 } 67 68 return "" 69 } 70 71 // FormatFromContentString tries to detect the format (JSON, YAML or TOML) 72 // in the given string. 73 // It return an empty string if no format could be detected. 74 func (d Decoder) FormatFromContentString(data string) Format { 75 csvIdx := strings.IndexRune(data, d.Delimiter) 76 jsonIdx := strings.Index(data, "{") 77 yamlIdx := strings.Index(data, ":") 78 tomlIdx := strings.Index(data, "=") 79 80 if isLowerIndexThan(csvIdx, jsonIdx, yamlIdx, tomlIdx) { 81 return CSV 82 } 83 84 if isLowerIndexThan(jsonIdx, yamlIdx, tomlIdx) { 85 return JSON 86 } 87 88 if isLowerIndexThan(yamlIdx, tomlIdx) { 89 return YAML 90 } 91 92 if tomlIdx != -1 { 93 return TOML 94 } 95 96 return "" 97 } 98 99 func isLowerIndexThan(first int, others ...int) bool { 100 if first == -1 { 101 return false 102 } 103 for _, other := range others { 104 if other != -1 && other < first { 105 return false 106 } 107 } 108 109 return true 110 }