-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblognow.go
289 lines (249 loc) · 6.82 KB
/
blognow.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// blognow is a CLI application for generating static blogs.
package main
import (
"bytes"
"errors"
"fmt"
"html/template"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/karrick/godirwalk"
"gitlab.com/golang-commonmark/markdown"
)
const sampleConfig string = `baseURL = "https://example.org/"
title = "My Blog"
tagline = "Don't sail too close to the wind"
dateFormat = "2 January 2006"
`
const samplePost string = `---
title = "My First Post"
date = 2019-05-05
---
Welcome to my blog!
# First things
- One
- Two
- Three
> This is a quote.
`
const postsDir string = "posts"
const outputDir string = "dist/"
type BlogInfo struct {
BaseURL string
Title string
Tagline string
DateFormat string
}
type Post struct {
Title string
Date time.Time
Slug string
Content template.HTML
}
type PostPageData struct {
Blog BlogInfo
Post Post
}
type ArchivePageData struct {
Blog BlogInfo
Years []int
YearGroups map[int][]Post
}
func main() {
if len(os.Args) == 1 {
fmt.Println("Building your blog...")
build()
fmt.Printf("Done. Output is in %s\n", outputDir)
os.Exit(0)
}
makeBlogDir(os.Args[1])
}
// makeBlogDir creates the initial directory with sample files.
func makeBlogDir(path string) {
postsPath := filepath.Join(path, postsDir)
templatesPath := filepath.Join(path, "templates")
os.MkdirAll(postsPath, os.ModePerm)
makeTemplates(templatesPath)
createFile(path+"/config.toml", sampleConfig)
createFile(postsPath+"/sample.md", samplePost)
fmt.Println("Created a new blog: " + path)
}
// build collects all the necessary information from configuration files
// and post files and builds the static site.
func build() {
os.Mkdir(outputDir, os.ModePerm)
// Get blog title, tagline, etc. from config.toml
blogInfo := blogInfo()
// These functions can be used inside templates.
fmap := template.FuncMap{
"formatDate": formatDate,
"formatArchiveDate": formatArchiveDate,
}
baseTemplate, err := template.New("").Funcs(fmap).ParseFiles(
"templates/base.html",
"templates/header.html",
)
check(err)
postTemplate, err := template.Must(baseTemplate.Clone()).ParseFiles(
"templates/post.html",
)
check(err)
// Iterate over all .md files in postsDir
posts := make([]Post, 0)
err = godirwalk.Walk(postsDir, &godirwalk.Options{
Callback: func(osPathname string, de *godirwalk.Dirent) error {
ext := filepath.Ext(osPathname)
if ext == ".md" {
// post.md -> Post struct
content, err := ioutil.ReadFile(osPathname)
check(err)
post := parse(string(content))
post.Slug = slug(post.Title)
posts = append(posts, post)
// Build output using template.
data := PostPageData{
Blog: blogInfo,
Post: post,
}
var postHTML bytes.Buffer
err = postTemplate.ExecuteTemplate(&postHTML, "base", data)
check(err)
os.Mkdir(outputDir+post.Slug, os.ModePerm)
createFile(outputDir+post.Slug+"/index.html", postHTML.String())
}
return nil
},
Unsorted: true,
})
check(err)
// Generate archive page.
tmpl, err := template.Must(baseTemplate.Clone()).ParseFiles(
"templates/archive.html",
)
check(err)
sort.Slice(posts, func(i, j int) bool {
return posts[i].Date.After(posts[j].Date)
})
// Group posts by years.
yearGroups := make(map[int][]Post)
for _, post := range posts {
yearGroups[post.Date.Year()] = append(yearGroups[post.Date.Year()], post)
}
// So that we can display the archive page post years newest to oldest.
years := make([]int, 0)
for key, _ := range yearGroups {
years = append(years, key)
}
sort.Sort(sort.Reverse(sort.IntSlice(years)))
archivePageData := ArchivePageData{
Blog: blogInfo,
Years: years,
YearGroups: yearGroups,
}
var archiveHTML bytes.Buffer
err = tmpl.ExecuteTemplate(&archiveHTML, "base", archivePageData)
check(err)
os.Mkdir(outputDir+"archive", os.ModePerm)
createFile(outputDir+"archive"+"/index.html", archiveHTML.String())
// Use the most recent post as the index page.
postPageData := PostPageData{
Blog: blogInfo,
Post: posts[0],
}
var postHTML bytes.Buffer
err = postTemplate.ExecuteTemplate(&postHTML, "base", postPageData)
check(err)
createFile(outputDir+"index.html", postHTML.String())
}
// makeTemplates outputs a default set of HTML templates in the directory
// specified by templatesPath.
func makeTemplates(templatesPath string) {
os.MkdirAll(templatesPath, os.ModePerm)
createFile(filepath.Join(templatesPath, "base.html"), baseTmpl)
createFile(filepath.Join(templatesPath, "header.html"), headerTmpl)
createFile(filepath.Join(templatesPath, "post.html"), postTmpl)
createFile(filepath.Join(templatesPath, "archive.html"), archiveTmpl)
}
// blogInfo reads a config.toml file and returns a BlogInfo struct.
func blogInfo() BlogInfo {
config, err := ioutil.ReadFile("config.toml")
check(err)
blogInfo := BlogInfo{}
_, err = toml.Decode(string(config), &blogInfo)
check(err)
return blogInfo
}
// parse creates a Post struct from a post file containing front matter and
// Markdown.
func parse(content string) Post {
post := Post{}
frontMatter, err := extractFrontMatter(content)
check(err)
_, err = toml.Decode(frontMatter, &post)
check(err)
post.Content = template.HTML(extractBody(content))
return post
}
// extractFrontMatter returns the front matter as a string given
// the entire contents of a post file.
func extractFrontMatter(content string) (string, error) {
frontMatter := ""
lines := strings.Split(content, "\n")
if len(lines) < 2 {
return frontMatter, errors.New("Error: Post file missing front matter")
}
for i := 1; i < len(lines); i++ {
if lines[i] == "---" {
break
} // End of front matter
frontMatter += lines[i] + "\n"
}
return frontMatter, nil
}
// extractBody takes the content of a post file, converts the Markdown in the
// content to an HTML string, and returns this string.
func extractBody(content string) string {
body := ""
lines := strings.Split(content, "\n")
for i, line := range lines {
if i < 4 {
continue
} // Skip past the front matter
// Since the blog and post title (h1 and h2, respectively) are added
// automatically, all other headings start two levels down.
if strings.HasPrefix(line, "#") {
line = "##" + line
}
body += line + "\n"
}
md := markdown.New()
return md.RenderToString([]byte(body))
}
func createFile(name string, content string) {
contentBytes := []byte(content)
err := ioutil.WriteFile(name, contentBytes, 0644)
check(err)
}
// slug turns a string into this-kind-of-format that can be used in a URL.
func slug(s string) string {
s = strings.ToLower(s)
s = strings.ReplaceAll(s, " ", "-")
return s
}
func formatDate(t time.Time) string {
return t.Format(blogInfo().DateFormat)
}
func formatArchiveDate(t time.Time) string {
return t.Format("02 Jan")
}
func check(e error) {
if e != nil {
log.Fatal("Error:", e)
}
}