tpl/transform: Add transform.Unmarshal func

Fixes #5428
This commit is contained in:
Bjørn Erik Pedersen
2018-12-21 16:21:13 +01:00
parent 43f9df0194
commit 822dc627a1
20 changed files with 633 additions and 74 deletions

View File

@@ -2,9 +2,10 @@ package transform
import (
"bytes"
"errors"
"strings"
"github.com/pkg/errors"
"github.com/gohugoio/hugo/parser"
"github.com/gohugoio/hugo/parser/metadecoders"
"github.com/spf13/cast"
@@ -34,9 +35,9 @@ func (ns *Namespace) Remarshal(format string, data interface{}) (string, error)
return "", err
}
fromFormat, err := detectFormat(from)
if err != nil {
return "", err
fromFormat := metadecoders.FormatFromContentString(from)
if fromFormat == "" {
return "", errors.New("failed to detect format from content")
}
meta, err := metadecoders.UnmarshalToMap([]byte(from), fromFormat)
@@ -56,24 +57,3 @@ func toFormatMark(format string) (metadecoders.Format, error) {
return "", errors.New("failed to detect target data serialization format")
}
func detectFormat(data string) (metadecoders.Format, error) {
jsonIdx := strings.Index(data, "{")
yamlIdx := strings.Index(data, ":")
tomlIdx := strings.Index(data, "=")
if jsonIdx != -1 && (yamlIdx == -1 || jsonIdx < yamlIdx) && (tomlIdx == -1 || jsonIdx < tomlIdx) {
return metadecoders.JSON, nil
}
if yamlIdx != -1 && (tomlIdx == -1 || yamlIdx < tomlIdx) {
return metadecoders.YAML, nil
}
if tomlIdx != -1 {
return metadecoders.TOML, nil
}
return "", errors.New("failed to detect data serialization format")
}