shitty-ssg/site/site.go

101 lines
1.9 KiB
Go
Raw Normal View History

2020-12-04 12:50:20 +01:00
package site
import (
"io/ioutil"
2020-12-31 13:28:09 +01:00
"os"
2020-12-04 12:50:20 +01:00
"path/filepath"
"git.sr.ht/~ewintr/shitty-ssg/pkg/adoc"
2020-12-04 12:50:20 +01:00
)
2020-12-31 13:28:09 +01:00
const dirMode = os.ModeDir | 0755
2020-12-04 12:50:20 +01:00
type StaticPage struct {
2020-12-04 16:52:25 +01:00
Name string
Path string
2020-12-04 12:50:20 +01:00
}
type Site struct {
resourcesPath string
config *SiteConfig
2020-12-04 12:50:20 +01:00
posts Posts
staticPages []*StaticPage
}
func New(config *SiteConfig, resourcesPath string) (*Site, error) {
if err := config.ParseTemplates(filepath.Join(resourcesPath, "template")); err != nil {
2020-12-04 12:50:20 +01:00
return &Site{}, err
}
return &Site{
resourcesPath: resourcesPath,
config: config,
posts: Posts{},
2020-12-04 16:52:25 +01:00
staticPages: []*StaticPage{},
2020-12-04 12:50:20 +01:00
}, nil
}
2020-12-04 16:52:25 +01:00
func (s *Site) AddStaticPage(staticPath string) {
s.staticPages = append(s.staticPages, &StaticPage{
Name: filepath.Base(staticPath),
Path: staticPath,
})
}
2020-12-04 12:50:20 +01:00
func (s *Site) AddFilePost(fPath string) error {
content, err := ioutil.ReadFile(fPath)
if err != nil {
return err
}
2021-04-15 06:46:30 +02:00
doc := adoc.New(string(content))
if !doc.Public {
return nil
}
post := NewPost(s.config, doc)
if post.Kind != KIND_INVALID {
s.posts = append(s.posts, post)
}
2020-12-04 12:50:20 +01:00
return nil
}
func (s *Site) RenderHTML(targetPath string) error {
posts := s.posts.Sort()
if err := resetTarget(targetPath); err != nil {
return err
}
if err := moveResources(targetPath, s.resourcesPath); err != nil {
return err
}
for _, tplConf := range s.config.TemplateConfigs {
if err := tplConf.Render(targetPath, tplConf.Template, posts, s.staticPages); err != nil {
return err
2020-12-04 12:50:20 +01:00
}
}
return nil
2020-12-04 12:50:20 +01:00
}
2020-12-31 13:28:09 +01:00
func resetTarget(targetPath string) error {
if err := os.RemoveAll(targetPath); err != nil {
return err
}
return os.Mkdir(targetPath, dirMode)
}
func moveResources(targetPath, resourcesPath string) error {
for _, dir := range []string{"css", "font"} {
srcPath := filepath.Join(resourcesPath, dir)
destPath := filepath.Join(targetPath, dir)
if err := copyFiles(filepath.Join(srcPath, "*"), destPath); err != nil {
return err
}
}
return nil
}