1
0
mirror of https://git.sr.ht/~adnano/kiln synced 2024-11-08 10:09:18 +01:00
kiln/main.go

115 lines
2.0 KiB
Go
Raw Normal View History

2020-09-22 22:42:14 +02:00
package main
import (
2021-04-11 22:00:29 +02:00
"flag"
"fmt"
2021-04-11 23:50:18 +02:00
"io"
"io/fs"
2020-09-22 22:42:14 +02:00
"log"
2021-04-11 23:50:18 +02:00
"os"
"path/filepath"
"strings"
2020-09-29 01:54:48 +02:00
)
2020-09-22 22:42:14 +02:00
func main() {
2021-04-11 22:00:29 +02:00
var (
task string
config string
)
flag.StringVar(&task, "t", "all", "the task to run")
flag.StringVar(&config, "c", "config.toml", "the configuration file to use")
flag.Parse()
2020-09-22 22:42:14 +02:00
2020-11-20 18:07:38 +01:00
// Load config
2021-04-11 22:00:29 +02:00
cfg, err := LoadConfig(config)
2021-03-20 07:02:36 +01:00
if err != nil {
2021-04-11 22:00:29 +02:00
log.Fatal(err)
2020-11-20 18:07:38 +01:00
}
2021-03-20 07:18:15 +01:00
if err := cfg.LoadTemplates("templates"); err != nil {
2021-04-11 22:00:29 +02:00
log.Fatal(err)
2020-10-01 04:14:10 +02:00
}
2021-04-11 22:00:29 +02:00
if err := run(cfg, task); err != nil {
log.Fatal(err)
}
}
func run(cfg *Config, taskName string) error {
switch taskName {
case "all":
return runAll(cfg)
default:
task, ok := cfg.Tasks[taskName]
if !ok {
return fmt.Errorf("run task %q: no such task", taskName)
}
2021-04-11 22:00:29 +02:00
return runTask(cfg, task)
}
}
func runAll(cfg *Config) error {
for _, task := range cfg.Tasks {
err := runTask(cfg, task)
if err != nil {
return err
}
2021-02-28 03:53:16 +01:00
}
2021-04-11 22:00:29 +02:00
return nil
}
2021-02-28 03:53:16 +01:00
2021-04-11 22:00:29 +02:00
func runTask(cfg *Config, task *Task) error {
// Load content
dir := NewDir("")
dir.inputExt = task.Input
dir.outputExt = task.Output
dir.templateExt = task.Template
if err := dir.read("content", ""); err != nil {
return err
}
dir.sort()
// Manipulate content
if err := dir.manipulate(cfg); err != nil {
return err
}
// Write content
if err := dir.write(task.Destination, task); err != nil {
return err
}
2021-04-11 23:50:18 +02:00
// Copy static files
if task.Static != "" {
err := copyAll(task.Static, task.Destination)
if err != nil {
return err
}
}
2020-09-22 22:42:14 +02:00
return nil
}
2021-04-11 23:50:18 +02:00
func copyAll(srcDir, dstDir string) error {
return filepath.Walk(srcDir, func(path string, info fs.FileInfo, err error) error {
if info.IsDir() {
// Do nothing
return nil
}
src, err := os.Open(path)
if err != nil {
return err
}
defer src.Close()
dstPath := filepath.Join(dstDir, strings.TrimPrefix(path, srcDir))
dst, err := os.Create(dstPath)
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
return err
}
return nil
})
}