-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrontmatter.go
90 lines (80 loc) · 1.74 KB
/
frontmatter.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
81
82
83
84
85
86
87
88
89
90
package frontmatter
import (
"errors"
"regexp"
"runtime"
"strings"
"unicode"
"gopkg.in/yaml.v2"
)
var (
regex *regexp.Regexp
ErrNoFrontMatter = errors.New("Frontmatter not found")
)
func hasFrontMatter(md string) bool {
md = strings.TrimLeftFunc(md, unicode.IsSpace)
lines := strings.Split(md, "\n")
if len(lines) > 0 && (strings.HasPrefix(lines[0], "= yaml =") ||
strings.HasPrefix(lines[0], "---")) {
return regex.MatchString(md)
}
return false
}
func trimLeft(md string) string {
return strings.TrimLeftFunc(md, unicode.IsSpace)
}
func submatches(md string) []string {
return regex.FindStringSubmatch(md)
}
func extract(md string) string {
matches := submatches(md)
if len(matches) <= 4 {
return ""
}
return strings.TrimSpace(matches[3])
}
func Extract(md string) string {
md = trimLeft(md)
if hasFrontMatter(md) {
return extract(md)
}
return ""
}
func Parse(md string) (map[string]interface{}, error) {
front := Extract(md)
if front == "" {
return map[string]interface{}{}, ErrNoFrontMatter
}
res := make(map[string]interface{})
err := yaml.Unmarshal([]byte(front), &res)
return res, err
}
func Trim(md string) string {
md = trimLeft(md)
if !hasFrontMatter(md) {
return md
}
matches := submatches(md)
if len(matches) <= 4 {
return md
}
return trimLeft(md[len(matches[0]):])
}
func init() {
var lineend = ""
if runtime.GOOS == "windows" {
lineend = `\\r?`
}
// see syntax : https://github.com/google/re2/wiki/Syntax
// also the tool at : https://regex-golang.appspot.com/
// regexp is based on https://github.com/jxson/front-matter
pat := `(?m)^(` +
`(= yaml =|---)` +
`$([\s\S]*?)` +
`(?:((---)|(\.\.\.)))` +
`$` +
lineend +
`(?:\\n)?)` +
`(.*)`
regex = regexp.MustCompile(pat)
}