-
Notifications
You must be signed in to change notification settings - Fork 2
/
fmatter.go
80 lines (69 loc) · 1.69 KB
/
fmatter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Package fmatter is a simple YAML Front Matter parser, using the
// gopkg.in/yaml.v2 package.
package fmatter
import (
"bytes"
"io"
"io/ioutil"
"strings"
"unicode"
"gopkg.in/yaml.v2"
)
// ReadFile read an entire file into memory, and calls Read which
// parses the front matter data and returns the remaining file
// contents.
func ReadFile(filename string, frontmatter interface{}) (content []byte, err error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return Read(data, frontmatter)
}
// Read detects and parses the front matter data, and returns the
// remaining contents. If no front matter is found, the entire
// file contents are returned. For details on the frontmatter
// parameter, please see the gopkg.in/yaml.v2 package.
func Read(data []byte, frontmatter interface{}) (content []byte, err error) {
r := bytes.NewBuffer(data)
// eat away starting whitespace
var ch rune = ' '
for unicode.IsSpace(ch) {
ch, _, err = r.ReadRune()
if err != nil {
// file is just whitespace
return []byte{}, nil
}
}
r.UnreadRune()
// check if first line is ---
line, err := r.ReadString('\n')
if err != nil && err != io.EOF {
return nil, err
}
if strings.TrimSpace(line) != "---" {
// no front matter, just content
return data, nil
}
yamlStart := len(data) - r.Len()
yamlEnd := yamlStart
for {
line, err = r.ReadString('\n')
if err != nil {
if err == io.EOF {
return data, nil
}
return nil, err
}
if strings.TrimSpace(line) == "---" {
yamlEnd = len(data) - r.Len()
break
}
}
err = yaml.Unmarshal(data[yamlStart:yamlEnd], frontmatter)
if err != nil {
return nil, err
}
content = data[yamlEnd:]
err = nil
return
}