package main import ( "flag" "fmt" "io" "io/fs" "log" "os" "path/filepath" "strings" ) var ( Version string ) func main() { var ( task string config string version bool ) flag.StringVar(&task, "t", "all", "the task to run") flag.StringVar(&config, "c", "config.toml", "the configuration file to use") flag.BoolVar(&version, "v", false, "print version") flag.Parse() if version { fmt.Println("kiln", Version) return } // Load config cfg, err := LoadConfig(config) if err != nil { log.Fatal(err) } if err := cfg.LoadTemplates("templates"); err != nil { log.Fatal(err) } 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) } return runTask(cfg, task) } } func runAll(cfg *Config) error { for _, task := range cfg.Tasks { err := runTask(cfg, task) if err != nil { return err } } return nil } func runTask(cfg *Config, task *Task) error { // Load content dir := NewDir("") dir.inputExt = task.InputExt dir.outputExt = task.OutputExt dir.templateExt = task.TemplateExt 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.OutputDir, task); err != nil { return err } // Copy static files if task.StaticDir != "" { err := copyAll(task.StaticDir, task.OutputDir) if err != nil { return err } } return nil } 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 }) }