-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgen.go
182 lines (167 loc) · 5.3 KB
/
gen.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
package main
import (
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"github.com/eknkc/amber"
)
var (
postTpl *template.Template // The one and only compiled post template
postTplNm = "post.amber" // The amber post template file name (native Go are compiled using ParseGlob)
// Special files in the public directory, that must not be deleted
// If value is true, this must match the prefix of the file (HasPrefix())
specFiles = map[string]struct{}{
"favicon.ico": struct{}{},
"robots.txt": struct{}{},
"humans.txt": struct{}{},
"crossdomain.xml": struct{}{},
"apple-touch-icon.png": struct{}{},
"apple-touch-icon-114x114-precomposed.png": struct{}{},
"apple-touch-icon-144x144-precomposed.png": struct{}{},
"apple-touch-icon-57x57-precomposed.png": struct{}{},
"apple-touch-icon-72x72-precomposed.png": struct{}{},
"apple-touch-icon-precomposed.png": struct{}{},
}
)
// This type is a slice of *LongPost that implements the sort.Interface, to sort in PubTime order.
type sortableLongPost []*LongPost
func (s sortableLongPost) Len() int { return len(s) }
func (s sortableLongPost) Less(i, j int) bool { return s[i].PubTime.Before(s[j].PubTime) }
func (s sortableLongPost) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Filter cleans the slice of FileInfo to leave only `.md` files (markdown)
func Filter(fi []os.FileInfo) []os.FileInfo {
for i := 0; i < len(fi); {
if fi[i].IsDir() || filepath.Ext(fi[i].Name()) != ".md" {
fi[i], fi = fi[len(fi)-1], fi[:len(fi)-1]
} else {
i++
}
}
return fi
}
// Compile the Post template.
func compileTemplate() error {
ap := filepath.Join(TemplatesDir, postTplNm)
if _, err := os.Stat(ap); os.IsNotExist(err) {
// Amber post template does not exist, compile the native Go templates
postTpl, err = template.ParseGlob(filepath.Join(TemplatesDir, "*.html"))
if err != nil {
return fmt.Errorf("error parsing templates: %s", err)
}
postTplNm = "post" // TODO : Validate this...
} else {
c := amber.New()
if err := c.ParseFile(ap); err != nil {
return fmt.Errorf("error parsing templates: %s", err)
}
if postTpl, err = c.Compile(); err != nil {
return fmt.Errorf("error compiling templates: %s", err)
}
}
return nil
}
// Clear the public directory, ignoring special files, subdirectories, and hidden (dot) files.
func clearPublicDir() error {
// Clear the public directory, except subdirs and special files (favicon.ico)
fis, err := ioutil.ReadDir(PublicDir)
if err != nil {
return fmt.Errorf("error getting public directory files: %s", err)
}
for _, fi := range fis {
if !fi.IsDir() && !strings.HasPrefix(fi.Name(), ".") {
// Check for special files
if _, ok := specFiles[fi.Name()]; !ok {
err = os.Remove(filepath.Join(PublicDir, fi.Name()))
if err != nil {
return fmt.Errorf("error deleting file %s: %s", fi.Name(), err)
}
}
}
}
return nil
}
// Generate the whole site.
func generateSite() error {
// First compile the template(s)
if err := compileTemplate(); err != nil {
return err
}
// Now read the posts
fis, err := ioutil.ReadDir(PostsDir)
if err != nil {
return err
}
// Remove directories from the list, keep only .md files
fis = Filter(fis)
// Get all posts.
all := make(sortableLongPost, 0, len(fis))
for _, fi := range fis {
lp, err := newLongPost(fi)
if err == nil {
all = append(all, lp)
} else {
log.Printf("post skipped: %s; error: %s\n", fi.Name(), err)
}
}
// Then sort in reverse order (newer first)
sort.Sort(sort.Reverse(all))
// Slice to get only recent posts
recent := all[:Options.RecentPostsCount]
// Delete current public directory files
if err := clearPublicDir(); err != nil {
return err
}
// Generate the static files
for i, p := range all {
td := newTemplateData(p, i, recent, all)
if err := generateFile(td, i == 0); err != nil {
return err
}
}
// Generate the RSS feed
td := newTemplateData(nil, 0, recent, nil)
return generateRss(td)
}
// Creates the rss feed from the recent posts.
func generateRss(td *TemplateData) error {
r := NewRss(td.SiteName, td.TagLine, Options.BaseURL)
base, err := url.Parse(Options.BaseURL)
if err != nil {
return fmt.Errorf("error parsing base URL: %s", err)
}
for _, p := range td.Recent {
u, err := base.Parse(p.Slug)
if err != nil {
return fmt.Errorf("error parsing post URL: %s", err)
}
r.Channels[0].AppendItem(NewRssItem(p.Title, u.String(), p.Description, p.Author, "", p.PubTime))
}
return r.WriteToFile(filepath.Join(PublicDir, "rss"))
}
// Generate the static HTML file for the post identified by the index.
func generateFile(td *TemplateData, idx bool) error {
var w io.Writer
fw, err := os.Create(filepath.Join(PublicDir, td.Post.Slug))
if err != nil {
return fmt.Errorf("error creating static file %s: %s", td.Post.Slug, err)
}
defer fw.Close()
// If this is the newest file, also save as index.html
w = fw
if idx {
idxw, err := os.Create(filepath.Join(PublicDir, "index.html"))
if err != nil {
return fmt.Errorf("error creating static file index.html: %s", err)
}
defer idxw.Close()
w = io.MultiWriter(fw, idxw)
}
return postTpl.ExecuteTemplate(w, postTplNm, td)
}