-
Notifications
You must be signed in to change notification settings - Fork 2
/
posts.go
242 lines (204 loc) · 5.39 KB
/
posts.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package engine
import (
"bufio"
"errors"
"fmt"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/parser"
"github.com/goodsign/monday"
"github.com/petarov/nenu/config"
)
type postPageData struct {
*config.YML
Post Post
}
// Post post meta data
type Post struct {
filename string
filenameHTML string
filepath string
date time.Time
Title string
Subtitle string
Summary string
Date string
ShortDate string
Content template.HTML
Permalink template.URL
PermalinkURL string
ImageURL string
IsPublish bool
IsIndex bool
Prev *Post
}
var (
markdownExt = []string{".md", ".markdown", ".mkd", ".mdown", ".mdwn"}
htmlDateLayout = "Monday, 02 January 2006"
)
func isExtOk(needle string) bool {
for _, ext := range markdownExt {
if ext == needle {
return true
}
}
return false
}
func writePost(post *Post, data []byte, templates *Templates) (err error) {
var (
lines = make([]string, 0)
parsing = false
)
// published unless specified otherwise
post.IsPublish = true
scanner := bufio.NewScanner(strings.NewReader(string(data)))
for scanner.Scan() {
line := scanner.Text()
switch {
case strings.HasPrefix(line, "---"):
parsing = !parsing
case strings.HasPrefix(line, "title:"):
post.Title = strings.TrimSpace(line[7:])
if len(post.Title) == 0 {
return errors.New("post title cannot be empty")
}
case strings.HasPrefix(line, "subtitle:"):
post.Subtitle = strings.TrimSpace(line[10:])
case strings.HasPrefix(line, "summary:"):
post.Summary = strings.TrimSpace(line[8:])
// case strings.HasPrefix(line, "date:"):
// post.date, err = time.Parse(time.RFC3339, line[6:])
// if err != nil {
// return
// }
case strings.HasPrefix(line, "publish:"):
post.IsPublish, err = strconv.ParseBool(line[9:])
if err != nil {
return
}
default:
if !parsing {
if len(line) > 0 {
lines = append(lines, line)
lines = append(lines, "\n")
} else {
lines = append(lines, "\n\n")
}
}
}
}
if post.IsPublish {
parser := parser.NewWithExtensions(extensions)
post.Content = template.HTML(markdown.ToHTML([]byte(strings.Join(lines, "")), parser, nil))
locale := monday.Locale(config.YMLConfig.Content.Locale)
post.Date = monday.Format(post.date.In(config.TimeZoneLocation).Local(), htmlDateLayout, locale)
post.ShortDate = monday.Format(post.date.In(config.TimeZoneLocation).Local(),
monday.MediumFormatsByLocale[locale], locale)
dirpath := filepath.Join(config.TempPath, post.filepath)
if err = os.MkdirAll(dirpath, 0755); err != nil {
return
}
var f *os.File
f, err = os.Create(filepath.Join(dirpath, post.filenameHTML))
if err != nil {
return
}
defer f.Close()
pd := &postPageData{config.YMLConfig, *post}
// header
if err = templates.Header.Execute(f, pd); err != nil {
return
}
// body
if err = templates.Post.Execute(f, pd); err != nil {
return
}
// footer
if err = templates.Footer.Execute(f, pd); err != nil {
return
}
} else {
fmt.Printf("| Skipped %s (publish = false)\n", post.filename)
}
return
}
// SpewPosts generate site posts
func SpewPosts(templates *Templates) ([]*Post, error) {
path := config.PostsPath
fmt.Printf("| Indexing posts from %s...\n", path)
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
posts := make([]*Post, 0, len(files))
for _, file := range files {
ext := filepath.Ext(file.Name())
if !file.IsDir() && isExtOk(ext) {
fmt.Println("|--> ", file.Name())
filenameClean := strings.ReplaceAll(file.Name(), ext, "")[11:]
post := new(Post)
post.filename = file.Name()
post.filenameHTML = fmt.Sprintf("%s.html", filenameClean)
dirs := strings.Split(post.filename[:10], "-")
if len(dirs) != 3 {
return nil, fmt.Errorf("%s unexpected date prefix. YYYY-mm-dd required", post.filename)
}
post.filepath = filepath.Join(dirs[0], dirs[1], dirs[2])
post.date, err = time.Parse(layout, post.filename[:10]+" 00:00:00")
if err != nil {
return nil, err
}
post.IsIndex = false
post.PermalinkURL = fmt.Sprintf("%s/%s/%s", config.YMLConfig.Site.URL, post.filepath,
post.filenameHTML)
post.Permalink = template.URL(post.Permalink)
post.Title = strings.ReplaceAll(filenameClean, "-", " ")
posts = append(posts, post)
}
}
fmt.Println("| Generating posts...")
// sort by ascending date
sort.Slice(posts, func(a, b int) bool {
return posts[a].date.Before(posts[b].date)
})
var prev *Post
for _, post := range posts {
fmt.Println("|--> ", post.filename)
post.Prev = prev
data, err := ioutil.ReadFile(filepath.Join(path, post.filename))
if err != nil {
return nil, err
}
if err = writePost(post, data, templates); err != nil {
return nil, err
}
if post.IsPublish {
prev = post
}
}
fmt.Println("| Generating index...")
index := posts[len(posts)-1]
index.filenameHTML = "index.html"
index.filepath = ""
index.IsIndex = true
data, err := ioutil.ReadFile(filepath.Join(path, index.filename))
if err != nil {
return nil, err
}
if err = writePost(index, data, templates); err != nil {
return nil, err
}
// sort by descending date
for i := len(posts)/2 - 1; i >= 0; i-- {
tmp := len(posts) - 1 - i
posts[i], posts[tmp] = posts[tmp], posts[i]
}
return posts, nil
}