-
Notifications
You must be signed in to change notification settings - Fork 1
/
post.go
304 lines (259 loc) · 6.74 KB
/
post.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"github.com/dimfeld/blackfriday"
"github.com/dimfeld/glog"
"hash/fnv"
"html/template"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
const PostTimeFormat string = "1/2/06 3:04PM -0700"
type PostList []*Post
type Post struct {
SourcePath string
Title string
Timestamp time.Time
Tags []string
Link string
Content []byte
}
func (p *Post) parseTags(line string) {
p.Tags = strings.Split(line, ",")
for i := range p.Tags {
p.Tags[i] = strings.Title(strings.TrimSpace(p.Tags[i]))
}
}
func (p *Post) readHeader(reader *bufio.Reader) (err error) {
line, err := reader.ReadString('\n')
if err != nil {
return
}
p.Title = strings.TrimSpace(string(line[0 : len(line)-1]))
line, err = reader.ReadString('\n')
if err != nil {
return
}
p.Timestamp, err = time.Parse(PostTimeFormat, strings.TrimSpace(line[0:len(line)-1]))
if err != nil {
return
}
// Read up to 2 optional lines
p.Tags = []string{}
for i := 0; i < 2; i++ {
line, err = reader.ReadString('\n')
if err != nil {
return
}
line = strings.TrimSpace(line)
if line == "" {
return nil
}
if strings.HasPrefix(line, "http://") {
if p.Link != "" {
return errors.New("More than one link in header")
}
p.Link = line
} else {
if len(p.Tags) != 0 {
return errors.New("More than one tags line in header")
}
p.parseTags(line)
}
}
line, err = reader.ReadString('\n')
if err != nil {
return
}
if len(line) != 1 {
return fmt.Errorf("Unexpected input after header: %s", string(line))
}
return nil
}
// NewPost reads a post from disk and returns a Post containing its data.
// If readContent is false, only the header of the post is read.
// The post format is:
// Title
// Date/Time
// Tags - optional
// Link - optional
//
// Markdown Content
func NewPost(filePath string, readContent bool) (p *Post, err error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()
p = &Post{}
p.SourcePath = filePath
reader := bufio.NewReader(f)
err = p.readHeader(reader)
if err != nil {
glog.Errorf("Error reading post %s: %s", filePath, err.Error())
return
}
if readContent {
buf := &bytes.Buffer{}
_, err = buf.ReadFrom(reader)
if err != nil {
return
}
p.Content = buf.Bytes()
}
return
}
func (p *Post) HTMLContent(atom bool) template.HTML {
htmlFlags := 0
htmlFlags |= blackfriday.HTML_USE_XHTML
htmlFlags |= blackfriday.HTML_FOOTNOTE_RETURN_LINKS
domain := ""
if atom {
domain = "http://" + config.Domain
if domain[len(domain)-1] == '/' {
domain = domain[0 : len(domain)-1]
}
} else {
htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
}
// Take the hash of the path, to form a prefix for the footnote links.
// This prevents duplicate anchors when multiple posts with footnotes are in a page.
hash := fnv.New32a()
hash.Write([]byte(p.SourcePath))
prefix := strconv.FormatInt(int64(hash.Sum32()), 36)
parameters := blackfriday.HtmlRendererParameters{
AbsolutePrefix: domain,
FootnoteAnchorPrefix: prefix,
FootnoteReturnLinkContents: `↩`,
}
renderer := blackfriday.HtmlRendererWithParameters(htmlFlags, "", "", parameters)
// set up the parser
extensions := 0
extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
extensions |= blackfriday.EXTENSION_TABLES
extensions |= blackfriday.EXTENSION_FENCED_CODE
extensions |= blackfriday.EXTENSION_AUTOLINK
extensions |= blackfriday.EXTENSION_STRIKETHROUGH
extensions |= blackfriday.EXTENSION_SPACE_HEADERS
extensions |= blackfriday.EXTENSION_HEADER_IDS
extensions |= blackfriday.EXTENSION_FOOTNOTES
content := blackfriday.Markdown(p.Content, renderer, extensions)
return template.HTML(content)
}
func LoadPostsFromPath(postPath string, readContent bool) (PostList, error) {
var outerErr error = nil
postList := make(PostList, 0, 15)
if glog.V(1) {
glog.Infoln("LoadPostsFromPath: Loading from", postPath)
}
err := filepath.Walk(postPath,
func(filePath string, info os.FileInfo, err error) error {
if info == nil {
return os.ErrNotExist
}
if info.IsDir() ||
path.Base(filePath)[0] == '.' ||
!strings.HasSuffix(filePath, ".md") {
// Skip directories, files starting with dot, and non-MD files.
return nil
}
if glog.V(1) {
glog.Infoln("LoadPostsFromPath: Loading", filePath)
}
newPost, err := NewPost(filePath, readContent)
if err == nil {
postList = append(postList, newPost)
} else {
glog.Errorf("Failed parsing post at %s: %s", filePath, err)
if outerErr == nil {
// Pass the error outward.
outerErr = err
}
}
return nil
})
if err != nil {
return nil, err
}
return postList, outerErr
}
func NewArchiveSpecList(postBase string) (ArchiveSpecList, error) {
// Get the post directory.
postDir, err := os.Open(postBase)
if err != nil {
return nil, err
}
postDirStat, err := postDir.Stat()
if err != nil || !postDirStat.IsDir() {
return nil, errors.New("Post path is not directory")
}
// Read out the list of year directories.
yearDirs, err := postDir.Readdir(0)
if err != nil {
glog.Warningln("Nothing in posts directory")
return nil, err
}
list := make(ArchiveSpecList, 0)
for _, yearDirStat := range yearDirs {
if !yearDirStat.IsDir() {
continue
}
yearDirName := yearDirStat.Name()
yearInt, err := strconv.Atoi(yearDirName)
if err != nil {
// This isn't a numeric path. Ignore it.
continue
}
yearDirPath := path.Join(postBase, yearDirName)
yearDir, err := os.Open(yearDirPath)
if err != nil {
// Probably the directory was deleted. Log and move on.
glog.Errorln("NewArchiveSpecList: Failed to open", yearDirPath)
continue
}
monthDirs, err := yearDir.Readdir(0)
if err != nil {
glog.Errorln("NewArchiveSpecList: Failed to read files from", yearDirPath)
}
for _, monthDirSpec := range monthDirs {
if !monthDirSpec.IsDir() {
continue
}
monthInt, err := strconv.Atoi(monthDirSpec.Name())
if err != nil {
// This isn't a numeric path. Ignore it.
continue
}
spec := time.Date(yearInt, time.Month(monthInt), 1, 1, 1, 1, 1, time.UTC)
list = append(list, ArchiveSpec(spec))
}
}
var sortObj sort.Interface = list
if config.ArchiveListNewestFirst {
sortObj = sort.Reverse(sortObj)
}
sort.Sort(sortObj)
return list, nil
}
func PostPath(base string, year int, month time.Month) string {
return path.Join(base, strconv.Itoa(year), fmt.Sprintf("%02d", int(month)))
}
func (l PostList) Less(i, j int) bool {
return l[i].Timestamp.Before(l[j].Timestamp)
}
func (l PostList) Len() int {
return len(l)
}
func (l PostList) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}