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
|
package main
import (
"fmt"
"os"
"path/filepath"
"text/template"
)
func apply(args []string) error {
if len(args) != 0 {
return applyFiles(args)
}
names, err := getFileNames()
if err != nil {
return err
}
return applyFiles(names)
}
func applyFiles(names []string) error {
for _, name := range names {
fmt.Printf("applying %s\n", name)
if err := applyFile(name); err != nil {
return fmt.Errorf("could not apply %s: %v", name, err)
}
}
return nil
}
func applyFile(name string) error {
src := filepath.Join(base, "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()
if err != nil {
return err
}
d := filepath.Join(dest, name)
if err = os.MkdirAll(filepath.Dir(d), 0700); err != nil {
return err
}
out, err := os.OpenFile(d, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
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
}
func getFileNames() ([]string, error) {
var names []string
d := filepath.Join(base, "templates")
err := filepath.Walk(d, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
name, err := filepath.Rel(d, path)
if err != nil {
return err
}
names = append(names, name)
return nil
})
if err != nil {
return nil, err
}
return names, nil
}
|