forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplates.go
104 lines (84 loc) · 1.92 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
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
"github.com/canonical/lxd/shared"
"github.com/canonical/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 := os.ReadFile(metaName)
if err != nil {
return nil, fmt.Errorf("Failed to read metadata: %w", err)
}
metadata := new(api.ImageMetadata)
err = yaml.Unmarshal(content, &metadata)
if err != nil {
return nil, fmt.Errorf("Could not parse metadata.yaml: %w", err)
}
// 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, tpl.Template+".out")
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 fmt.Errorf("Failed to create template file: %w", err)
}
} else {
// Create the directories leading to the file.
err := os.MkdirAll(filepath.Dir(tplPath), 0755)
if err != nil {
return err
}
// Create the file itself.
w, err = os.Create(tplPath)
if err != nil {
return err
}
// Fix mode.
err = w.Chmod(0644)
if err != nil {
return err
}
}
defer func() { _ = w.Close() }()
// Do the copy.
src, err := os.Open(filePath)
if err != nil {
return err
}
defer func() { _ = src.Close() }()
_, err = io.Copy(w, src)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
files = append(files, tplPath)
return nil
}(tplPath, tpl)
if err != nil {
return nil, err
}
}
return files, nil
}