2017-07-04 15:09:36 +02:00
|
|
|
package site
|
2017-06-29 17:00:59 +02:00
|
|
|
|
|
|
|
import (
|
2017-07-14 21:24:26 +02:00
|
|
|
"encoding/csv"
|
|
|
|
"encoding/json"
|
2017-06-29 17:00:59 +02:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
2017-07-09 22:17:20 +02:00
|
|
|
"github.com/osteele/gojekyll/utils"
|
2017-06-29 17:00:59 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Site) readDataFiles() error {
|
|
|
|
s.data = map[string]interface{}{}
|
2017-07-01 02:00:38 +02:00
|
|
|
dataDir := filepath.Join(s.SourceDir(), s.config.DataDir)
|
2017-06-29 17:00:59 +02:00
|
|
|
files, err := ioutil.ReadDir(dataDir)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, f := range files {
|
|
|
|
if f.IsDir() {
|
|
|
|
break
|
|
|
|
}
|
2017-07-14 21:24:26 +02:00
|
|
|
var (
|
|
|
|
filename = filepath.Join(dataDir, f.Name())
|
|
|
|
basename = utils.TrimExt(filepath.Base(f.Name()))
|
|
|
|
data, err = readDataFile(filename)
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return utils.WrapPathError(err, filename)
|
|
|
|
}
|
|
|
|
if data != nil {
|
|
|
|
s.data[basename] = data
|
2017-06-29 17:00:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2017-07-14 21:24:26 +02:00
|
|
|
|
|
|
|
func readDataFile(filename string) (interface{}, error) {
|
|
|
|
switch filepath.Ext(filename) {
|
|
|
|
case ".csv":
|
|
|
|
f, err := os.Open(filename)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-07-15 03:19:01 +02:00
|
|
|
defer f.Close() // nolint: errcheck
|
2017-07-14 21:24:26 +02:00
|
|
|
r := csv.NewReader(f)
|
|
|
|
return r.ReadAll()
|
|
|
|
case ".json":
|
|
|
|
b, err := ioutil.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var data interface{}
|
|
|
|
err = json.Unmarshal(b, &data)
|
|
|
|
return data, err
|
|
|
|
case ".yaml", ".yml":
|
|
|
|
b, err := ioutil.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
var data interface{}
|
|
|
|
err = utils.UnmarshalYAMLInterface(b, &data)
|
|
|
|
return data, err
|
|
|
|
}
|
|
|
|
return nil, nil
|
|
|
|
}
|