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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
|
package file
import (
"bytes"
"fmt"
"log"
"os"
"os/user"
"strconv"
"strings"
"text/template"
"codeberg.org/snonux/gonf/internal/resource"
"codeberg.org/snonux/gonf/internal/resource/opt"
)
type File struct {
resource resource.Resource
path string
content string
source string // bare path, no "source://" prefix
user string
group string
mode os.FileMode
absent bool
}
// SetContent implements opt.Contented. Setting literal content clears any
// previously configured source, as the two are mutually exclusive.
func (f *File) SetContent(content string) {
f.content = content
f.source = ""
}
// SetSource implements opt.Sourced. Setting a source clears any previously
// configured literal content, as the two are mutually exclusive.
func (f *File) SetSource(source string) {
f.source = source
f.content = ""
}
// SetOwner implements opt.Owner.
func (f *File) SetOwner(user string) { f.user = user }
// SetGroup implements opt.Grouped.
func (f *File) SetGroup(group string) { f.group = group }
// SetMode implements opt.Moded.
func (f *File) SetMode(mode os.FileMode) { f.mode = mode }
// SetAbsent implements opt.Absentable.
func (f *File) SetAbsent() { f.absent = true }
func build(path string, opts ...opt.Option) (*File, error) {
curr, err := user.Current()
if err != nil {
return nil, fmt.Errorf("failed to get current user for default: %w", err)
}
f := &File{
path: path,
mode: 0o640,
user: curr.Username,
group: curr.Gid,
}
for _, o := range opts {
o(f)
}
return f, nil
}
// apply performs the idempotent OS work for f without registering a
// resource.
func (f *File) apply() error {
if f.absent {
return ensureAbsent(f.targetPath())
}
finalPath, content, err := f.resolve()
if err != nil {
return fmt.Errorf("failed to resolve content for %s: %w", f.path, err)
}
return f.ensureFile(finalPath, content)
}
// targetPath returns the actual on-disk path f writes to. It strips a
// trailing ".tmpl" suffix from the caller-given path whenever templating was
// triggered by a ".tmpl"-suffixed source, so a source foo.conf.tmpl never
// leaves a foo.conf.tmpl behind on disk — whether that source is written via
// a direct Have/Ensure call or delegated to from a directory source-tree
// copy, since both routes go through this same function.
func (f *File) targetPath() string {
if strings.HasSuffix(f.source, ".tmpl") {
return strings.TrimSuffix(f.path, ".tmpl")
}
return f.path
}
// shouldRenderTemplate reports whether content should be rendered through
// text/template: either the destination path or the source path ends in
// ".tmpl".
func (f *File) shouldRenderTemplate() bool {
return strings.HasSuffix(f.path, ".tmpl") || strings.HasSuffix(f.source, ".tmpl")
}
// resolve reads f's content (from source or literal content), renders it as
// a template if applicable, and returns the final on-disk path alongside the
// resulting bytes. Param is always the bare source path when source-based
// (never a "source://"-prefixed string), or the literal content when
// content-based — one definition used by both the single-file path and by
// dir's per-file delegation.
func (f *File) resolve() (string, []byte, error) {
var content []byte
param := f.content
if f.source != "" {
data, err := os.ReadFile(f.source)
if err != nil {
return "", nil, fmt.Errorf("failed to read source file %s: %w", f.source, err)
}
content = data
param = f.source
} else {
content = []byte(f.content)
}
if f.shouldRenderTemplate() {
rendered, err := f.applyTemplateToContent(content, param)
if err != nil {
return "", nil, err
}
content = rendered
}
return f.targetPath(), content, nil
}
func (f *File) applyTemplateToContent(content []byte, param string) ([]byte, error) {
data := make(map[string]string)
for _, env := range os.Environ() {
pair := strings.SplitN(env, "=", 2)
if len(pair) == 2 {
data[pair[0]] = pair[1]
}
}
data["Param"] = param
tmpl, err := template.New("resource").Parse(string(content))
if err != nil {
return nil, fmt.Errorf("template parse error: %w", err)
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, fmt.Errorf("template execute error: %w", err)
}
return buf.Bytes(), nil
}
func (f *File) applyAttributesTo(path string) error {
if err := os.Chmod(path, f.mode); err != nil {
return fmt.Errorf("failed to chmod %s to %v: %w", path, f.mode, err)
}
log.Printf("set mode %v for %s", f.mode, path)
uid, gid := -1, -1
if f.user != "" {
u, err := user.Lookup(f.user)
if err != nil {
return fmt.Errorf("failed to lookup user %s: %w", f.user, err)
}
uid, _ = strconv.Atoi(u.Uid)
}
if f.group != "" {
gidInt, err := strconv.Atoi(f.group)
if err != nil {
return fmt.Errorf("group must be numeric for now: %s", f.group)
}
gid = gidInt
}
if err := os.Chown(path, uid, gid); err != nil {
return fmt.Errorf("failed to chown %s to %s:%s: %w", path, f.user, f.group, err)
}
log.Printf("set owner %s:%s for %s", f.user, f.group, path)
return nil
}
func ensureAbsent(path string) error {
log.Printf("ensuring absent: %s", path)
if err := os.Remove(path); err != nil {
if os.IsNotExist(err) {
log.Printf("%s already absent", path)
return nil
}
return fmt.Errorf("failed to remove %s: %w", path, err)
}
log.Printf("removed %s", path)
return nil
}
// Ensure builds and applies the file resource described by opts, without
// registering it. Used by other resource packages (e.g. dir) to write an
// individual file without it becoming its own top-level resource.
func Ensure(path string, opts ...opt.Option) error {
_, err := build(path, opts...)
return err
}
func Have(path string, opts ...opt.Option) resource.Resource {
f, err := build(path, opts...)
if err != nil {
log.Fatalf("failed to apply file resource %s: %v", path, err)
}
f.resource = resource.Register("File", f.targetPath(),
resource.ApplierFunc(func() error { return f.apply() }))
return f.resource
}
func Absent(path string, opts ...opt.Option) resource.Resource {
opts = append(opts, opt.IsAbsent())
return Have(path, opts...)
}
|