github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/cli/command/image/build/dockerignore.go (about) 1 package build 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 8 "github.com/moby/patternmatcher" 9 "github.com/moby/patternmatcher/ignorefile" 10 ) 11 12 // ReadDockerignore reads the .dockerignore file in the context directory and 13 // returns the list of paths to exclude 14 func ReadDockerignore(contextDir string) ([]string, error) { 15 var excludes []string 16 17 f, err := os.Open(filepath.Join(contextDir, ".dockerignore")) 18 switch { 19 case os.IsNotExist(err): 20 return excludes, nil 21 case err != nil: 22 return nil, err 23 } 24 defer f.Close() 25 26 patterns, err := ignorefile.ReadAll(f) 27 if err != nil { 28 return nil, fmt.Errorf("error reading .dockerignore: %w", err) 29 } 30 return patterns, nil 31 } 32 33 // TrimBuildFilesFromExcludes removes the named Dockerfile and .dockerignore from 34 // the list of excluded files. The daemon will remove them from the final context 35 // but they must be in available in the context when passed to the API. 36 func TrimBuildFilesFromExcludes(excludes []string, dockerfile string, dockerfileFromStdin bool) []string { 37 if keep, _ := patternmatcher.Matches(".dockerignore", excludes); keep { 38 excludes = append(excludes, "!.dockerignore") 39 } 40 41 // canonicalize dockerfile name to be platform-independent. 42 dockerfile = filepath.ToSlash(dockerfile) 43 if keep, _ := patternmatcher.Matches(dockerfile, excludes); keep && !dockerfileFromStdin { 44 excludes = append(excludes, "!"+dockerfile) 45 } 46 return excludes 47 }