frontmatter.go (2386B)
1 // Copyright 2015 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 parser 15 16 import ( 17 "encoding/json" 18 "errors" 19 "io" 20 21 "github.com/gohugoio/hugo/parser/metadecoders" 22 23 toml "github.com/pelletier/go-toml/v2" 24 25 yaml "gopkg.in/yaml.v2" 26 27 xml "github.com/clbanning/mxj/v2" 28 ) 29 30 const ( 31 yamlDelimLf = "---\n" 32 tomlDelimLf = "+++\n" 33 ) 34 35 func InterfaceToConfig(in any, format metadecoders.Format, w io.Writer) error { 36 if in == nil { 37 return errors.New("input was nil") 38 } 39 40 switch format { 41 case metadecoders.YAML: 42 b, err := yaml.Marshal(in) 43 if err != nil { 44 return err 45 } 46 47 _, err = w.Write(b) 48 return err 49 50 case metadecoders.TOML: 51 enc := toml.NewEncoder(w) 52 enc.SetIndentTables(true) 53 return enc.Encode(in) 54 case metadecoders.JSON: 55 b, err := json.MarshalIndent(in, "", " ") 56 if err != nil { 57 return err 58 } 59 60 _, err = w.Write(b) 61 if err != nil { 62 return err 63 } 64 65 _, err = w.Write([]byte{'\n'}) 66 return err 67 case metadecoders.XML: 68 b, err := xml.AnyXmlIndent(in, "", "\t", "root") 69 if err != nil { 70 return err 71 } 72 73 _, err = w.Write(b) 74 return err 75 default: 76 return errors.New("unsupported Format provided") 77 } 78 } 79 80 func InterfaceToFrontMatter(in any, format metadecoders.Format, w io.Writer) error { 81 if in == nil { 82 return errors.New("input was nil") 83 } 84 85 switch format { 86 case metadecoders.YAML: 87 _, err := w.Write([]byte(yamlDelimLf)) 88 if err != nil { 89 return err 90 } 91 92 err = InterfaceToConfig(in, format, w) 93 if err != nil { 94 return err 95 } 96 97 _, err = w.Write([]byte(yamlDelimLf)) 98 return err 99 100 case metadecoders.TOML: 101 _, err := w.Write([]byte(tomlDelimLf)) 102 if err != nil { 103 return err 104 } 105 106 err = InterfaceToConfig(in, format, w) 107 108 if err != nil { 109 return err 110 } 111 112 _, err = w.Write([]byte("\n" + tomlDelimLf)) 113 return err 114 115 default: 116 return InterfaceToConfig(in, format, w) 117 } 118 }