1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-12-04 05:57:50 +01:00
gojekyll/templates/frontmatter.go

38 lines
1.1 KiB
Go
Raw Normal View History

2017-06-24 20:00:19 +02:00
package templates
2017-06-22 17:02:32 +02:00
import (
"bytes"
"regexp"
yaml "gopkg.in/yaml.v2"
)
2017-06-24 20:00:19 +02:00
var (
frontMatterMatcher = regexp.MustCompile(`(?s)^---\n(.+?\n)---\n`)
emptyFontMatterMatcher = regexp.MustCompile(`(?s)^---\n+---\n`)
)
2017-06-22 17:02:32 +02:00
// ReadFrontMatter reads the front matter from a document.
2017-06-24 20:00:19 +02:00
func ReadFrontMatter(sourcePtr *[]byte) (frontMatter VariableMap, err error) {
2017-06-22 17:02:32 +02:00
var (
source = *sourcePtr
start = 0
)
// Replace Windows linefeeds. This allows the following regular expressions to work.
source = bytes.Replace(source, []byte("\r\n"), []byte("\n"), -1)
if match := frontMatterMatcher.FindSubmatchIndex(source); match != nil {
start = match[1]
if err = yaml.Unmarshal(source[match[2]:match[3]], &frontMatter); err != nil {
return
}
} else if match := emptyFontMatterMatcher.FindSubmatchIndex(source); match != nil {
start = match[1]
}
// This fixes the line numbers, so that template errors show with the correct line.
// TODO find a less hack-ey solution
*sourcePtr = append(
regexp.MustCompile(`[^\n\r]+`).ReplaceAllLiteral(source[:start], []byte{}),
source[start:]...)
return
}