Explorar el Código

fix various linting issues

Got these when running locally on a more recent version of golangci-lint:

    pkg/compose/build_bake.go:187:3: importShadow: shadow of imported from 'github.com/docker/cli/cli/command/image/build' package 'build' (gocritic)
                    build := *service.Build
                    ^
    pkg/compose/build_bake.go:526:19: importShadow: shadow of imported from 'github.com/docker/cli/cli/command/image/build' package 'build' (gocritic)
    func toBakeAttest(build types.BuildConfig) []string {
                      ^
    pkg/compose/create.go:1453:2: importShadow: shadow of imported from 'github.com/docker/docker/api/types/network' package 'network' (gocritic)
            network string,
            ^
    pkg/compose/create.go:1468:2: importShadow: shadow of imported from 'github.com/docker/docker/api/types/network' package 'network' (gocritic)
            network string,
            ^
    pkg/compose/monitor.go:42:17: importShadow: shadow of imported from 'github.com/docker/compose/v2/pkg/api' package 'api' (gocritic)
    func newMonitor(api client.APIClient, project string) *monitor {
                    ^
    cmd/compose/config.go:337:1: File is not properly formatted (gofumpt)
            return
    ^
    pkg/compose/convergence.go:608:1: File is not properly formatted (gofumpt)
                    return
    ^
    pkg/compose/cp.go:335:1: File is not properly formatted (gofumpt)
                    return
    ^
    pkg/e2e/compose_up_test.go:35:10: go-require: c.RunDockerComposeCmd contains assertions that must only be used in the goroutine running the test function (testifylint)
                    res := c.RunDockerComposeCmd(t, "-f", "fixtures/dependencies/deps-completed-successfully.yaml", "--project-name", projectName, "up", "--wait", "-d")
                           ^
    pkg/e2e/healthcheck_test.go:42:10: go-require: c.RunDockerComposeCmd contains assertions that must only be used in the goroutine running the test function (testifylint)
                    res := c.RunDockerComposeCmd(t, "-f", "fixtures/start_interval/compose.yaml", "--project-name", projectName, "up", "--wait", "-d", "test")
                           ^
    10 issues:
    * gocritic: 5
    * gofumpt: 3
    * testifylint: 2

Signed-off-by: Sebastiaan van Stijn <[email protected]>
Sebastiaan van Stijn hace 1 mes
padre
commit
74a4ccdd85

+ 2 - 3
cmd/compose/config.go

@@ -324,17 +324,16 @@ func resolveImageDigests(ctx context.Context, dockerCli command.Cli, model map[s
 func formatModel(model map[string]any, format string) (content []byte, err error) {
 	switch format {
 	case "json":
-		content, err = json.MarshalIndent(model, "", "  ")
+		return json.MarshalIndent(model, "", "  ")
 	case "yaml":
 		buf := bytes.NewBuffer([]byte{})
 		encoder := yaml.NewEncoder(buf)
 		encoder.SetIndent(2)
 		err = encoder.Encode(model)
-		content = buf.Bytes()
+		return buf.Bytes(), err
 	default:
 		return nil, fmt.Errorf("unsupported format %q", format)
 	}
-	return
 }
 
 func runServices(ctx context.Context, dockerCli command.Cli, opts configOptions) error {

+ 31 - 31
pkg/compose/build_bake.go

@@ -184,7 +184,7 @@ func (s *composeService) doBuildBake(ctx context.Context, project *types.Project
 		if service.Build == nil {
 			continue
 		}
-		build := *service.Build
+		buildConfig := *service.Build
 		labels := getImageBuildLabels(project, service)
 
 		args := resolveAndMergeBuildArgs(s.getProxyConfig(), project, service, options).ToMapping()
@@ -192,11 +192,11 @@ func (s *composeService) doBuildBake(ctx context.Context, project *types.Project
 			args[k] = strings.ReplaceAll(v, "${", "$${")
 		}
 
-		entitlements := build.Entitlements
-		if slices.Contains(build.Entitlements, "security.insecure") {
+		entitlements := buildConfig.Entitlements
+		if slices.Contains(buildConfig.Entitlements, "security.insecure") {
 			privileged = true
 		}
-		if build.Privileged {
+		if buildConfig.Privileged {
 			entitlements = append(entitlements, "security.insecure")
 			privileged = true
 		}
@@ -217,8 +217,8 @@ func (s *composeService) doBuildBake(ctx context.Context, project *types.Project
 			}
 		}
 
-		read = append(read, build.Context)
-		for _, path := range build.AdditionalContexts {
+		read = append(read, buildConfig.Context)
+		for _, path := range buildConfig.AdditionalContexts {
 			_, _, err := gitutil.ParseGitRef(path)
 			if !strings.Contains(path, "://") && err != nil {
 				read = append(read, path)
@@ -235,35 +235,35 @@ func (s *composeService) doBuildBake(ctx context.Context, project *types.Project
 
 		target := targets[serviceName]
 
-		secrets, env := toBakeSecrets(project, build.Secrets)
+		secrets, env := toBakeSecrets(project, buildConfig.Secrets)
 		secretsEnv = append(secretsEnv, env...)
 
 		cfg.Targets[target] = bakeTarget{
-			Context:          build.Context,
-			Contexts:         additionalContexts(build.AdditionalContexts, targets),
-			Dockerfile:       dockerFilePath(build.Context, build.Dockerfile),
-			DockerfileInline: strings.ReplaceAll(build.DockerfileInline, "${", "$${"),
+			Context:          buildConfig.Context,
+			Contexts:         additionalContexts(buildConfig.AdditionalContexts, targets),
+			Dockerfile:       dockerFilePath(buildConfig.Context, buildConfig.Dockerfile),
+			DockerfileInline: strings.ReplaceAll(buildConfig.DockerfileInline, "${", "$${"),
 			Args:             args,
 			Labels:           labels,
-			Tags:             append(build.Tags, image),
+			Tags:             append(buildConfig.Tags, image),
 
-			CacheFrom:    build.CacheFrom,
-			CacheTo:      build.CacheTo,
-			NetworkMode:  build.Network,
-			Platforms:    build.Platforms,
-			Target:       build.Target,
+			CacheFrom:    buildConfig.CacheFrom,
+			CacheTo:      buildConfig.CacheTo,
+			NetworkMode:  buildConfig.Network,
+			Platforms:    buildConfig.Platforms,
+			Target:       buildConfig.Target,
 			Secrets:      secrets,
-			SSH:          toBakeSSH(append(build.SSH, options.SSHs...)),
+			SSH:          toBakeSSH(append(buildConfig.SSH, options.SSHs...)),
 			Pull:         pull,
 			NoCache:      noCache,
-			ShmSize:      build.ShmSize,
-			Ulimits:      toBakeUlimits(build.Ulimits),
+			ShmSize:      buildConfig.ShmSize,
+			Ulimits:      toBakeUlimits(buildConfig.Ulimits),
 			Entitlements: entitlements,
-			ExtraHosts:   toBakeExtraHosts(build.ExtraHosts),
+			ExtraHosts:   toBakeExtraHosts(buildConfig.ExtraHosts),
 
 			Outputs: outputs,
 			Call:    call,
-			Attest:  toBakeAttest(build),
+			Attest:  toBakeAttest(buildConfig),
 		}
 	}
 
@@ -524,24 +524,24 @@ func toBakeSecrets(project *types.Project, secrets []types.ServiceSecretConfig)
 	return s, env
 }
 
-func toBakeAttest(build types.BuildConfig) []string {
+func toBakeAttest(buildConfig types.BuildConfig) []string {
 	var attests []string
 
 	// Handle per-service provenance configuration (only from build config, not global options)
-	if build.Provenance != "" {
-		if build.Provenance == "true" {
+	if buildConfig.Provenance != "" {
+		if buildConfig.Provenance == "true" {
 			attests = append(attests, "type=provenance")
-		} else if build.Provenance != "false" {
-			attests = append(attests, fmt.Sprintf("type=provenance,%s", build.Provenance))
+		} else if buildConfig.Provenance != "false" {
+			attests = append(attests, fmt.Sprintf("type=provenance,%s", buildConfig.Provenance))
 		}
 	}
 
 	// Handle per-service SBOM configuration (only from build config, not global options)
-	if build.SBOM != "" {
-		if build.SBOM == "true" {
+	if buildConfig.SBOM != "" {
+		if buildConfig.SBOM == "true" {
 			attests = append(attests, "type=sbom")
-		} else if build.SBOM != "false" {
-			attests = append(attests, fmt.Sprintf("type=sbom,%s", build.SBOM))
+		} else if buildConfig.SBOM != "false" {
+			attests = append(attests, fmt.Sprintf("type=sbom,%s", buildConfig.SBOM))
 		}
 	}
 

+ 2 - 2
pkg/compose/convergence.go

@@ -605,10 +605,10 @@ func (s *composeService) createContainer(ctx context.Context, project *types.Pro
 				StatusText: err.Error(),
 			})
 		}
-		return
+		return ctr, err
 	}
 	s.events.On(progress.CreatedEvent(eventName))
-	return
+	return ctr, nil
 }
 
 func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,

+ 1 - 1
pkg/compose/cp.go

@@ -331,7 +331,7 @@ func splitCpArg(arg string) (ctr, path string) {
 
 func resolveLocalPath(localPath string) (absPath string, err error) {
 	if absPath, err = filepath.Abs(localPath); err != nil {
-		return
+		return absPath, err
 	}
 	return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil
 }

+ 4 - 4
pkg/compose/create.go

@@ -1449,11 +1449,11 @@ func (s *composeService) removeDivergedNetwork(ctx context.Context, project *typ
 
 func (s *composeService) disconnectNetwork(
 	ctx context.Context,
-	network string,
+	nwName string,
 	containers Containers,
 ) error {
 	for _, c := range containers {
-		err := s.apiClient().NetworkDisconnect(ctx, network, c.ID, true)
+		err := s.apiClient().NetworkDisconnect(ctx, nwName, c.ID, true)
 		if err != nil {
 			return err
 		}
@@ -1464,12 +1464,12 @@ func (s *composeService) disconnectNetwork(
 
 func (s *composeService) connectNetwork(
 	ctx context.Context,
-	network string,
+	nwName string,
 	containers Containers,
 	config *network.EndpointSettings,
 ) error {
 	for _, c := range containers {
-		err := s.apiClient().NetworkConnect(ctx, network, c.ID, config)
+		err := s.apiClient().NetworkConnect(ctx, nwName, c.ID, config)
 		if err != nil {
 			return err
 		}

+ 9 - 9
pkg/compose/monitor.go

@@ -32,18 +32,18 @@ import (
 )
 
 type monitor struct {
-	api     client.APIClient
-	project string
+	apiClient client.APIClient
+	project   string
 	// services tells us which service to consider and those we can ignore, maybe ran by a concurrent compose command
 	services  map[string]bool
 	listeners []api.ContainerEventListener
 }
 
-func newMonitor(api client.APIClient, project string) *monitor {
+func newMonitor(apiClient client.APIClient, project string) *monitor {
 	return &monitor{
-		api:      api,
-		project:  project,
-		services: map[string]bool{},
+		apiClient: apiClient,
+		project:   project,
+		services:  map[string]bool{},
 	}
 }
 
@@ -58,7 +58,7 @@ func (c *monitor) withServices(services []string) {
 //nolint:gocyclo
 func (c *monitor) Start(ctx context.Context) error {
 	// collect initial application container
-	initialState, err := c.api.ContainerList(ctx, container.ListOptions{
+	initialState, err := c.apiClient.ContainerList(ctx, container.ListOptions{
 		All: true,
 		Filters: filters.NewArgs(
 			projectFilter(c.project),
@@ -79,7 +79,7 @@ func (c *monitor) Start(ctx context.Context) error {
 	}
 	restarting := utils.Set[string]{}
 
-	evtCh, errCh := c.api.Events(ctx, events.ListOptions{
+	evtCh, errCh := c.apiClient.Events(ctx, events.ListOptions{
 		Filters: filters.NewArgs(
 			filters.Arg("type", "container"),
 			projectFilter(c.project)),
@@ -140,7 +140,7 @@ func (c *monitor) Start(ctx context.Context) error {
 				logrus.Debugf("container %s restarted", ctr.Name)
 			case events.ActionDie:
 				logrus.Debugf("container %s exited with code %d", ctr.Name, ctr.ExitCode)
-				inspect, err := c.api.ContainerInspect(ctx, event.Actor.ID)
+				inspect, err := c.apiClient.ContainerInspect(ctx, event.Actor.ID)
 				if errdefs.IsNotFound(err) {
 					// Source is already removed
 				} else if err != nil {

+ 1 - 0
pkg/e2e/compose_up_test.go

@@ -32,6 +32,7 @@ func TestUpWait(t *testing.T) {
 	timeout := time.After(30 * time.Second)
 	done := make(chan bool)
 	go func() {
+		//nolint:nolintlint,testifylint // helper asserts inside goroutine; acceptable in this e2e test
 		res := c.RunDockerComposeCmd(t, "-f", "fixtures/dependencies/deps-completed-successfully.yaml", "--project-name", projectName, "up", "--wait", "-d")
 		assert.Assert(t, strings.Contains(res.Combined(), "e2e-deps-wait-oneshot-1"), res.Combined())
 		done <- true

+ 1 - 0
pkg/e2e/healthcheck_test.go

@@ -39,6 +39,7 @@ func TestStartInterval(t *testing.T) {
 	timeout := time.After(30 * time.Second)
 	done := make(chan bool)
 	go func() {
+		//nolint:nolintlint,testifylint // helper asserts inside goroutine; acceptable in this e2e test
 		res := c.RunDockerComposeCmd(t, "-f", "fixtures/start_interval/compose.yaml", "--project-name", projectName, "up", "--wait", "-d", "test")
 		out := res.Combined()
 		assert.Assert(t, strings.Contains(out, "Healthy"), out)