1
0
mirror of https://git.sr.ht/~adnano/kiln synced 2024-11-23 17:12:18 +01:00
kiln/config.go
2021-04-20 16:16:12 -04:00

89 lines
2.1 KiB
Go

package main
import (
"log"
"os"
"os/exec"
"path"
"strings"
"text/template"
"github.com/BurntSushi/toml"
)
// Config contains site configuration.
type Config struct {
Title string `toml:"title"` // site title
URLs []string `toml:"urls"` // site URLs
Feeds map[string]string `toml:"feeds"` // site feeds
Tasks map[string]*Task `toml:"tasks"` // site tasks
Templates *Templates `toml:"-"` // site templates
}
// Task represents a site build task.
type Task struct {
InputExt string `toml:"input_ext"` // input file extension
OutputExt string `toml:"output_ext"` // output file extension
TemplateExt string `toml:"template_ext"` // template file extension
PostProcess string `toml:"postprocess"` // postprocess command
StaticDir string `toml:"static_dir"` // static file directory
OutputDir string `toml:"output_dir"` // output directory
}
func (t Task) Format(p *Page) (string, []byte) {
path := path.Join(p.Path, "index"+t.OutputExt)
// Run a custom command.
if t.PostProcess != "" {
split := strings.Split(t.PostProcess, " ")
cmd := exec.Command(split[0], split[1:]...)
cmd.Stdin = strings.NewReader(p.Content)
cmd.Stderr = os.Stderr
output, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
return path, output
}
return path, []byte(p.Content)
}
// LoadConfig loads the configuration from the provided path.
func LoadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
c := &Config{}
if _, err := toml.DecodeReader(f, c); err != nil {
return nil, err
}
return c, nil
}
// LoadTemplates loads templates from the provided path.
func (c *Config) LoadTemplates(path string) error {
// Site contains site metadata passed to templates
type Site struct {
Title string
URLs []string
}
// Load templates
c.Templates = NewTemplates()
c.Templates.Funcs(template.FuncMap{
"site": func() Site {
return Site{
Title: c.Title,
URLs: c.URLs,
}
},
})
c.Templates.LoadDefault()
return c.Templates.Load(path)
}