aboutsummaryrefslogtreecommitdiff
path: root/apply.go
blob: 904ffef7359f287cff7da5a486de8a130c2a6e8d (plain)
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
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"text/template"
)

func apply(conf *Conf, args []string) error {
	if len(args) != 0 {
		return applyFiles(conf, args)
	}
	names, err := conf.FileNames()
	if err != nil {
		return err
	}
	return applyFiles(conf, names)
}

func applyFiles(conf *Conf, names []string) error {
	for _, name := range names {
		fmt.Printf("applying %s\n", name)
		if err := applyFile(conf, name); err != nil {
			return fmt.Errorf("could not apply %s: %v", name, err)
		}
	}
	return nil
}

func applyFile(conf *Conf, name string) error {
	src := filepath.Join(conf.Source, "templates", name)
	t, err := template.New(filepath.Base(name)).Funcs(buildFuncMap()).ParseFiles(src)
	if err != nil {
		return fmt.Errorf("could not build template: %v", err)
	}
	data, err := getTemplateData(conf)
	if err != nil {
		return err
	}
	dest := filepath.Join(conf.Dest, name)
	if err = os.MkdirAll(filepath.Dir(dest), 0700); err != nil {
		return err
	}
	srcInfo, err := os.Stat(src)
	if err != nil {
		return err
	}
	out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, srcInfo.Mode())
	if err != nil {
		return err
	}
	defer out.Close()
	if err = t.Execute(out, data); err != nil {
		return fmt.Errorf("could not execute template: %v", err)
	}
	return nil
}