/
parser.go
96 lines (76 loc) · 1.85 KB
/
parser.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
91
92
93
94
95
96
package mate
import (
"bytes"
"html/template"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/yuin/goldmark"
"golang.org/x/sync/errgroup"
)
type Parser struct {
mu sync.Mutex
}
func NewParser() *Parser {
return &Parser{}
}
// ParsePaths will scan a slice of local, relative paths (provided ideally by mate.Aggregator)
// performing ParsePath on each one and returning an array of pages.
func (p *Parser) ParsePaths(paths []string, project *Project) ([]Post, error) {
posts := make([]Post, 0)
g := new(errgroup.Group)
for _, path := range paths {
path := path
g.Go(func() error {
if post, err := p.ParsePath(path, project); err == nil {
p.mu.Lock()
posts = append(posts, *post)
p.mu.Unlock()
return nil
} else {
return err
}
})
}
if err := g.Wait(); err != nil {
return nil, err
}
posts = project.PostsSorted(project.CreatedOnSorter())
return posts, nil
}
func (p *Parser) ParsePath(path string, project *Project) (*Post, error) {
relativePath, _ := filepath.Rel(project.GetPostsDirectory(), path)
source, err := os.ReadFile(path)
if err != nil {
return nil, err
}
fm := NewFrontMatterFromSource(string(source))
var buf bytes.Buffer
err = goldmark.Convert([]byte(fm.GetBody()), &buf)
if err != nil {
return nil, err
}
fileName := strings.TrimSuffix(filepath.Base(relativePath), filepath.Ext(relativePath))
tags := fm.GetArrayValue("tags")
p.mu.Lock()
project.AddTags(tags...)
p.mu.Unlock()
post := &Post{
CreatedOn: time.Now(),
Title: fm.GetValue("title", fileName),
Tags: tags,
Path: filepath.Dir(relativePath),
File: fileName,
Source: fm.GetBody(),
Body: template.HTML(buf.String()),
Layout: fm.GetValue("layout", "post"),
Slug: fileName,
Project: project,
}
p.mu.Lock()
project.AddPost(*post)
p.mu.Unlock()
return post, nil
}