1
0
mirror of https://github.com/danog/gojekyll.git synced 2025-01-22 12:51:24 +01:00

Read YAML lists

This commit is contained in:
Oliver Steele 2017-06-21 09:42:49 -04:00
parent 1f30aee1f5
commit e16a921af0
2 changed files with 33 additions and 15 deletions

26
helpers/yaml.go Normal file
View File

@ -0,0 +1,26 @@
package helpers
import yaml "gopkg.in/yaml.v2"
// UnmarshalYAMLInterface is a wrapper for yaml.Unmarshall that
// knows how to unmarshal maps and lists.
func UnmarshalYAMLInterface(b []byte, i *interface{}) error {
var m map[interface{}]interface{}
err := yaml.Unmarshal(b, &m)
switch err.(type) {
case *yaml.TypeError:
// Work around https://github.com/go-yaml/yaml/issues/20
var s []interface{}
err = yaml.Unmarshal(b, &s)
if err != nil {
return err
}
*i = s
default:
if err != nil {
return err
}
*i = m
}
return nil
}

View File

@ -1,13 +1,11 @@
package gojekyll
import (
"fmt"
"io/ioutil"
"path/filepath"
"time"
"github.com/osteele/gojekyll/helpers"
yaml "gopkg.in/yaml.v2"
)
func (site *Site) initSiteVariables() error {
@ -45,23 +43,17 @@ func (site *Site) readDataFiles() (VariableMap, error) {
filename := filepath.Join(dataDir, f.Name())
switch filepath.Ext(f.Name()) {
case ".yaml", ".yml":
bytes, err := ioutil.ReadFile(filename)
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
fileData := map[interface{}]interface{}{}
err = yaml.Unmarshal(bytes, &fileData)
switch err.(type) {
case *yaml.TypeError:
fmt.Printf("Warning: skipping %s because it is a list\n", filename)
fmt.Println("See https://github.com/go-yaml/yaml/issues/20")
default:
if err != nil {
return nil, helpers.PathError(err, "read YAML", filename)
}
basename := helpers.TrimExt(filepath.Base(f.Name()))
data[basename] = fileData
var d interface{} // map or slice
err = helpers.UnmarshalYAMLInterface(b, &d)
if err != nil {
return nil, helpers.PathError(err, "read YAML", filename)
}
basename := helpers.TrimExt(filepath.Base(f.Name()))
data[basename] = d
}
}
return data, nil