Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: watch flag skips files specified by dockerignore #5565

Merged
merged 22 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/pkg/cli/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ Format: [container]:KEY=VALUE. Omit container name to apply to all containers.`
Example: --port-override 5000:80 binds localhost:5000 to the service's port 80.`
proxyFlagDescription = `Optional. Proxy outbound requests to your environment's VPC.`
proxyNetworkFlagDescription = `Optional. Set the IP Network used by --proxy.`
watchFlagDescription = `Optional. Watch changes to local files and restart containers when updated.`
watchFlagDescription = `Optional. Watch changes to local files and restart containers when updated. Directories in a .dockerignore file are ignored.`
useTaskRoleFlagDescription = "Optional. Run containers with TaskRole credentials instead of session credentials."

svcManifestFlagDescription = `Optional. Name of the environment in which the service was deployed;
Expand Down
4 changes: 4 additions & 0 deletions internal/pkg/cli/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -754,3 +754,7 @@ type stackConfiguration interface {
type secretGetter interface {
GetSecretValue(context.Context, string) (string, error)
}

type dockerWorkload interface {
Dockerfile() string
}
37 changes: 37 additions & 0 deletions internal/pkg/cli/mocks/mock_interfaces.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 34 additions & 27 deletions internal/pkg/cli/run_local.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ type runLocalOpts struct {

newRecursiveWatcher func() (recursiveWatcher, error)
buildContainerImages func(mft manifest.DynamicWorkload) (map[string]string, error)
readDockerignoreFile func(fs afero.Fs, contextDir string) ([]string, error)
configureClients func() error
labeledTermPrinter func(fw syncbuffer.FileWriter, bufs []*syncbuffer.LabeledSyncBuffer, opts ...syncbuffer.LabeledTermPrinterOption) clideploy.LabeledTermPrinter
unmarshal func([]byte) (manifest.DynamicWorkload, error)
Expand Down Expand Up @@ -172,19 +171,18 @@ func newRunLocalOpts(vars runLocalVars) (*runLocalOpts, error) {
return syncbuffer.NewLabeledTermPrinter(fw, bufs, opts...)
}
o := &runLocalOpts{
runLocalVars: vars,
sel: selector.NewDeploySelect(prompt.New(), store, deployStore),
store: store,
ws: ws,
newInterpolator: newManifestInterpolator,
sessProvider: sessProvider,
unmarshal: manifest.UnmarshalWorkload,
sess: defaultSess,
cmd: exec.NewCmd(),
dockerEngine: dockerengine.New(exec.NewCmd()),
labeledTermPrinter: labeledTermPrinter,
prog: termprogress.NewSpinner(log.DiagnosticWriter),
readDockerignoreFile: dockerfile.ReadDockerignore,
runLocalVars: vars,
sel: selector.NewDeploySelect(prompt.New(), store, deployStore),
store: store,
ws: ws,
newInterpolator: newManifestInterpolator,
sessProvider: sessProvider,
unmarshal: manifest.UnmarshalWorkload,
sess: defaultSess,
cmd: exec.NewCmd(),
dockerEngine: dockerengine.New(exec.NewCmd()),
labeledTermPrinter: labeledTermPrinter,
prog: termprogress.NewSpinner(log.DiagnosticWriter),
}
o.configureClients = func() error {
defaultSessEnvRegion, err := o.sessProvider.DefaultWithRegion(o.targetEnv.Region)
Expand Down Expand Up @@ -241,23 +239,15 @@ func newRunLocalOpts(vars runLocalVars) (*runLocalOpts, error) {
return nil
}
o.buildContainerImages = func(mft manifest.DynamicWorkload) (map[string]string, error) {
var dockerfileDir string
switch v := mft.Manifest().(type) {
case *manifest.LoadBalancedWebService:
dockerfileDir, _ = filepath.Split(aws.StringValue(v.ImageConfig.ImageWithPort.Image.Build.BuildString))
case *manifest.BackendService:
dockerfileDir, _ = filepath.Split(aws.StringValue(v.ImageConfig.ImageWithOptionalPort.Image.Build.BuildString))
case *manifest.ScheduledJob:
dockerfileDir, _ = filepath.Split(aws.StringValue(v.ImageConfig.Image.Build.BuildString))
case *manifest.RequestDrivenWebService:
dockerfileDir, _ = filepath.Split(aws.StringValue(v.ImageConfig.Image.Build.BuildString))
case *manifest.WorkerService:
dockerfileDir, _ = filepath.Split(aws.StringValue(v.ImageConfig.Image.Build.BuildString))
var dfDir string
if dockerWkld, ok := mft.Manifest().(dockerWorkload); ok {
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
dfDir = filepath.Dir(dockerWkld.Dockerfile())
}
o.dockerExcludes, err = o.readDockerignoreFile(afero.NewOsFs(), filepath.Join(ws.Path(), dockerfileDir))
o.dockerExcludes, err = dockerfile.ReadDockerignore(afero.NewOsFs(), filepath.Join(ws.Path(), dfDir))
if err != nil {
return nil, err
}
o.filterDockerExcludes()

gitShortCommit := imageTagFromGit(o.cmd)
image := clideploy.ContainerImageIdentifier{
Expand Down Expand Up @@ -615,6 +605,23 @@ func (o *runLocalOpts) prepareTask(ctx context.Context) (orchestrator.Task, erro
return task, nil
}

func (o *runLocalOpts) filterDockerExcludes() {
filter := func(excludes []string, match func(string) bool) []string {
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
result := []string{}
for _, exclude := range excludes {
if !match(exclude) {
result = append(result, exclude)
}
}
return result
}

wsPath := o.ws.Path()
o.dockerExcludes = filter(o.dockerExcludes, func(s string) bool {
return strings.HasPrefix(s, filepath.ToSlash(filepath.Join(wsPath, workspace.CopilotDirName)))
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
})
}

func (o *runLocalOpts) watchLocalFiles(stopCh <-chan struct{}) (<-chan interface{}, <-chan error, error) {
workspacePath := o.ws.Path()

Expand Down
42 changes: 42 additions & 0 deletions internal/pkg/cli/run_local_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1978,3 +1978,45 @@ func TestRunLocal_HostDiscovery(t *testing.T) {
})
}
}

type runLocalFilterDockerExcludesMocks struct {
ws *mocks.MockwsWlDirReader
}

func TestRunLocal_FilterDockerExcludes(t *testing.T) {
tests := map[string]struct {
setupMocks func(t *testing.T, m *runLocalFilterDockerExcludesMocks)

inputDockerExcludes []string
wantedDockerExcludes []string
}{
"filter out all copilot directories": {
setupMocks: func(t *testing.T, m *runLocalFilterDockerExcludesMocks) {
m.ws.EXPECT().Path().Return("/ws")
},
inputDockerExcludes: []string{"/ws/copilot/*", "/ws/ignoredfile.go", "/ws/copilot/environments/*"},
wantedDockerExcludes: []string{"/ws/ignoredfile.go"},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := &runLocalFilterDockerExcludesMocks{
ws: mocks.NewMockwsWlDirReader(ctrl),
}
tc.setupMocks(t, m)
opts := runLocalOpts{
dockerExcludes: tc.inputDockerExcludes,
ws: m.ws,
}

// WHEN
opts.filterDockerExcludes()

// THEN
require.Equal(t, opts.dockerExcludes, tc.wantedDockerExcludes)
})
}
}
5 changes: 5 additions & 0 deletions internal/pkg/manifest/backend_svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ func (s *BackendService) requiredEnvironmentFeatures() []string {
return features
}

// Dockerfile returns the relative path of the Dockerfile in the manifest.
func (s *BackendService) Dockerfile() string {
return s.ImageConfig.Image.dockerfilePath()
}

// Port returns the exposed port in the manifest.
// If the backend service is not meant to be reachable, then ok is set to false.
func (s *BackendService) Port() (port uint16, ok bool) {
Expand Down
5 changes: 5 additions & 0 deletions internal/pkg/manifest/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ func (s *ScheduledJob) requiredEnvironmentFeatures() []string {
return features
}

// Dockerfile returns the relative path of the Dockerfile in the manifest.
func (j *ScheduledJob) Dockerfile() string {
return j.ImageConfig.Image.dockerfilePath()
}

// Publish returns the list of topics where notifications can be published.
func (j *ScheduledJob) Publish() []Topic {
return j.ScheduledJobConfig.PublishConfig.publishedTopics()
Expand Down
5 changes: 5 additions & 0 deletions internal/pkg/manifest/lb_web_svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ func (s *LoadBalancedWebService) requiredEnvironmentFeatures() []string {
return features
}

// Dockerfile returns the relative path of the Dockerfile in the manifest.
func (s *LoadBalancedWebService) Dockerfile() string {
return s.ImageConfig.Image.dockerfilePath()
}

// Port returns the exposed port in the manifest.
// A LoadBalancedWebService always has a port exposed therefore the boolean is always true.
func (s *LoadBalancedWebService) Port() (port uint16, ok bool) {
Expand Down
5 changes: 5 additions & 0 deletions internal/pkg/manifest/rd_web_svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ func (s *RequestDrivenWebService) MarshalBinary() ([]byte, error) {
return content.Bytes(), nil
}

// Dockerfile returns the relative path of the Dockerfile in the manifest.
func (s *RequestDrivenWebService) Dockerfile() string {
return s.ImageConfig.Image.dockerfilePath()
}

// Port returns the exposed the exposed port in the manifest.
// A RequestDrivenWebService always has a port exposed therefore the boolean is always true.
func (s *RequestDrivenWebService) Port() (port uint16, ok bool) {
Expand Down
5 changes: 5 additions & 0 deletions internal/pkg/manifest/worker_svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ type WorkerService struct {
parser template.Parser
}

// Dockerfile returns the relative path of the Dockerfile in the manifest.
func (s *WorkerService) Dockerfile() string {
return s.ImageConfig.Image.dockerfilePath()
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
}

// Publish returns the list of topics where notifications can be published.
func (s *WorkerService) Publish() []Topic {
return s.WorkerServiceConfig.PublishConfig.publishedTopics()
Expand Down
52 changes: 27 additions & 25 deletions internal/pkg/manifest/workload.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,38 +166,40 @@ func (i Image) GetLocation() string {
}

// BuildConfig populates a docker.BuildArguments struct from the fields available in the manifest.
// Prefer the following hierarchy:
// 1. Specific dockerfile, specific context
// 2. Specific dockerfile, context = dockerfile dir
// 3. "Dockerfile" located in context dir
// 4. "Dockerfile" located in ws root.
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
func (i *ImageLocationOrBuild) BuildConfig(rootDirectory string) *DockerBuildArgs {
df := i.dockerfile()
ctx := i.context()
dockerfile := aws.String(filepath.Join(rootDirectory, defaultDockerfileName))
context := aws.String(rootDirectory)

if df != "" && ctx != "" {
dockerfile = aws.String(filepath.Join(rootDirectory, df))
context = aws.String(filepath.Join(rootDirectory, ctx))
}
if df != "" && ctx == "" {
dockerfile = aws.String(filepath.Join(rootDirectory, df))
context = aws.String(filepath.Join(rootDirectory, filepath.Dir(df)))
}
if df == "" && ctx != "" {
dockerfile = aws.String(filepath.Join(rootDirectory, ctx, defaultDockerfileName))
context = aws.String(filepath.Join(rootDirectory, ctx))
}
return &DockerBuildArgs{
Dockerfile: dockerfile,
Context: context,
Dockerfile: aws.String(filepath.Join(rootDirectory, i.dockerfilePath())),
Context: aws.String(filepath.Join(rootDirectory, i.contextPath())),
Args: i.args(),
Target: i.target(),
CacheFrom: i.cacheFrom(),
}
}

// dockerfilePath returns the relative path of a dockerfile.
// Prefer a specific dockerfile, then a dockerfile in the context directory.
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
func (i *ImageLocationOrBuild) dockerfilePath() string {
df := i.dockerfile()
ctx := i.context()

if df != "" {
return df
}
return filepath.Join(ctx, defaultDockerfileName)
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
}

// dockerfileContext returns the relative context of an image.
// Prefer a specific context, then the dockerfile directory.
func (i *ImageLocationOrBuild) contextPath() string {
df := i.dockerfile()
ctx := i.context()

if ctx != "" {
return ctx
}
return filepath.Dir(df)
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
}

// dockerfile returns the path to the workload's Dockerfile. If no dockerfile is specified,
// returns "".
func (i *ImageLocationOrBuild) dockerfile() string {
Expand Down Expand Up @@ -390,7 +392,7 @@ func (b *BuildArgsOrString) UnmarshalYAML(value *yaml.Node) error {

// DockerBuildArgs represents the options specifiable under the "build" field
// of Docker Compose services. For more information, see:
// https://docs.docker.com/compose/compose-file/#build
// https://docs.docker.com/compose/compose-file/build
CaptainCarpensir marked this conversation as resolved.
Show resolved Hide resolved
type DockerBuildArgs struct {
Context *string `yaml:"context,omitempty"`
Dockerfile *string `yaml:"dockerfile,omitempty"`
Expand Down