Skip to content

Commit

Permalink
chore: only include the dockerignore file if it exists
Browse files Browse the repository at this point in the history
  • Loading branch information
mdelapenya committed Apr 9, 2024
1 parent 9e2372e commit 84cc48a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
18 changes: 12 additions & 6 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,13 +221,13 @@ func (c *ContainerRequest) GetContext() (io.Reader, error) {
}
c.Context = abs

excluded, err := parseDockerIgnore(abs)
dockerIgnoreExists, excluded, err := parseDockerIgnore(abs)
if err != nil {
return nil, err
}

if len(excluded) > 0 {
// only add .dockerignore if it exists including files to ignore
if dockerIgnoreExists {
// only add .dockerignore if it exists
includes = append(includes, filepath.Join(".dockerignore"))
}

Expand All @@ -244,18 +244,24 @@ func (c *ContainerRequest) GetContext() (io.Reader, error) {
return buildContext, nil
}

func parseDockerIgnore(targetDir string) ([]string, error) {
// parseDockerIgnore returns if the file exists, the excluded files and an error if any
func parseDockerIgnore(targetDir string) (bool, []string, error) {
// based on https://github.com/docker/cli/blob/master/cli/command/image/build/dockerignore.go#L14
fileLocation := filepath.Join(targetDir, ".dockerignore")
var excluded []string
exists := false
if f, openErr := os.Open(fileLocation); openErr == nil {
defer f.Close()

exists = true

var err error
excluded, err = ignorefile.ReadAll(f)
if err != nil {
return excluded, fmt.Errorf("error reading .dockerignore: %w", err)
return true, excluded, fmt.Errorf("error reading .dockerignore: %w", err)
}
}
return excluded, nil
return exists, excluded, nil
}

// GetBuildArgs returns the env args to be used when creating from Dockerfile
Expand Down
11 changes: 10 additions & 1 deletion container_ignore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,32 @@ import (
func TestParseDockerIgnore(t *testing.T) {
testCases := []struct {
filePath string
exists bool
expectedErr error
expectedExcluded []string
}{
{
filePath: "./testdata/dockerignore",
expectedErr: nil,
exists: true,
expectedExcluded: []string{"vendor", "foo", "bar"},
},
{
filePath: "./testdata",
expectedErr: nil,
exists: true,
expectedExcluded: []string{"Dockerfile", "echo.Dockerfile"},
},
{
filePath: "./testdata/data",
expectedErr: nil,
expectedExcluded: nil, // it's nil because the parseDockerIgnore function uses the zero value of a slice
},
}

for _, testCase := range testCases {
excluded, err := parseDockerIgnore(testCase.filePath)
exists, excluded, err := parseDockerIgnore(testCase.filePath)
assert.Equal(t, testCase.exists, exists)
assert.Equal(t, testCase.expectedErr, err)
assert.Equal(t, testCase.expectedExcluded, excluded)
}
Expand Down

0 comments on commit 84cc48a

Please sign in to comment.