~adnano/kiln

ref: 4ca3833665cfad55238c1e2b24551764d0ae3464 kiln/config.go -rw-r--r-- 2.3 KiB
4ca38336Adnan Maolood Switch to other toml library a month ago
                                                                                
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
package main

import (
	"fmt"
	"os"
	"path"
	"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 {
	Input       string `toml:"input"`       // input file extension
	Output      string `toml:"output"`      // output file extension
	Template    string `toml:"template"`    // template file extension
	PostProcess string `toml:"postprocess"` // postprocess directive
	Destination string `toml:"destination"` // destination directory
	postProcess Format
}

func (t Task) Format(p *Page) (string, []byte) {
	if t.postProcess == nil {
		return path.Join(p.Path, "index"+t.Output), []byte(p.Content)
	}
	return t.postProcess.Format(p)
}

// LoadConfig loads the configuration from the provided path.
func LoadConfig(path string) (*Config, error) {
	c := new(Config)
	c.Feeds = make(map[string]string)
	c.Tasks = make(map[string]*Task)

	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	if _, err := toml.DecodeReader(f, c); err != nil {
		return nil, err
	}

	// Add default task
	// The toml library overwrites the map, so add default values after parsing
	if _, ok := c.Tasks["gemini"]; !ok {
		c.Tasks["gemini"] = &Task{
			Input:       ".gmi",
			Output:      ".gmi",
			Template:    ".gmi",
			Destination: "public",
		}
	}

	for _, task := range c.Tasks {
		switch task.PostProcess {
		case "":
			continue
		case "geminiToHTML":
			task.postProcess = GeminiToHTML(c)
		default:
			return nil, fmt.Errorf("unrecognized postprocess directive %q", task.PostProcess)
		}
	}

	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)
}