hugo/hugolib/site.go

703 lines
16 KiB
Go
Raw Normal View History

2013-07-04 15:32:55 +00:00
// 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"
"errors"
2013-07-04 15:32:55 +00:00
"fmt"
"github.com/spf13/hugo/target"
2013-07-04 15:32:55 +00:00
"github.com/spf13/nitro"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
var DefaultTimer = nitro.Initalize()
2013-07-04 15:32:55 +00:00
type Site struct {
Config Config
Pages Pages
Tmpl *template.Template
Indexes IndexList
Files []string
Sections Index
Info SiteInfo
Shortcodes map[string]ShortcodeFunc
timer *nitro.B
Target target.Publisher
2013-07-04 15:32:55 +00:00
}
type SiteInfo struct {
BaseUrl template.URL
Indexes OrderedIndexList
2013-07-04 15:32:55 +00:00
Recent *Pages
LastChange time.Time
Title string
2013-07-26 13:51:07 +00:00
Config *Config
2013-07-04 15:32:55 +00:00
}
func (s *Site) getFromIndex(kind string, name string) Pages {
return s.Indexes[kind][name]
}
func (s *Site) timerStep(step string) {
if s.timer == nil {
s.timer = DefaultTimer
}
s.timer.Step(step)
2013-07-04 15:32:55 +00:00
}
func (s *Site) Build() (err error) {
if err = s.Process(); err != nil {
return
}
if err = s.Render(); err != nil {
fmt.Printf("Error rendering site: %s\n", err)
fmt.Printf("Available templates:")
for _, template := range s.Tmpl.Templates() {
fmt.Printf("\t%s\n", template.Name())
}
return
}
s.Write()
return nil
2013-07-04 15:32:55 +00:00
}
func (s *Site) Analyze() {
s.Process()
s.checkDescriptions()
2013-07-04 15:32:55 +00:00
}
func (s *Site) Process() (err error) {
s.initialize()
s.prepTemplates()
s.timerStep("initialize & template prep")
s.CreatePages()
s.setupPrevNext()
s.timerStep("import pages")
if err = s.BuildSiteMeta(); err != nil {
return
}
s.timerStep("build indexes")
return
2013-07-04 15:32:55 +00:00
}
func (s *Site) Render() (err error) {
s.RenderAliases()
s.timerStep("render and write aliases")
s.ProcessShortcodes()
s.timerStep("render shortcodes")
s.AbsUrlify()
s.timerStep("absolute URLify")
if err = s.RenderIndexes(); err != nil {
return
}
s.RenderIndexesIndexes()
s.timerStep("render and write indexes")
s.RenderLists()
s.timerStep("render and write lists")
if err = s.RenderPages(); err != nil {
return
}
s.timerStep("render pages")
if err = s.RenderHomePage(); err != nil {
return
}
s.timerStep("render and write homepage")
return
2013-07-04 15:32:55 +00:00
}
func (s *Site) Write() {
s.WritePages()
s.timerStep("write pages")
2013-07-04 15:32:55 +00:00
}
func (s *Site) checkDescriptions() {
for _, p := range s.Pages {
2013-07-04 15:32:55 +00:00
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)
2013-08-10 14:35:34 +00:00
s.Tmpl = templates
s.primeTemplates()
s.loadTemplates()
}
func (s *Site) loadTemplates() {
2013-07-04 15:32:55 +00:00
walker := func(path string, fi os.FileInfo, err error) error {
if err != nil {
PrintErr("Walker: ", err)
return nil
}
if !fi.IsDir() {
if ignoreDotFile(path) {
return nil
}
2013-07-04 15:32:55 +00:00
filetext, err := ioutil.ReadFile(path)
if err != nil {
return err
}
s.addTemplate(s.generateTemplateNameFrom(path), string(filetext))
2013-07-04 15:32:55 +00:00
}
return nil
}
filepath.Walk(s.absLayoutDir(), walker)
}
func (s *Site) addTemplate(name, tmpl string) (err error) {
_, err = s.Tmpl.New(name).Parse(tmpl)
return
}
func (s *Site) generateTemplateNameFrom(path string) (name string) {
name = filepath.ToSlash(path[len(s.absLayoutDir())+1:])
return
2013-08-10 14:35:34 +00:00
}
2013-07-04 15:32:55 +00:00
2013-08-10 14:35:34 +00:00
func (s *Site) primeTemplates() {
alias := "<!DOCTYPE html>\n <html>\n <head>\n <link rel=\"canonical\" href=\"{{ .Permalink }}\"/>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta http-equiv=\"refresh\" content=\"0;url={{ .Permalink }}\" />\n </head>\n </html>"
alias_xhtml := "<!DOCTYPE html>\n <html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <link rel=\"canonical\" href=\"{{ .Permalink }}\"/>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta http-equiv=\"refresh\" content=\"0;url={{ .Permalink }}\" />\n </head>\n </html>"
2013-08-10 14:35:34 +00:00
s.addTemplate("alias", alias)
s.addTemplate("alias-xhtml", alias_xhtml)
2013-07-04 15:32:55 +00:00
}
func (s *Site) initialize() {
s.checkDirectories()
staticDir := s.Config.GetAbsPath(s.Config.StaticDir + "/")
2013-07-04 15:32:55 +00:00
walker := func(path string, fi os.FileInfo, err error) error {
if err != nil {
PrintErr("Walker: ", err)
return nil
}
if fi.IsDir() {
if path == staticDir {
return filepath.SkipDir
}
2013-07-04 15:32:55 +00:00
return nil
} else {
if ignoreDotFile(path) {
return nil
}
s.Files = append(s.Files, path)
2013-07-04 15:32:55 +00:00
return nil
}
}
filepath.Walk(s.absContentDir(), walker)
2013-08-13 12:43:42 +00:00
s.Info = SiteInfo{
BaseUrl: template.URL(s.Config.BaseUrl),
Title: s.Config.Title,
Recent: &s.Pages,
Config: &s.Config,
}
2013-07-04 15:32:55 +00:00
s.Shortcodes = make(map[string]ShortcodeFunc)
}
func ignoreDotFile(path string) bool {
return filepath.Base(path)[0] == '.'
}
func (s *Site) absLayoutDir() string {
return s.Config.GetAbsPath(s.Config.LayoutDir)
}
func (s *Site) absContentDir() string {
return s.Config.GetAbsPath(s.Config.ContentDir)
}
func (s *Site) absPublishDir() string {
return s.Config.GetAbsPath(s.Config.PublishDir)
}
2013-07-04 15:32:55 +00:00
func (s *Site) checkDirectories() {
if b, _ := dirExists(s.absLayoutDir()); !b {
FatalErr("No layout directory found, expecting to find it at " + s.absLayoutDir())
2013-07-04 15:32:55 +00:00
}
if b, _ := dirExists(s.absContentDir()); !b {
FatalErr("No source directory found, expecting to find it at " + s.absContentDir())
2013-07-04 15:32:55 +00:00
}
mkdirIf(s.absPublishDir())
2013-07-04 15:32:55 +00:00
}
func (s *Site) ProcessShortcodes() {
for i, _ := range s.Pages {
s.Pages[i].Content = HTML(ShortcodesHandle(string(s.Pages[i].Content), s.Pages[i], s.Tmpl))
2013-07-04 15:32:55 +00:00
}
}
func (s *Site) AbsUrlify() {
baseWithoutTrailingSlash := strings.TrimRight(s.Config.BaseUrl, "/")
baseWithSlash := baseWithoutTrailingSlash + "/"
for i, _ := range s.Pages {
content := string(s.Pages[i].Content)
content = strings.Replace(content, " src=\"/", " src=\""+baseWithSlash, -1)
content = strings.Replace(content, " src='/", " src='"+baseWithSlash, -1)
content = strings.Replace(content, " href='/", " href='"+baseWithSlash, -1)
content = strings.Replace(content, " href=\"/", " href=\""+baseWithSlash, -1)
content = strings.Replace(content, baseWithoutTrailingSlash+"//", baseWithSlash, -1)
s.Pages[i].Content = HTML(content)
}
}
2013-07-04 15:32:55 +00:00
func (s *Site) CreatePages() {
for _, fileName := range s.Files {
page := NewPage(fileName)
page.Site = s.Info
page.Tmpl = s.Tmpl
_ = s.setUrlPath(page)
page.Initalize()
s.setOutFile(page)
if s.Config.BuildDrafts || !page.Draft {
2013-07-04 15:32:55 +00:00
s.Pages = append(s.Pages, page)
}
}
s.Pages.Sort()
}
2013-08-02 20:30:26 +00:00
func (s *Site) setupPrevNext() {
for i, _ := range s.Pages {
if i < len(s.Pages)-1 {
s.Pages[i].Next = s.Pages[i+1]
}
if i > 0 {
s.Pages[i].Prev = s.Pages[i-1]
}
}
}
func (s *Site) setUrlPath(p *Page) error {
y := strings.TrimPrefix(p.FileName, s.Config.GetAbsPath(s.Config.ContentDir))
x := strings.Split(y, string(os.PathSeparator))
if len(x) <= 1 {
return errors.New("Zero length page name")
}
p.Section = strings.Trim(x[1], "/\\")
p.Path = strings.Trim(strings.Join(x[:len(x)-1], string(os.PathSeparator)), "/\\")
return nil
}
// If Url is provided it is assumed to be the complete relative path
// and will override everything
// Otherwise path + slug is used if provided
// Lastly path + filename is used if provided
func (s *Site) setOutFile(p *Page) {
// Always use Url if it's specified
if len(strings.TrimSpace(p.Url)) > 2 {
p.OutFile = strings.TrimSpace(p.Url)
if strings.HasSuffix(p.OutFile, "/") {
p.OutFile = p.OutFile + "index.html"
}
return
}
var outfile string
if len(strings.TrimSpace(p.Slug)) > 0 {
// Use Slug if provided
if s.Config.UglyUrls {
2013-08-13 21:58:50 +00:00
outfile = strings.TrimSpace(p.Slug) + "." + p.Extension
} else {
2013-08-13 21:58:50 +00:00
outfile = filepath.Join(strings.TrimSpace(p.Slug), "index."+p.Extension)
}
} else {
// Fall back to filename
_, t := filepath.Split(p.FileName)
if s.Config.UglyUrls {
outfile = replaceExtension(strings.TrimSpace(t), p.Extension)
} else {
file, _ := fileExt(strings.TrimSpace(t))
2013-08-13 21:58:50 +00:00
outfile = filepath.Join(file, "index."+p.Extension)
}
}
p.OutFile = p.Path + string(os.PathSeparator) + strings.TrimSpace(outfile)
}
func (s *Site) BuildSiteMeta() (err error) {
2013-07-04 15:32:55 +00:00
s.Indexes = make(IndexList)
s.Sections = make(Index)
for _, plural := range s.Config.Indexes {
2013-07-04 15:32:55 +00:00
s.Indexes[plural] = make(Index)
for i, p := range s.Pages {
vals := p.GetParam(plural)
if vals != nil {
v, ok := vals.([]string)
if ok {
for _, idx := range v {
s.Indexes[plural].Add(idx, s.Pages[i])
}
} else {
PrintErr("Invalid " + plural + " in " + p.File.FileName)
2013-07-04 15:32:55 +00:00
}
}
}
for k, _ := range s.Indexes[plural] {
s.Indexes[plural][k].Sort()
}
}
for i, p := range s.Pages {
s.Sections.Add(p.Section, s.Pages[i])
2013-07-04 15:32:55 +00:00
}
for k, _ := range s.Sections {
s.Sections[k].Sort()
}
s.Info.Indexes = s.Indexes.BuildOrderedIndexList()
if len(s.Pages) == 0 {
return
}
2013-07-04 15:32:55 +00:00
s.Info.LastChange = s.Pages[0].Date
// populate pages with site metadata
for _, p := range s.Pages {
p.Site = s.Info
}
return
2013-07-04 15:32:55 +00:00
}
2013-08-13 17:46:05 +00:00
func (s *Site) possibleIndexes() (indexes []string) {
for _, p := range s.Pages {
for k, _ := range p.Params {
if !inStringArray(indexes, k) {
indexes = append(indexes, k)
}
}
}
return
}
func inStringArray(arr []string, el string) bool {
for _, v := range arr {
if v == el {
return true
}
}
return false
}
2013-08-10 14:35:34 +00:00
func (s *Site) RenderAliases() error {
for i, p := range s.Pages {
for _, a := range p.Aliases {
t := "alias"
if strings.HasSuffix(a, ".xhtml") {
t = "alias-xhtml"
}
content, err := s.RenderThing(s.Pages[i], t)
2013-08-10 14:35:34 +00:00
if strings.HasSuffix(a, "/") {
a = a + "index.html"
}
if err != nil {
return err
}
2013-08-31 04:24:25 +00:00
err = s.WritePublic(a, content.Bytes())
if err != nil {
return err
}
2013-08-10 14:35:34 +00:00
}
}
return nil
}
func (s *Site) RenderPages() error {
2013-07-04 15:32:55 +00:00
for i, _ := range s.Pages {
content, err := s.RenderThingOrDefault(s.Pages[i], s.Pages[i].Layout(), "_default/single.html")
if err != nil {
return err
}
s.Pages[i].RenderedContent = content
2013-07-04 15:32:55 +00:00
}
return nil
2013-07-04 15:32:55 +00:00
}
2013-08-31 04:24:25 +00:00
func (s *Site) WritePages() (err error) {
2013-07-04 15:32:55 +00:00
for _, p := range s.Pages {
2013-08-31 04:24:25 +00:00
err = s.WritePublic(p.OutFile, p.RenderedContent.Bytes())
if err != nil {
return
}
2013-07-04 15:32:55 +00:00
}
2013-08-31 04:24:25 +00:00
return
2013-07-04 15:32:55 +00:00
}
func (s *Site) RenderIndexes() error {
for singular, plural := range s.Config.Indexes {
2013-07-04 15:32:55 +00:00
for k, o := range s.Indexes[plural] {
n := s.NewNode()
n.Title = strings.Title(k)
url := Urlize(plural + "/" + k)
plink := url
if s.Config.UglyUrls {
n.Url = url + ".html"
plink = n.Url
} else {
n.Url = url + "/index.html"
}
n.Permalink = HTML(MakePermalink(string(n.Site.BaseUrl), string(plink)))
n.RSSlink = HTML(MakePermalink(string(n.Site.BaseUrl), string(url+".xml")))
2013-07-04 15:32:55 +00:00
n.Date = o[0].Date
n.Data[singular] = o
n.Data["Pages"] = o
layout := "indexes/" + singular + ".html"
x, err := s.RenderThing(n, layout)
if err != nil {
return err
}
var base string
if s.Config.UglyUrls {
base = plural + "/" + k
} else {
base = plural + "/" + k + "/" + "index"
}
2013-08-31 04:24:25 +00:00
err = s.WritePublic(base+".html", x.Bytes())
if err != nil {
return err
}
2013-07-04 15:32:55 +00:00
if a := s.Tmpl.Lookup("rss.xml"); a != nil {
// XML Feed
y := s.NewXMLBuffer()
if s.Config.UglyUrls {
n.Url = Urlize(plural + "/" + k + ".xml")
} else {
n.Url = Urlize(plural + "/" + k + "/" + "index.xml")
}
n.Permalink = HTML(string(n.Site.BaseUrl) + n.Url)
2013-07-04 15:32:55 +00:00
s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
2013-08-31 04:24:25 +00:00
err = s.WritePublic(base+".xml", y.Bytes())
if err != nil {
return err
}
2013-07-04 15:32:55 +00:00
}
}
}
return nil
2013-07-04 15:32:55 +00:00
}
func (s *Site) RenderIndexesIndexes() (err error) {
layout := "indexes/indexes.html"
if s.Tmpl.Lookup(layout) != nil {
for singular, plural := range s.Config.Indexes {
n := s.NewNode()
n.Title = strings.Title(plural)
url := Urlize(plural)
n.Url = url + "/index.html"
n.Permalink = HTML(MakePermalink(string(n.Site.BaseUrl), string(n.Url)))
n.Data["Singular"] = singular
n.Data["Plural"] = plural
n.Data["Index"] = s.Indexes[plural]
n.Data["OrderedIndex"] = s.Info.Indexes[plural]
x, err := s.RenderThing(n, layout)
2013-08-31 04:24:25 +00:00
if err != nil {
return err
}
err = s.WritePublic(plural+"/index.html", x.Bytes())
if err != nil {
return err
}
}
}
return
}
func (s *Site) RenderLists() error {
2013-07-04 15:32:55 +00:00
for section, data := range s.Sections {
n := s.NewNode()
n.Title = strings.Title(inflect.Pluralize(section))
n.Url = Urlize(section + "/" + "index.html")
n.Permalink = HTML(MakePermalink(string(n.Site.BaseUrl), string(n.Url)))
n.RSSlink = HTML(MakePermalink(string(n.Site.BaseUrl), string(section+".xml")))
2013-07-04 15:32:55 +00:00
n.Date = data[0].Date
n.Data["Pages"] = data
layout := "indexes/" + section + ".html"
2013-07-04 15:32:55 +00:00
content, err := s.RenderThingOrDefault(n, layout, "_default/index.html")
if err != nil {
return err
}
2013-08-31 04:24:25 +00:00
err = s.WritePublic(section+"/index.html", content.Bytes())
if err != nil {
return err
}
2013-07-04 15:32:55 +00:00
if a := s.Tmpl.Lookup("rss.xml"); a != nil {
// XML Feed
2013-08-13 02:01:23 +00:00
if s.Config.UglyUrls {
2013-08-13 12:43:42 +00:00
n.Url = Urlize(section + ".xml")
2013-08-13 02:01:23 +00:00
} else {
2013-08-13 12:43:42 +00:00
n.Url = Urlize(section + "/" + "index.xml")
2013-08-13 02:01:23 +00:00
}
n.Permalink = HTML(string(n.Site.BaseUrl) + n.Url)
2013-07-04 15:32:55 +00:00
y := s.NewXMLBuffer()
s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
2013-08-31 04:24:25 +00:00
err = s.WritePublic(section+"/index.xml", y.Bytes())
return err
2013-07-04 15:32:55 +00:00
}
}
return nil
2013-07-04 15:32:55 +00:00
}
func (s *Site) RenderHomePage() error {
2013-07-04 15:32:55 +00:00
n := s.NewNode()
n.Title = n.Site.Title
2013-07-04 15:32:55 +00:00
n.Url = Urlize(string(n.Site.BaseUrl))
n.RSSlink = HTML(MakePermalink(string(n.Site.BaseUrl), string("index.xml")))
n.Permalink = HTML(string(n.Site.BaseUrl))
if len(s.Pages) > 0 {
n.Date = s.Pages[0].Date
if len(s.Pages) < 9 {
n.Data["Pages"] = s.Pages
} else {
n.Data["Pages"] = s.Pages[:9]
}
2013-07-04 15:32:55 +00:00
}
x, err := s.RenderThing(n, "index.html")
if err != nil {
return err
}
2013-08-31 04:24:25 +00:00
err = s.WritePublic("index.html", x.Bytes())
if err != nil {
return err
}
2013-07-04 15:32:55 +00:00
if a := s.Tmpl.Lookup("rss.xml"); a != nil {
// XML Feed
n.Url = Urlize("index.xml")
n.Title = "Recent Content"
n.Permalink = HTML(string(n.Site.BaseUrl) + "index.xml")
2013-07-04 15:32:55 +00:00
y := s.NewXMLBuffer()
s.Tmpl.ExecuteTemplate(y, "rss.xml", n)
2013-08-31 04:24:25 +00:00
err = s.WritePublic("index.xml", y.Bytes())
return err
2013-07-04 15:32:55 +00:00
}
if a := s.Tmpl.Lookup("404.html"); a != nil {
n.Url = Urlize("404.html")
n.Title = "404 Page not found"
n.Permalink = HTML(string(n.Site.BaseUrl) + "404.html")
x, err := s.RenderThing(n, "404.html")
if err != nil {
return err
}
2013-08-31 04:24:25 +00:00
err = s.WritePublic("404.html", x.Bytes())
return err
}
return nil
2013-07-04 15:32:55 +00:00
}
func (s *Site) Stats() {
fmt.Printf("%d pages created \n", len(s.Pages))
for _, pl := range s.Config.Indexes {
fmt.Printf("%d %s index created\n", len(s.Indexes[pl]), pl)
2013-07-04 15:32:55 +00:00
}
}
2013-09-01 03:00:57 +00:00
func (s *Site) NewNode() (y Node) {
2013-07-04 15:32:55 +00:00
y.Data = make(map[string]interface{})
y.Site = s.Info
return y
}
func (s *Site) RenderThing(d interface{}, layout string) (*bytes.Buffer, error) {
if s.Tmpl.Lookup(layout) == nil {
return nil, errors.New(fmt.Sprintf("Layout not found: %s", layout))
}
2013-07-04 15:32:55 +00:00
buffer := new(bytes.Buffer)
err := s.Tmpl.ExecuteTemplate(buffer, layout, d)
return buffer, err
2013-07-04 15:32:55 +00:00
}
func (s *Site) RenderThingOrDefault(d interface{}, layout string, defaultLayout string) (*bytes.Buffer, error) {
content, err := s.RenderThing(d, layout)
if err != nil {
var err2 error
content, err2 = s.RenderThing(d, defaultLayout)
if err2 == nil {
return content, err2
}
}
return content, err
}
2013-07-04 15:32:55 +00:00
func (s *Site) NewXMLBuffer() *bytes.Buffer {
header := "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>\n"
return bytes.NewBufferString(header)
}
2013-08-31 04:24:25 +00:00
func (s *Site) WritePublic(path string, content []byte) (err error) {
if s.Target != nil {
2013-08-31 04:24:25 +00:00
return s.Target.Publish(path, bytes.NewReader(content))
}
if s.Config.Verbose {
fmt.Println(path)
2013-07-04 15:32:55 +00:00
}
path, filename := filepath.Split(path)
path = filepath.FromSlash(s.Config.GetAbsPath(filepath.Join(s.Config.PublishDir, path)))
2013-08-31 04:24:25 +00:00
err = mkdirIf(path)
2013-07-26 13:28:26 +00:00
if err != nil {
2013-08-31 04:24:25 +00:00
return
2013-07-26 13:28:26 +00:00
}
file, _ := os.Create(filepath.Join(path, filename))
2013-07-04 15:32:55 +00:00
defer file.Close()
2013-08-31 04:24:25 +00:00
_, err = file.Write(content)
return
2013-07-04 15:32:55 +00:00
}