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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
|
// Copyright © 2013 Steve Francia <spf@spf13.com>.
//
// Licensed under the Simple Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://opensource.org/licenses/Simple-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"bitbucket.org/pkg/inflect"
"bytes"
"fmt"
"github.com/spf13/nitro"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
//"sync"
)
const slash = string(os.PathSeparator)
type Site struct {
c Config
Pages Pages
Tmpl *template.Template
Indexes IndexList
Files []string
Directories []string
Sections Index
Info SiteInfo
Shortcodes map[string]ShortcodeFunc
timer *nitro.B
}
type SiteInfo struct {
BaseUrl template.URL
Indexes *OrderedIndexList
Recent *Pages
LastChange time.Time
Title string
Config *Config
}
func (s *Site) getFromIndex(kind string, name string) Pages {
return s.Indexes[kind][name]
}
func NewSite(config *Config) *Site {
return &Site{c: *config, timer: nitro.Initalize()}
}
func (site *Site) Build() {
site.Process()
site.Render()
site.Write()
}
func (site *Site) Analyze() {
site.Process()
site.checkDescriptions()
}
func (site *Site) Process() {
site.initialize()
site.prepTemplates()
site.timer.Step("initialize & template prep")
site.CreatePages()
site.timer.Step("import pages")
site.BuildSiteMeta()
site.timer.Step("build indexes")
}
func (site *Site) Render() {
site.ProcessShortcodes()
site.timer.Step("render shortcodes")
site.AbsUrlify()
site.timer.Step("absolute URLify")
site.RenderIndexes()
site.timer.Step("render and write indexes")
site.RenderLists()
site.timer.Step("render and write lists")
site.RenderPages()
site.timer.Step("render pages")
site.RenderHomePage()
site.timer.Step("render and write homepage")
}
func (site *Site) Write() {
site.WritePages()
site.timer.Step("write pages")
}
func (site *Site) checkDescriptions() {
for _, p := range site.Pages {
if len(p.Description) < 60 {
fmt.Print(p.FileName + " ")
}
}
}
func (s *Site) prepTemplates() {
var templates = template.New("")
funcMap := template.FuncMap{
"urlize": Urlize,
"gt": Gt,
"isset": IsSet,
"echoParam": ReturnWhenSet,
}
templates.Funcs(funcMap)
walker := func(path string, fi os.FileInfo, err error) error {
if err != nil {
PrintErr("Walker: ", err)
return nil
}
if !fi.IsDir() {
filetext, err := ioutil.ReadFile(path)
if err != nil {
return err
}
text := string(filetext)
name := path[len(s.c.GetAbsPath(s.c.LayoutDir))+1:]
t := templates.New(name)
template.Must(t.Parse(text))
}
return nil
}
filepath.Walk(s.c.GetAbsPath(s.c.LayoutDir), walker)
s.Tmpl = templates
}
func (s *Site) initialize() {
site := s
s.checkDirectories()
walker := func(path string, fi os.FileInfo, err error) error {
if err != nil {
PrintErr("Walker: ", err)
return nil
}
if fi.IsDir() {
site.Directories = append(site.Directories, path)
return nil
} else {
site.Files = append(site.Files, path)
return nil
}
return nil
}
filepath.Walk(s.c.GetAbsPath(s.c.ContentDir), walker)
s.Info = SiteInfo{BaseUrl: template.URL(s.c.BaseUrl), Title: s.c.Title, Config: &s.c}
s.Shortcodes = make(map[string]ShortcodeFunc)
}
func (s *Site) checkDirectories() {
if b, _ := dirExists(s.c.GetAbsPath(s.c.LayoutDir)); !b {
FatalErr("No layout directory found, expecting to find it at " + s.c.GetAbsPath(s.c.LayoutDir))
}
if b, _ := dirExists(s.c.GetAbsPath(s.c.ContentDir)); !b {
FatalErr("No source directory found, expecting to find it at " + s.c.GetAbsPath(s.c.ContentDir))
}
mkdirIf(s.c.GetAbsPath(s.c.PublishDir))
}
func (s *Site) ProcessShortcodes() {
for i, _ := range s.Pages {
s.Pages[i].Content = template.HTML(ShortcodesHandle(string(s.Pages[i].Content), s.Pages[i], s.Tmpl))
}
}
func (s *Site) AbsUrlify() {
for i, _ := range s.Pages {
content := string(s.Pages[i].Content)
content = strings.Replace(content, " src=\"/", " src=\""+s.c.BaseUrl+"/", -1)
content = strings.Replace(content, " src='/", " src='"+s.c.BaseUrl+"/", -1)
content = strings.Replace(content, " href='/", " href='"+s.c.BaseUrl+"/", -1)
content = strings.Replace(content, " href=\"/", " href=\""+s.c.BaseUrl+"/", -1)
s.Pages[i].Content = template.HTML(content)
}
}
func (s *Site) CreatePages() {
for _, fileName := range s.Files {
page := NewPage(fileName)
page.Site = s.Info
page.Tmpl = s.Tmpl
s.setOutFile(page)
if s.c.BuildDrafts || !page.Draft {
s.Pages = append(s.Pages, page)
}
}
s.Pages.Sort()
}
func (s *Site) BuildSiteMeta() {
s.Indexes = make(IndexList)
s.Sections = make(Index)
for _, plural := range s.c.Indexes {
s.Indexes[plural] = make(Index)
for i, p := range s.Pages {
vals := p.GetParam(plural)
if vals != nil {
for _, idx := range vals.([]string) {
s.Indexes[plural].Add(idx, s.Pages[i])
}
}
}
for k, _ := range s.Indexes[plural] {
s.Indexes[plural][k].Sort()
}
}
for i, p := range s.Pages {
sect := p.GetSection()
s.Sections.Add(sect, s.Pages[i])
}
for k, _ := range s.Sections {
s.Sections[k].Sort()
}
s.Info.Indexes = s.Indexes.BuildOrderedIndexList()
s.Info.LastChange = s.Pages[0].Date
}
func (s *Site) RenderPages() {
for i, _ := range s.Pages {
s.Pages[i].RenderedContent = s.RenderThing(s.Pages[i], s.Pages[i].Layout())
}
}
func (s *Site) WritePages() {
for _, p := range s.Pages {
s.WritePublic(p.Section+slash+p.OutFile, p.RenderedContent.Bytes())
}
}
func (s *Site) setOutFile(p *Page) {
if len(strings.TrimSpace(p.Slug)) > 0 {
// Use Slug if provided
if s.c.UglyUrls {
p.OutFile = strings.TrimSpace(p.Slug + "." + p.Extension)
} else {
p.OutFile = strings.TrimSpace(p.Slug + "/index.html")
}
} else if len(strings.TrimSpace(p.Url)) > 2 {
// Use Url if provided & Slug missing
p.OutFile = strings.TrimSpace(p.Url)
} else {
// Fall back to filename
_, t := filepath.Split(p.FileName)
if s.c.UglyUrls {
p.OutFile = replaceExtension(strings.TrimSpace(t), p.Extension)
} else {
file, _ := fileExt(strings.TrimSpace(t))
p.OutFile = file + "/index." + p.Extension
}
}
}
func (s *Site) RenderIndexes() {
for singular, plural := range s.c.Indexes {
for k, o := range s.Indexes[plural] {
n := s.NewNode()
n.Title = strings.Title(k)
url := Urlize(plural + "/" + k)
plink := url
if s.c.UglyUrls {
n.Url = url + ".html"
plink = n.Url
} else {
n.Url = url + "/index.html"
}
n.Permalink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(plink)))
n.RSSlink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(url+".xml")))
n.Date = o[0].Date
n.Data[singular] = o
n.Data["Pages"] = o
layout := "indexes" + slash + singular + ".html"
x := s.RenderThing(n, layout)
var base string
if s.c.UglyUrls {
base = plural + slash + k
} else {
base = plural + slash + k + slash + "index"
}
s.WritePublic(base+".html", x.Bytes())
if a := s.Tmpl.Lookup("rss.xml"); a != nil {
// XML Feed
y := s.NewXMLBuffer()
if s.c.UglyUrls {
n.Url = Urlize(plural + "/" + k + ".xml")
} else {
n.Url = Urlize(plural + "/" + k + "/index.xml")
}
n.Permalink = template.HTML(string(n.Site.BaseUrl) + n.Url)
s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
s.WritePublic(base+".xml", y.Bytes())
}
}
}
}
func (s *Site) RenderLists() {
for section, data := range s.Sections {
n := s.NewNode()
n.Title = strings.Title(inflect.Pluralize(section))
n.Url = Urlize(section + "/index.html")
n.Permalink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(n.Url)))
n.RSSlink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(section+".xml")))
n.Date = data[0].Date
n.Data["Pages"] = data
layout := "indexes/" + section + ".html"
x := s.RenderThing(n, layout)
s.WritePublic(section+slash+"index.html", x.Bytes())
if a := s.Tmpl.Lookup("rss.xml"); a != nil {
// XML Feed
n.Url = Urlize(section + ".xml")
n.Permalink = template.HTML(string(n.Site.BaseUrl) + n.Url)
y := s.NewXMLBuffer()
s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
s.WritePublic(section+slash+"index.xml", y.Bytes())
}
}
}
func (s *Site) RenderHomePage() {
n := s.NewNode()
n.Title = n.Site.Title
n.Url = Urlize(string(n.Site.BaseUrl))
n.RSSlink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string("index.xml")))
n.Permalink = template.HTML(string(n.Site.BaseUrl))
n.Date = s.Pages[0].Date
if len(s.Pages) < 9 {
n.Data["Pages"] = s.Pages
} else {
n.Data["Pages"] = s.Pages[:9]
}
x := s.RenderThing(n, "index.html")
s.WritePublic("index.html", x.Bytes())
if a := s.Tmpl.Lookup("rss.xml"); a != nil {
// XML Feed
n.Url = Urlize("index.xml")
n.Title = "Recent Content"
n.Permalink = template.HTML(string(n.Site.BaseUrl) + "index.xml")
y := s.NewXMLBuffer()
s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
s.WritePublic("index.xml", y.Bytes())
}
}
func (s *Site) Stats() {
fmt.Printf("%d pages created \n", len(s.Pages))
for _, pl := range s.c.Indexes {
fmt.Printf("%d %s created\n", len(s.Indexes[pl]), pl)
}
}
func (s *Site) NewNode() Node {
var y Node
y.Data = make(map[string]interface{})
y.Site = s.Info
return y
}
func (s *Site) RenderThing(d interface{}, layout string) *bytes.Buffer {
buffer := new(bytes.Buffer)
s.Tmpl.ExecuteTemplate(buffer, layout, d)
return buffer
}
func (s *Site) NewXMLBuffer() *bytes.Buffer {
header := "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>\n"
return bytes.NewBufferString(header)
}
func (s *Site) WritePublic(path string, content []byte) {
if s.c.Verbose {
fmt.Println(path)
}
path, filename := filepath.Split(path)
path = filepath.FromSlash(s.c.GetAbsPath(filepath.Join(s.c.PublishDir, path)))
err := mkdirIf(path)
if err != nil {
fmt.Println(err)
}
file, _ := os.Create(filepath.Join(path, filename))
defer file.Close()
file.Write(content)
}
|