Support Dockerfile-specific ignore-file with watch

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
This commit is contained in:
Nicolas De Loof 2024-10-08 09:25:14 +02:00 committed by Nicolas De loof
parent 407d825705
commit f794c79eb3
2 changed files with 22 additions and 16 deletions

View File

@ -136,7 +136,7 @@ func (s *composeService) watch(ctx context.Context, syncChannel chan bool, proje
service.PullPolicy = types.PullPolicyBuild service.PullPolicy = types.PullPolicyBuild
project.Services[i] = service project.Services[i] = service
dockerIgnores, err := watch.LoadDockerIgnore(service.Build.Context) dockerIgnores, err := watch.LoadDockerIgnore(service.Build)
if err != nil { if err != nil {
return err return err
} }

View File

@ -18,10 +18,12 @@ package watch
import ( import (
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/compose-spec/compose-go/v2/types"
"github.com/docker/compose/v2/internal/paths" "github.com/docker/compose/v2/internal/paths"
"github.com/moby/patternmatcher" "github.com/moby/patternmatcher"
"github.com/moby/patternmatcher/ignorefile" "github.com/moby/patternmatcher/ignorefile"
@ -61,13 +63,28 @@ func (i dockerPathMatcher) MatchesEntireDir(f string) (bool, error) {
return true, nil return true, nil
} }
func LoadDockerIgnore(repoRoot string) (*dockerPathMatcher, error) { func LoadDockerIgnore(build *types.BuildConfig) (*dockerPathMatcher, error) {
repoRoot := build.Context
absRoot, err := filepath.Abs(repoRoot) absRoot, err := filepath.Abs(repoRoot)
if err != nil { if err != nil {
return nil, err return nil, err
} }
patterns, err := readDockerignorePatterns(absRoot) // first try Dockerfile-specific ignore-file
f, err := os.Open(filepath.Join(repoRoot, build.Dockerfile+".dockerignore"))
if os.IsNotExist(err) {
// defaults to a global .dockerignore
f, err = os.Open(filepath.Join(repoRoot, ".dockerignore"))
if os.IsNotExist(err) {
return NewDockerPatternMatcher(repoRoot, nil)
}
}
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
patterns, err := readDockerignorePatterns(f)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -122,19 +139,8 @@ func NewDockerPatternMatcher(repoRoot string, patterns []string) (*dockerPathMat
}, nil }, nil
} }
func readDockerignorePatterns(repoRoot string) ([]string, error) { func readDockerignorePatterns(r io.Reader) ([]string, error) {
var excludes []string patterns, err := ignorefile.ReadAll(r)
f, err := os.Open(filepath.Join(repoRoot, ".dockerignore"))
switch {
case os.IsNotExist(err):
return excludes, nil
case err != nil:
return nil, err
}
defer func() { _ = f.Close() }()
patterns, err := ignorefile.ReadAll(f)
if err != nil { if err != nil {
return nil, fmt.Errorf("error reading .dockerignore: %w", err) return nil, fmt.Errorf("error reading .dockerignore: %w", err)
} }