From e16a921af0d6d1989d9fb7e5cc9c30270bc78ed8 Mon Sep 17 00:00:00 2001 From: Oliver Steele Date: Wed, 21 Jun 2017 09:42:49 -0400 Subject: [PATCH] Read YAML lists --- helpers/yaml.go | 26 ++++++++++++++++++++++++++ site_variables.go | 22 +++++++--------------- 2 files changed, 33 insertions(+), 15 deletions(-) create mode 100644 helpers/yaml.go diff --git a/helpers/yaml.go b/helpers/yaml.go new file mode 100644 index 0000000..84b437a --- /dev/null +++ b/helpers/yaml.go @@ -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 +} diff --git a/site_variables.go b/site_variables.go index 6b42562..a167585 100644 --- a/site_variables.go +++ b/site_variables.go @@ -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