Debian Codegraph @

builder.go

raw
1 package imagebuilder
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "log"
9 "os"
10 "path/filepath"
11 "runtime"
12 "slices"
13 "strconv"
14 "strings"
15
16 docker "github.com/fsouza/go-dockerclient"
17
18 buildkitparser "github.com/moby/buildkit/frontend/dockerfile/parser"
19 "github.com/openshift/imagebuilder/dockerfile/command"
20 "github.com/openshift/imagebuilder/dockerfile/parser"
21 )
22
23 // Copy defines a copy operation required on the container.
24 type Copy struct {
25 // If true, this is a copy from the file system to the container. If false,
26 // the copy is from the context.
27 FromFS bool
28 // If set, this is a copy from the named stage or image to the container.
29 From string
30 Src []string
31 Dest string
32 Download bool
33 // If set, the owner:group for the destination. This value is passed
34 // to the executor for handling.
35 Chown string
36 // If set, an octal mode (0 through 07777) or chmod(1) symbolic mode
37 // clauses for the destination. This value is passed to the executor for
38 // handling: symbolic clauses (including the conditional X) are resolved
39 // against each copied file's current mode there.
40 Chmod string
41 // If set, a checksum which the source must match, or be rejected.
42 Checksum string
43 // Additional files which need to be created by executor for this
44 // instruction.
45 Files []File
46 // If set, when the source is a URL for a remote Git repository,
47 // refrain from stripping out the .git subdirectory after cloning it.
48 KeepGitDir bool
49 // If set, instead of adding these items to the rootfs and picking them
50 // up as part of a subsequent diff generation, build an archive of them
51 // and include it as an independent layer.
52 Link bool
53 // If set, preserve leading directories in the paths of items being
54 // copied, relative to either the top of the build context, or to the
55 // "pivot point", a location in the source path marked by a path
56 // component named "." (i.e., where "/./" occurs in the path).
57 Parents bool
58 // Exclusion patterns, a la .dockerignore, relative to either the top
59 // of a directory tree being copied, or the "pivot point", a location
60 // in the source path marked by a path component named ".".
61 Excludes []string
62 }
63
64 // File defines if any additional file needs to be created
65 // by the executor instruction so that specified command
66 // can execute/copy the created file inside the build container.
67 type File struct {
68 Name string // Name of the new file.
69 Data string // Content of the file.
70 }
71
72 // Run defines a run operation required in the container.
73 type Run struct {
74 Shell bool
75 Args []string
76 // Mounts are mounts specified through the --mount flag inside the Containerfile
77 Mounts []string
78 // Network specifies the network mode to run the container with
79 Network string
80 // Additional files which need to be created by executor for this
81 // instruction.
82 Files []File
83 }
84
85 type Executor interface {
86 Preserve(path string) error
87 // EnsureContainerPath should ensure that the directory exists, creating any components required
88 EnsureContainerPath(path string) error
89 // EnsureContainerPathAs should ensure that the directory exists, creating any components required
90 // with the specified owner and mode, if either is specified
91 EnsureContainerPathAs(path, user string, mode *os.FileMode) error
92 Copy(excludes []string, copies ...Copy) error
93 Run(run Run, config docker.Config) error
94 UnrecognizedInstruction(step *Step) error
95 }
96
97 type logExecutor struct{}
98
99 func (logExecutor) Preserve(path string) error {
100 log.Printf("PRESERVE %s", path)
101 return nil
102 }
103
104 func (logExecutor) EnsureContainerPath(path string) error {
105 log.Printf("ENSURE %s", path)
106 return nil
107 }
108
109 func (logExecutor) EnsureContainerPathAs(path, user string, mode *os.FileMode) error {
110 if mode != nil {
111 log.Printf("ENSURE %s AS %q with MODE=%q", path, user, *mode)
112 } else {
113 log.Printf("ENSURE %s AS %q", path, user)
114 }
115 return nil
116 }
117
118 func (logExecutor) Copy(excludes []string, copies ...Copy) error {
119 for _, c := range copies {
120 log.Printf("COPY %v -> %s (from:%s download:%t), chown: %s, chmod %s, checksum: %s", c.Src, c.Dest, c.From, c.Download, c.Chown, c.Chmod, c.Checksum)
121 }
122 return nil
123 }
124
125 func (logExecutor) Run(run Run, config docker.Config) error {
126 log.Printf("RUN %v %v %t (%v)", run.Args, run.Mounts, run.Shell, config.Env)
127 return nil
128 }
129
130 func (logExecutor) UnrecognizedInstruction(step *Step) error {
131 log.Printf("Unknown instruction: %s", strings.ToUpper(step.Command))
132 return nil
133 }
134
135 type noopExecutor struct{}
136
137 func (noopExecutor) Preserve(path string) error {
138 return nil
139 }
140
141 func (noopExecutor) EnsureContainerPath(path string) error {
142 return nil
143 }
144
145 func (noopExecutor) EnsureContainerPathAs(path, user string, mode *os.FileMode) error {
146 return nil
147 }
148
149 func (noopExecutor) Copy(excludes []string, copies ...Copy) error {
150 return nil
151 }
152
153 func (noopExecutor) Run(run Run, config docker.Config) error {
154 return nil
155 }
156
157 func (noopExecutor) UnrecognizedInstruction(step *Step) error {
158 return nil
159 }
160
161 type VolumeSet []string
162
163 func (s *VolumeSet) Add(path string) bool {
164 if path == "/" {
165 set := len(*s) != 1 || (*s)[0] != ""
166 *s = []string{""}
167 return set
168 }
169 path = strings.TrimSuffix(path, "/")
170 var adjusted []string
171 for _, p := range *s {
172 if p == path || strings.HasPrefix(path, p+"/") {
173 return false
174 }
175 if strings.HasPrefix(p, path+"/") {
176 continue
177 }
178 adjusted = append(adjusted, p)
179 }
180 adjusted = append(adjusted, path)
181 *s = adjusted
182 return true
183 }
184
185 func (s VolumeSet) Has(path string) bool {
186 if path == "/" {
187 return len(s) == 1 && s[0] == ""
188 }
189 path = strings.TrimSuffix(path, "/")
190 for _, p := range s {
191 if p == path {
192 return true
193 }
194 }
195 return false
196 }
197
198 func (s VolumeSet) Covers(path string) bool {
199 if path == "/" {
200 return len(s) == 1 && s[0] == ""
201 }
202 path = strings.TrimSuffix(path, "/")
203 for _, p := range s {
204 if p == path || strings.HasPrefix(path, p+"/") {
205 return true
206 }
207 }
208 return false
209 }
210
211 var (
212 LogExecutor = logExecutor{}
213 NoopExecutor = noopExecutor{}
214 )
215
216 type Stages []Stage
217
218 func (stages Stages) ByName(name string) (Stage, bool) {
219 for _, stage := range slices.Backward(stages) {
220 if stage.Name == name {
221 return stage, true
222 }
223 }
224 if i, err := strconv.Atoi(name); err == nil {
225 return stages.ByPosition(i)
226 }
227 return Stage{}, false
228 }
229
230 func (stages Stages) ByPosition(position int) (Stage, bool) {
231 for _, stage := range stages {
232 // stage.Position is expected to be the same as the unnamed
233 // index variable for this loop, but comparing to the Position
234 // field's value is easier to explain
235 if stage.Position == position {
236 return stage, true
237 }
238 }
239 return Stage{}, false
240 }
241
242 // Get just the target stage.
243 func (stages Stages) ByTarget(target string) (Stages, bool) {
244 if len(target) == 0 {
245 return stages, true
246 }
247 for i, stage := range slices.Backward(stages) {
248 if stage.Name == target {
249 return stages[i : i+1], true
250 }
251 }
252 if position, err := strconv.Atoi(target); err == nil {
253 for i, stage := range stages {
254 // stage.Position is expected to be the same as the unnamed
255 // index variable for this loop, but comparing to the Position
256 // field's value is easier to explain
257 if stage.Position == position {
258 return stages[i : i+1], true
259 }
260 }
261 }
262 return nil, false
263 }
264
265 // Get all the stages up to and including the target.
266 func (stages Stages) ThroughTarget(target string) (Stages, bool) {
267 if len(target) == 0 {
268 return stages, true
269 }
270 for i, stage := range slices.Backward(stages) {
271 if stage.Name == target {
272 return stages[0 : i+1], true
273 }
274 }
275 if position, err := strconv.Atoi(target); err == nil {
276 for i, stage := range stages {
277 // stage.Position is expected to be the same as the unnamed
278 // index variable for this loop, but comparing to the Position
279 // field's value is easier to explain
280 if stage.Position == position {
281 return stages[0 : i+1], true
282 }
283 }
284 }
285 return nil, false
286 }
287
288 type Stage struct {
289 Position int
290 Name string // may just be strconv.Itoa(Position), be sure to search from back to front
291 Builder *Builder
292 Node *parser.Node
293 }
294
295 func NewStages(node *parser.Node, b *Builder) (Stages, error) {
296 getStageFrom := func(stageIndex int, root *parser.Node) (from string, as string, err error) {
297 for _, child := range root.Children {
298 if !strings.EqualFold(child.Value, command.From) {
299 continue
300 }
301 if child.Next == nil {
302 return "", "", errors.New("FROM requires an argument")
303 }
304 if child.Next.Value == "" {
305 return "", "", errors.New("FROM requires a non-empty argument")
306 }
307 from = child.Next.Value
308 if name, ok := extractNameFromNode(child); ok {
309 as = name
310 }
311 return from, as, nil
312 }
313 return "", "", fmt.Errorf("stage %d requires a FROM instruction (%q)", stageIndex+1, root.Original)
314 }
315 argInstructionsInStages := make(map[string][]string)
316 setStageInheritedArgs := func(s *Stage) error {
317 from, as, err := getStageFrom(s.Position, s.Node)
318 if err != nil {
319 return err
320 }
321 inheritedArgs := argInstructionsInStages[from]
322 thisStageArgs := slices.Clone(inheritedArgs)
323 filteredUserArgs := make(map[string]string)
324 for k, v := range b.UserArgs {
325 for _, a := range b.GlobalAllowedArgs {
326 if a == k {
327 filteredUserArgs[k] = v
328 }
329 }
330 }
331 userArgs := envMapAsSlice(filteredUserArgs)
332 userArgs = mergeEnv(envMapAsSlice(b.BuiltinArgDefaults), userArgs)
333 userArgs = mergeEnv(envMapAsSlice(builtinArgDefaults), userArgs)
334 userArgs = mergeEnv(envMapAsSlice(b.HeadingArgs), userArgs)
335 for _, child := range s.Node.Children {
336 if !strings.EqualFold(child.Value, command.Arg) {
337 continue
338 }
339 if child.Next == nil {
340 return errors.New("ARG requires an argument")
341 }
342 if child.Next.Value == "" {
343 return errors.New("ARG requires a non-empty argument")
344 }
345 next := child.Next
346 for next != nil {
347 processedValue, err := ProcessWord(next.Value, userArgs)
348 if err != nil {
349 return fmt.Errorf("processing ARG %q", next.Value)
350 }
351 thisStageArgs = append(thisStageArgs, processedValue)
352 userArgs = mergeEnv(userArgs, []string{processedValue})
353 next = next.Next
354 }
355 }
356 if as != "" {
357 argInstructionsInStages[as] = thisStageArgs
358 }
359 argInstructionsInStages[strconv.Itoa(s.Position)] = thisStageArgs
360 return arg(s.Builder, inheritedArgs, nil, nil, "", nil)
361 }
362 var stages Stages
363 var headingArgs []string
364 if err := b.extractHeadingArgsFromNode(node); err != nil {
365 return stages, err
366 }
367 for k := range b.HeadingArgs {
368 headingArgs = append(headingArgs, k)
369 }
370 for i, root := range SplitBy(node, command.From) {
371 name, hasName := extractNameFromNode(root.Children[0])
372 if !hasName {
373 name = strconv.Itoa(i)
374 }
375 filteredUserArgs := make(map[string]string)
376 for k, v := range b.UserArgs {
377 for _, a := range b.GlobalAllowedArgs {
378 if a == k {
379 filteredUserArgs[k] = v
380 }
381 }
382 }
383 userArgs := envMapAsSlice(filteredUserArgs)
384 userArgs = mergeEnv(envMapAsSlice(b.BuiltinArgDefaults), userArgs)
385 userArgs = mergeEnv(envMapAsSlice(builtinArgDefaults), userArgs)
386 userArgs = mergeEnv(envMapAsSlice(b.HeadingArgs), userArgs)
387 processedName, err := ProcessWord(name, userArgs)
388 if err != nil {
389 return nil, err
390 }
391 stage := Stage{
392 Position: i,
393 Name: processedName,
394 Builder: b.builderForStage(headingArgs),
395 Node: root,
396 }
397 if err := setStageInheritedArgs(&stage); err != nil {
398 return nil, err
399 }
400 stages = append(stages, stage)
401 }
402 return stages, nil
403 }
404
405 func (b *Builder) extractHeadingArgsFromNode(node *parser.Node) error {
406 var args []*parser.Node
407 var children []*parser.Node
408 extract := true
409 for _, child := range node.Children {
410 if extract && child.Value == command.Arg {
411 args = append(args, child)
412 } else {
413 if child.Value == command.From {
414 extract = false
415 }
416 children = append(children, child)
417 }
418 }
419
420 // Set children equal to everything except the leading ARG nodes
421 node.Children = children
422
423 // Use a separate builder to evaluate the heading args
424 tempBuilder := NewBuilder(b.UserArgs)
425
426 // Built-in ARGs are declared implicitly in the heading and should be resolvable in its scope
427 for k, v := range tempBuilder.BuiltinArgDefaults {
428 tempBuilder.AllowedArgs[k] = true
429 if _, ok := tempBuilder.Args[k]; !ok {
430 tempBuilder.Args[k] = v
431 }
432 }
433
434 // Evaluate all the heading arg commands
435 for _, c := range args {
436 step := tempBuilder.Step()
437 if err := step.Resolve(c); err != nil {
438 return err
439 }
440 if err := tempBuilder.Run(step, NoopExecutor, false); err != nil {
441 return err
442 }
443 }
444
445 // Add all of the defined heading args to the original builder's HeadingArgs map
446 for k, v := range tempBuilder.Args {
447 if _, ok := tempBuilder.AllowedArgs[k]; ok {
448 b.HeadingArgs[k] = v
449 }
450 }
451
452 return nil
453 }
454
455 func extractNameFromNode(node *parser.Node) (string, bool) {
456 if node.Value != command.From {
457 return "", false
458 }
459 n := node.Next
460 if n == nil || n.Next == nil {
461 return "", false
462 }
463 n = n.Next
464 if !strings.EqualFold(n.Value, "as") || n.Next == nil || len(n.Next.Value) == 0 {
465 return "", false
466 }
467 return n.Next.Value, true
468 }
469
470 func (b *Builder) builderForStage(globalArgsList []string) *Builder {
471 stageBuilder := newBuilderWithGlobalAllowedArgs(b.UserArgs, b.HeadingArgs, b.BuiltinArgDefaults, globalArgsList)
472 return stageBuilder
473 }
474
475 type Builder struct {
476 RunConfig docker.Config
477
478 Env []string
479
480 // Args contains values originally given to NewBuilder() or set due to
481 // ARG instructions in a stage, either with a default value provided,
482 // or with a default inherited from an ARG instruction in the header
483 Args map[string]string
484 // HeadingArgs contains the values for ARG instructions in the
485 // Dockerfile which occurred before the first FROM instruction, either
486 // with a default value provided as part of the ARG instruction, or
487 // expecting a value to be supplied in UserArgs via NewBuilder().
488 HeadingArgs map[string]string
489 // UserArgs includes a copy of the values that were passed to
490 // NewBuilder(), unmodified.
491 UserArgs map[string]string
492
493 CmdSet bool
494 Author string
495
496 // GlobalAllowedArgs are args which should be resolvable in a FROM
497 // instruction, either built-in and always available, or introduced by
498 // an ARG instruction in the header.
499 GlobalAllowedArgs []string
500 // AllowedArgs are args which should be resolvable in this stage,
501 // having been introduced by a previous ARG instruction in this stage.
502 AllowedArgs map[string]bool
503
504 Volumes VolumeSet
505 Excludes []string
506
507 PendingVolumes VolumeSet
508 PendingRuns []Run
509 PendingCopies []Copy
510
511 Warnings []string
512 // Raw platform string specified with `FROM --platform` of the stage
513 // It's up to the implementation or client to parse and use this field
514 Platform string
515 // After contains the stage name specified with `FROM --after=<stage>`. This
516 // declares a dependency on another stage. It's up to the implementation or
517 // client to handle this field.
518 After string
519
520 // Overrides for TARGET... and BUILD... values. TARGET... values are
521 // typically only necessary if the builder's target platform is not the
522 // same as the build platform.
523 BuiltinArgDefaults map[string]string
524 }
525
526 func NewBuilder(args map[string]string) *Builder {
527 return newBuilderWithGlobalAllowedArgs(args, nil, nil, []string{})
528 }
529
530 func newBuilderWithGlobalAllowedArgs(args, headingArgs, userBuiltinArgDefaults map[string]string, globalAllowedArgs []string) *Builder {
531 allowed := make(map[string]bool)
532 for k, v := range builtinAllowedBuildArgs {
533 allowed[k] = v
534 }
535 userArgs := make(map[string]string)
536 initialArgs := make(map[string]string)
537 for k, v := range args {
538 userArgs[k] = v
539 initialArgs[k] = v
540 }
541 var copiedGlobalAllowedArgs []string
542 if len(globalAllowedArgs) > 0 {
543 copiedGlobalAllowedArgs = append([]string{}, globalAllowedArgs...)
544 }
545 copiedHeadingArgs := make(map[string]string)
546 for k, v := range headingArgs {
547 copiedHeadingArgs[k] = v
548 }
549 copiedBuiltinArgDefaults := make(map[string]string)
550 for k, v := range builtinArgDefaults {
551 copiedBuiltinArgDefaults[k] = v
552 }
553 for k, v := range userBuiltinArgDefaults {
554 copiedBuiltinArgDefaults[k] = v
555 }
556 return &Builder{
557 Args: initialArgs,
558 UserArgs: userArgs,
559 HeadingArgs: copiedHeadingArgs,
560 AllowedArgs: allowed,
561 GlobalAllowedArgs: copiedGlobalAllowedArgs,
562 BuiltinArgDefaults: copiedBuiltinArgDefaults,
563 }
564 }
565
566 func ParseFile(path string) (*parser.Node, error) {
567 f, err := os.Open(path)
568 if err != nil {
569 return nil, err
570 }
571 defer f.Close()
572 return ParseDockerfile(f)
573 }
574
575 // Step creates a new step from the current state.
576 func (b *Builder) Step() *Step {
577 // Include build arguments in the table of variables that we'll use in
578 // Resolve(), but override them with values from the actual
579 // environment in case there's any conflict.
580 return &Step{Env: mergeEnv(b.Arguments(), mergeEnv(b.Env, b.RunConfig.Env))}
581 }
582
583 // Run executes a step, transforming the current builder and
584 // invoking any Copy or Run operations. noRunsRemaining is an
585 // optimization hint that allows the builder to avoid performing
586 // unnecessary work.
587 func (b *Builder) Run(step *Step, exec Executor, noRunsRemaining bool) error {
588 fn, ok := evaluateTable[step.Command]
589 if !ok {
590 return exec.UnrecognizedInstruction(step)
591 }
592 if err := fn(b, step.Args, step.Attrs, step.Flags, step.Original, step.Heredocs); err != nil {
593 return err
594 }
595
596 copies := b.PendingCopies
597 b.PendingCopies = nil
598 runs := b.PendingRuns
599 b.PendingRuns = nil
600
601 // Once a VOLUME is defined, future ADD/COPY instructions are
602 // all that may mutate that path. Instruct the executor to preserve
603 // the path. The executor must handle invalidating preserved info.
604 for _, path := range b.PendingVolumes {
605 if b.Volumes.Add(path) && !noRunsRemaining {
606 if err := exec.Preserve(path); err != nil {
607 return err
608 }
609 }
610 }
611
612 if err := exec.Copy(b.Excludes, copies...); err != nil {
613 return err
614 }
615
616 if len(b.RunConfig.WorkingDir) > 0 {
617 if err := exec.EnsureContainerPathAs(b.RunConfig.WorkingDir, b.RunConfig.User, nil); err != nil {
618 return err
619 }
620 }
621
622 for _, run := range runs {
623 config := b.Config()
624 config.Env = step.Env
625 if err := exec.Run(run, *config); err != nil {
626 return err
627 }
628 }
629
630 return nil
631 }
632
633 // RequiresStart returns true if a running container environment is necessary
634 // to invoke the provided commands
635 func (b *Builder) RequiresStart(node *parser.Node) bool {
636 for _, child := range node.Children {
637 if child.Value == command.Run {
638 return true
639 }
640 }
641 return false
642 }
643
644 // Config returns a snapshot of the current RunConfig intended for
645 // use with a container commit.
646 func (b *Builder) Config() *docker.Config {
647 config := b.RunConfig
648 if config.OnBuild == nil {
649 config.OnBuild = []string{}
650 }
651 if config.Entrypoint == nil {
652 config.Entrypoint = []string{}
653 }
654 config.Image = ""
655 return &config
656 }
657
658 // Arguments returns the currently active arguments.
659 func (b *Builder) Arguments() []string {
660 var envs []string
661 for key, val := range b.Args {
662 if _, ok := b.AllowedArgs[key]; ok {
663 envs = append(envs, fmt.Sprintf("%s=%s", key, val))
664 }
665 }
666 return envs
667 }
668
669 // ErrNoFROM is returned if the Dockerfile did not contain a FROM
670 // statement.
671 var ErrNoFROM = fmt.Errorf("no FROM statement found")
672
673 // From returns the image this dockerfile depends on, or an error
674 // if no FROM is found or if multiple FROM are specified. If a
675 // single from is found the passed node is updated with only
676 // the remaining statements. The builder's RunConfig.Image field
677 // is set to the first From found, or left unchanged if already
678 // set.
679 func (b *Builder) From(node *parser.Node) (string, error) {
680 if err := b.extractHeadingArgsFromNode(node); err != nil {
681 return "", err
682 }
683 children := SplitChildren(node, command.From)
684 switch {
685 case len(children) == 0:
686 return "", ErrNoFROM
687 case len(children) > 1:
688 return "", fmt.Errorf("multiple FROM statements are not supported")
689 default:
690 step := b.Step()
691 if err := step.Resolve(children[0]); err != nil {
692 return "", err
693 }
694 if err := b.Run(step, NoopExecutor, false); err != nil {
695 return "", err
696 }
697 return b.RunConfig.Image, nil
698 }
699 }
700
701 // FromImage updates the builder to use the provided image (resetting RunConfig
702 // and recording the image environment), and updates the node with any ONBUILD
703 // statements extracted from the parent image.
704 func (b *Builder) FromImage(image *docker.Image, node *parser.Node) error {
705 SplitChildren(node, command.From)
706
707 b.RunConfig = *image.Config
708 b.Env = mergeEnv(b.Env, b.RunConfig.Env)
709 b.RunConfig.Env = nil
710
711 // Check to see if we have a default PATH, note that windows won't
712 // have one as it's set by HCS
713 if runtime.GOOS != "windows" && !hasEnvName(b.Env, "PATH") {
714 b.RunConfig.Env = append(b.RunConfig.Env, "PATH="+defaultPathEnv)
715 }
716
717 // Join the image onbuild statements into node
718 if image.Config == nil || len(image.Config.OnBuild) == 0 {
719 return nil
720 }
721 extra, err := ParseDockerfile(bytes.NewBufferString(strings.Join(image.Config.OnBuild, "\n")))
722 if err != nil {
723 return err
724 }
725 for _, child := range extra.Children {
726 switch strings.ToUpper(child.Value) {
727 case "ONBUILD":
728 return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
729 case "MAINTAINER", "FROM":
730 return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", child.Value)
731 }
732 }
733 node.Children = append(extra.Children, node.Children...)
734 // Since we've processed the OnBuild statements, clear them from the runconfig state.
735 b.RunConfig.OnBuild = nil
736 return nil
737 }
738
739 // SplitChildren removes any children with the provided value from node
740 // and returns them as an array. node.Children is updated.
741 func SplitChildren(node *parser.Node, value string) []*parser.Node {
742 var split []*parser.Node
743 var children []*parser.Node
744 for _, child := range node.Children {
745 if child.Value == value {
746 split = append(split, child)
747 } else {
748 children = append(children, child)
749 }
750 }
751 node.Children = children
752 return split
753 }
754
755 func SplitBy(node *parser.Node, value string) []*parser.Node {
756 var split []*parser.Node
757 var current *parser.Node
758 for _, child := range node.Children {
759 if current == nil || child.Value == value {
760 copied := *node
761 current = &copied
762 current.Children = nil
763 current.Next = nil
764 split = append(split, current)
765 }
766 current.Children = append(current.Children, child)
767 }
768 return split
769 }
770
771 // StepFunc is invoked with the result of a resolved step.
772 type StepFunc func(*Builder, []string, map[string]bool, []string, string, []buildkitparser.Heredoc) error
773
774 var evaluateTable = map[string]StepFunc{
775 command.Env: env,
776 command.Label: label,
777 command.Maintainer: maintainer,
778 command.Add: add,
779 command.Copy: dispatchCopy, // copy() is a go builtin
780 command.From: from,
781 command.Onbuild: onbuild,
782 command.Workdir: workdir,
783 command.Run: run,
784 command.Cmd: cmd,
785 command.Entrypoint: entrypoint,
786 command.Expose: expose,
787 command.Volume: volume,
788 command.User: user,
789 command.StopSignal: stopSignal,
790 command.Arg: arg,
791 command.Healthcheck: healthcheck,
792 command.Shell: shell,
793 }
794
795 // builtinAllowedBuildArgs is list of built-in allowed build args
796 var builtinAllowedBuildArgs = map[string]bool{
797 "HTTP_PROXY": true,
798 "http_proxy": true,
799 "HTTPS_PROXY": true,
800 "https_proxy": true,
801 "FTP_PROXY": true,
802 "ftp_proxy": true,
803 "NO_PROXY": true,
804 "no_proxy": true,
805 }
806
807 // ParseIgnoreReader returns a list of the excludes in the provided file
808 // which uses the .dockerignore format
809 // extracted from fsouza/go-dockerclient and modified to drop comments and
810 // empty lines.
811 func ParseIgnoreReader(r io.Reader) ([]string, error) {
812 var excludes []string
813
814 ignores, err := io.ReadAll(r)
815 if err != nil {
816 return excludes, err
817 }
818 for _, ignore := range strings.Split(string(ignores), "\n") {
819 if len(ignore) == 0 || ignore[0] == '#' {
820 continue
821 }
822 ignore = strings.Trim(ignore, "/")
823 if len(ignore) > 0 {
824 excludes = append(excludes, ignore)
825 }
826 }
827 return excludes, nil
828 }
829
830 // ParseIgnore returns a list returned by having ParseIgnoreReader() read the
831 // specified path
832 func ParseIgnore(path string) ([]string, error) {
833 var excludes []string
834
835 ignores, err := os.ReadFile(path)
836 if err != nil {
837 return excludes, err
838 }
839 return ParseIgnoreReader(bytes.NewReader(ignores))
840 }
841
842 // ParseDockerIgnore returns a list of the excludes in the .containerignore or .dockerignore file.
843 func ParseDockerignore(root string) ([]string, error) {
844 excludes, err := ParseIgnore(filepath.Join(root, ".containerignore"))
845 if err != nil && os.IsNotExist(err) {
846 excludes, err = ParseIgnore(filepath.Join(root, ".dockerignore"))
847 }
848 if err != nil && os.IsNotExist(err) {
849 return excludes, nil
850 }
851 return excludes, err
852 }
853
854 // ExportEnv creates an export statement for a shell that contains all of the
855 // provided environment.
856 func ExportEnv(env []string) string {
857 if len(env) == 0 {
858 return ""
859 }
860 out := "export"
861 for _, e := range env {
862 if len(e) == 0 {
863 continue
864 }
865 out += " " + BashQuote(e)
866 }
867 return out + "; "
868 }
869
870 // BashQuote escapes the provided string and surrounds it with double quotes.
871 // TODO: verify that these are all we have to escape.
872 func BashQuote(env string) string {
873 out := []rune{'"'}
874 for _, r := range env {
875 switch r {
876 case '$', '\\', '"':
877 out = append(out, '\\', r)
878 default:
879 out = append(out, r)
880 }
881 }
882 out = append(out, '"')
883 return string(out)
884 }