forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
94 lines (76 loc) · 1.77 KB
/
templates.go
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
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
)
func templatesApply(path string) ([]string, error) {
metaName := filepath.Join(path, "metadata.yaml")
if !shared.PathExists(metaName) {
return nil, nil
}
// Parse the metadata.
content, err := ioutil.ReadFile(metaName)
if err != nil {
return nil, errors.Wrap(err, "Failed to read metadata")
}
metadata := new(api.ImageMetadata)
err = yaml.Unmarshal(content, &metadata)
if err != nil {
return nil, errors.Wrap(err, "Could not parse metadata.yaml")
}
// Go through the files and copy them into place.
files := []string{}
for tplPath, tpl := range metadata.Templates {
err = func(tplPath string, tpl *api.ImageMetadataTemplate) error {
filePath := filepath.Join(path, fmt.Sprintf("%s.out", tpl.Template))
if !shared.PathExists(filePath) {
return nil
}
var w *os.File
if shared.PathExists(tplPath) {
if tpl.CreateOnly {
return nil
}
// Open the existing file.
w, err = os.Create(tplPath)
if err != nil {
return errors.Wrap(err, "Failed to create template file")
}
} else {
// Create the directories leading to the file.
os.MkdirAll(filepath.Dir(tplPath), 0755)
// Create the file itself.
w, err = os.Create(tplPath)
if err != nil {
return err
}
// Fix mode.
w.Chmod(0644)
}
defer w.Close()
// Do the copy.
src, err := os.Open(filePath)
if err != nil {
return err
}
defer src.Close()
_, err = io.Copy(w, src)
if err != nil {
return err
}
files = append(files, tplPath)
return nil
}(tplPath, tpl)
if err != nil {
return nil, err
}
}
return files, nil
}