2017-04-16 15:01:15 -04:00
|
|
|
package build
|
|
|
|
|
|
|
|
import (
|
2023-08-22 18:05:32 -04:00
|
|
|
"fmt"
|
2017-04-16 15:01:15 -04:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
2022-10-13 09:49:35 -04:00
|
|
|
"github.com/moby/patternmatcher"
|
2023-08-22 18:05:32 -04:00
|
|
|
"github.com/moby/patternmatcher/ignorefile"
|
2017-04-16 15:01:15 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// ReadDockerignore reads the .dockerignore file in the context directory and
|
|
|
|
// returns the list of paths to exclude
|
|
|
|
func ReadDockerignore(contextDir string) ([]string, error) {
|
|
|
|
var excludes []string
|
|
|
|
|
|
|
|
f, err := os.Open(filepath.Join(contextDir, ".dockerignore"))
|
|
|
|
switch {
|
|
|
|
case os.IsNotExist(err):
|
|
|
|
return excludes, nil
|
|
|
|
case err != nil:
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
2023-08-22 18:05:32 -04:00
|
|
|
patterns, err := ignorefile.ReadAll(f)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error reading .dockerignore: %w", err)
|
|
|
|
}
|
|
|
|
return patterns, nil
|
2017-04-16 15:01:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// TrimBuildFilesFromExcludes removes the named Dockerfile and .dockerignore from
|
|
|
|
// the list of excluded files. The daemon will remove them from the final context
|
|
|
|
// but they must be in available in the context when passed to the API.
|
|
|
|
func TrimBuildFilesFromExcludes(excludes []string, dockerfile string, dockerfileFromStdin bool) []string {
|
2022-10-13 09:49:35 -04:00
|
|
|
if keep, _ := patternmatcher.Matches(".dockerignore", excludes); keep {
|
2017-04-16 15:01:15 -04:00
|
|
|
excludes = append(excludes, "!.dockerignore")
|
|
|
|
}
|
2022-08-31 11:50:47 -04:00
|
|
|
|
|
|
|
// canonicalize dockerfile name to be platform-independent.
|
|
|
|
dockerfile = filepath.ToSlash(dockerfile)
|
2022-10-13 09:49:35 -04:00
|
|
|
if keep, _ := patternmatcher.Matches(dockerfile, excludes); keep && !dockerfileFromStdin {
|
2017-04-16 15:01:15 -04:00
|
|
|
excludes = append(excludes, "!"+dockerfile)
|
|
|
|
}
|
|
|
|
return excludes
|
|
|
|
}
|