forked from project-dalec/dalec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource_inline.go
More file actions
388 lines (330 loc) · 11.1 KB
/
source_inline.go
File metadata and controls
388 lines (330 loc) · 11.1 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package dalec
import (
"context"
goerrors "errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/goccy/go-yaml/ast"
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/frontend/dockerfile/shell"
"github.com/moby/buildkit/solver/errdefs"
"github.com/pkg/errors"
)
const (
// This is used as the source name for sources in specified in `SourceMount`
// For any sources we need to mount we need to give the source a name.
// We don't actually care about the name here *except* the way file-backed
// sources work the name of the file becomes the source name.
// So we at least need to track it.
// Source names must also not contain path separators or it can screw up the logic.
//
// To note, the name of the source affects how the source is cached, so this
// should just be a single specific name so we can get maximal cache re-use.
internalMountSourceName = "mount"
)
// SourceInlineFile is used to specify the content of an inline source.
type SourceInlineFile struct {
// Contents is the content.
Contents string `yaml:"contents,omitempty" json:"contents,omitempty"`
// Permissions is the octal file permissions to set on the file.
Permissions fs.FileMode `yaml:"permissions,omitempty" json:"permissions,omitempty"`
// UID is the user ID to set on the directory and all files and directories within it.
// UID must be greater than or equal to 0
UID int `yaml:"uid,omitempty" json:"uid,omitempty"`
// GID is the group ID to set on the directory and all files and directories within it.
// UID must be greater than or equal to 0
GID int `yaml:"gid,omitempty" json:"gid,omitempty"`
_sourceMap *sourceMap
_uidSourceMap *sourceMap
_gidSourceMap *sourceMap
}
func (s *SourceInlineFile) UnmarshalYAML(ctx context.Context, node ast.Node) error {
type internal struct {
Contents string `yaml:"contents,omitempty" json:"contents,omitempty"`
Permissions fs.FileMode `yaml:"permissions,omitempty" json:"permissions,omitempty"`
UID sourceMappedValue[int] `yaml:"uid,omitempty" json:"uid"`
GID sourceMappedValue[int] `yaml:"gid,omitempty" json:"gid"`
}
var i internal
dec := getDecoder(ctx)
if err := dec.DecodeFromNodeContext(ctx, node, &i); err != nil {
return errors.Wrap(err, "failed to decode inline file")
}
*s = SourceInlineFile{
Contents: i.Contents,
Permissions: i.Permissions,
UID: i.UID.Value,
GID: i.GID.Value,
}
s._sourceMap = newSourceMap(ctx, node)
s._uidSourceMap = i.UID.sourceMap
s._gidSourceMap = i.GID.sourceMap
return nil
}
// SourceInlineDir is used by by [SourceInline] to represent a filesystem directory.
type SourceInlineDir struct {
// Files is the list of files to include in the directory.
// The map key is the name of the file.
//
// Files with path separators in the key will be rejected.
Files map[string]*SourceInlineFile `yaml:"files,omitempty" json:"files,omitempty"`
// Permissions is the octal permissions to set on the directory.
Permissions fs.FileMode `yaml:"permissions,omitempty" json:"permissions,omitempty"`
// UID is the user ID to set on the directory and all files and directories within it.
// UID must be greater than or equal to 0
UID int `yaml:"uid,omitempty" json:"uid,omitempty"`
// GID is the group ID to set on the directory and all files and directories within it.
// UID must be greater than or equal to 0
GID int `yaml:"gid,omitempty" json:"gid,omitempty"`
_sourceMap *sourceMap
_gidSourceMap *sourceMap
_uidSourceMap *sourceMap
}
func (s *SourceInlineDir) UnmarshalYAML(ctx context.Context, node ast.Node) error {
type internal struct {
Files map[string]*SourceInlineFile `yaml:"files,omitempty" json:"files"`
Permissions fs.FileMode `yaml:"permissions,omitempty" json:"permissions"`
UID sourceMappedValue[int] `yaml:"uid,omitempty" json:"uid"`
GID sourceMappedValue[int] `yaml:"gid,omitempty" json:"gid"`
}
var i internal
dec := getDecoder(ctx)
if err := dec.DecodeFromNodeContext(ctx, node, &i); err != nil {
return errors.Wrap(err, "failed to decode inline dir")
}
*s = SourceInlineDir{
Files: i.Files,
Permissions: i.Permissions,
UID: i.UID.Value,
GID: i.GID.Value,
}
s._sourceMap = newSourceMap(ctx, node)
s._uidSourceMap = i.UID.sourceMap
s._gidSourceMap = i.GID.sourceMap
return nil
}
// SourceInline is used to generate a source from inline content.
type SourceInline struct {
// File is the inline file to generate.
// File is treated as a literal single file.
// [SourceIsDir] will return false when this is set.
// This is mutually exclusive with [Dir]
File *SourceInlineFile `yaml:"file,omitempty" json:"file,omitempty"`
// Dir creates a directory with the given files and directories.
// [SourceIsDir] will return true when this is set.
// This is mutually exclusive with [File]
Dir *SourceInlineDir `yaml:"dir,omitempty" json:"dir,omitempty"`
_sourceMap *sourceMap
}
func (src *SourceInline) IsDir() bool {
return src.Dir != nil
}
const (
defaultFilePerms = 0o644
defaultDirPerms = 0o755
)
func (s *SourceInline) validate(opts fetchOptions) (retErr error) {
var errs []error
if s.File == nil && s.Dir == nil {
err := errors.New("inline source is missing contents to inline")
err = errdefs.WithSource(err, s._sourceMap.GetErrdefsSource())
errs = append(errs, err)
}
if s.File != nil && s.Dir != nil {
err := errors.New("inline source variant cannot have both a file and dir set")
err = errdefs.WithSource(err, s._sourceMap.GetErrdefsSource())
errs = append(errs, err)
}
if s.Dir != nil {
if err := s.Dir.validate(); err != nil {
errs = append(errs, err)
}
}
if s.File != nil {
if opts.Path != "" {
errs = append(errs, errors.New("inline file source cannot have a path set"))
}
if opts.Includes != nil {
errs = append(errs, errors.New("inline file source cannot have includes set"))
}
if opts.Excludes != nil {
errs = append(errs, errors.New("inline file source cannot have excludes set"))
}
if err := s.File.validate(); err != nil {
errs = append(errs, errors.Wrap(err, "inline file source validation failed"))
}
}
return goerrors.Join(errs...)
}
func (s *SourceInlineDir) validate() error {
var errs []error
if s.UID < 0 {
err := errors.Errorf("uid %d must be non-negative", s.UID)
err = errdefs.WithSource(err, s._uidSourceMap.GetErrdefsSource())
errs = append(errs, err)
}
if s.GID < 0 {
err := errors.Errorf("gid %d must be non-negative", s.GID)
err = errdefs.WithSource(err, s._gidSourceMap.GetErrdefsSource())
errs = append(errs, err)
}
for k, f := range s.Files {
if strings.ContainsRune(k, os.PathSeparator) {
errs = append(errs, errors.Wrapf(errSourceNamePathSeparator, "file %q", k))
}
if err := f.validate(); err != nil {
errs = append(errs, errors.Wrapf(err, "file %q", k))
}
}
return goerrors.Join(errs...)
}
func (s *SourceInlineFile) validate() error {
var errs []error
if s.UID < 0 {
err := errors.Errorf("uid %d must be non-negative", s.UID)
err = errdefs.WithSource(err, s._uidSourceMap.GetErrdefsSource())
errs = append(errs, err)
}
if s.GID < 0 {
err := errors.Errorf("gid %d must be non-negative", s.GID)
err = errdefs.WithSource(err, s._gidSourceMap.GetErrdefsSource())
errs = append(errs, err)
}
return goerrors.Join(errs...)
}
func (s *SourceInline) Doc(w io.Writer, name string) {
if s.File != nil {
s.File.Doc(w, name)
}
if s.Dir != nil {
s.Dir.Doc(w, name)
}
}
// Doc writes the information about the file to the writer.
func (s *SourceInlineFile) Doc(w io.Writer, name string) {
printDocLn(w, ` cat << EOF > `+name+`
`+s.Contents+`
EOF`)
if s.UID != 0 {
printDocLn(w, ` chown `+strconv.Itoa(s.UID)+" "+name)
}
if s.GID != 0 {
printDocLn(w, ` chgrp `+strconv.Itoa(s.GID)+" "+name)
}
perms := s.Permissions.Perm()
if perms == 0 {
perms = 0o644
}
printDocf(w, " chmod %o %s\n", perms.Perm(), name)
}
// Doc writes the information about the directory to the writer.
func (s *SourceInlineDir) Doc(w io.Writer, name string) {
printDocLn(w, ` mkdir -p `+name)
if s.UID != 0 {
printDocLn(w, ` chown `+strconv.Itoa(s.UID)+" "+name)
}
if s.GID != 0 {
printDocLn(w, ` chgrp `+strconv.Itoa(s.GID)+" "+name)
}
perms := s.Permissions.Perm()
if perms == 0 {
perms = 0o644
}
sorted := SortMapKeys(s.Files)
for _, k := range sorted {
v := s.Files[k]
v.Doc(w, filepath.Join(name, k))
}
printDocf(w, " chmod %o %s\n", perms.Perm(), name)
}
func (s *SourceInline) toState(opts fetchOptions) llb.State {
if s.File != nil {
return llb.Scratch().With(s.File.toState(opts))
}
return s.Dir.toState(opts)
}
func (s *SourceInline) toMount(opts fetchOptions) (llb.State, []llb.MountOption) {
if s.File != nil {
return s.File.toMount(opts)
}
return s.Dir.toMount(opts)
}
func (s *SourceInlineFile) toState(opts fetchOptions) llb.StateOption {
return func(in llb.State) llb.State {
if isRoot(opts.Rename) {
// If we are here, then something is very much not right and is almost
// certainly a dalec bug.
panic(fmt.Sprintf("invalid file name: %q", opts.Rename))
}
st := in.File(llb.Mkfile(opts.Rename, s.Permissions, []byte(s.Contents), llb.WithUIDGID(int(s.UID), int(s.GID))))
return st
}
}
func (s *SourceInlineFile) toMount(opts fetchOptions) (llb.State, []llb.MountOption) {
if isRoot(opts.Rename) {
opts.Rename = internalMountSourceName
}
// This is always a file, so to make sure we always mount a file instead of
// a directory we need to add a mount opt pointing at the file name.
mountOpts := []llb.MountOption{llb.SourcePath(opts.Rename)}
st := llb.Scratch().With(s.toState(opts))
return st, mountOpts
}
func (s *SourceInlineDir) toState(opts fetchOptions) llb.State {
base := s.baseState(opts)
// inline dir handles dir names and subpaths itself
// Do not pass rename to sourceFilters
opts.Rename = ""
return base.With(sourceFilters(opts))
}
func (s *SourceInlineDir) baseState(opts fetchOptions) llb.State {
st := llb.Scratch().File(llb.Mkdir(opts.Rename, s.Permissions, llb.WithUIDGID(int(s.UID), int(s.GID))))
sorted := SortMapKeys(s.Files)
for _, k := range sorted {
if !isRoot(opts.Path) && opts.Path != k {
continue
}
f := s.Files[k]
opts := opts
opts.Rename = filepath.Join(opts.Rename, k)
st = st.With(f.toState(opts))
}
return st
}
func (s *SourceInlineDir) toMount(opts fetchOptions) (llb.State, []llb.MountOption) {
st := s.toState(opts).With(mountFilters(opts))
return st, nil
}
func (s *SourceInlineFile) fillDefaults(_ []*SourceGenerator) {
if s.Permissions == 0 {
s.Permissions = defaultFilePerms
}
}
func (s *SourceInlineDir) fillDefaults(gen []*SourceGenerator) {
if s.Permissions == 0 {
s.Permissions = defaultDirPerms
}
for _, f := range s.Files {
f.fillDefaults(gen)
}
}
func (s *SourceInline) fillDefaults(gen []*SourceGenerator) {
if s.File != nil {
s.File.fillDefaults(gen)
}
if s.Dir != nil {
s.Dir.fillDefaults(gen)
}
}
func (s *SourceInline) processBuildArgs(lex *shell.Lex, args map[string]string, allowArg func(key string) bool) error {
return nil
}
func (src *SourceInline) doc(w io.Writer, name string) {
printDocLn(w, "Generated from an inline source:")
src.Doc(w, name)
}