Răsfoiți Sursa

Add "opinionated" tag to gocritic

Signed-off-by: Ulysses Souza <[email protected]>
Ulysses Souza 3 ani în urmă
părinte
comite
d42adf6efb

+ 4 - 0
.golangci.yml

@@ -38,6 +38,10 @@ linters-settings:
     # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
     enabled-tags:
       - diagnostic
+      - opinionated
+    disabled-checks:
+      - paramTypeCombine
+      - unnamedResult
   gocyclo:
     min-complexity: 16
   lll:

+ 13 - 13
cmd/compose/compose.go

@@ -239,11 +239,11 @@ func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command {
 		verbose bool
 		version bool
 	)
-	command := &cobra.Command{
+	c := &cobra.Command{
 		Short:            "Docker Compose",
 		Use:              PluginName,
 		TraverseChildren: true,
-		// By default (no Run/RunE in parent command) for typos in subcommands, cobra displays the help of parent command but exit(0) !
+		// By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
 		RunE: func(cmd *cobra.Command, args []string) error {
 			if len(args) == 0 {
 				return cmd.Help()
@@ -300,7 +300,7 @@ func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command {
 		},
 	}
 
-	command.AddCommand(
+	c.AddCommand(
 		upCommand(&opts, backend),
 		downCommand(&opts, backend),
 		startCommand(&opts, backend),
@@ -327,16 +327,16 @@ func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command {
 		createCommand(&opts, backend),
 		copyCommand(&opts, backend),
 	)
-	command.Flags().SetInterspersed(false)
-	opts.addProjectFlags(command.Flags())
-	command.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
-	command.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
-	command.Flags().MarkHidden("version") //nolint:errcheck
-	command.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
-	command.Flags().MarkHidden("no-ansi") //nolint:errcheck
-	command.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
-	command.Flags().MarkHidden("verbose") //nolint:errcheck
-	return command
+	c.Flags().SetInterspersed(false)
+	opts.addProjectFlags(c.Flags())
+	c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
+	c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
+	c.Flags().MarkHidden("version") //nolint:errcheck
+	c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
+	c.Flags().MarkHidden("no-ansi") //nolint:errcheck
+	c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
+	c.Flags().MarkHidden("verbose") //nolint:errcheck
+	return c
 }
 
 func setEnvWithDotEnv(prjOpts *projectOptions) error {

+ 11 - 11
cmd/compose/list.go

@@ -39,19 +39,19 @@ type lsOptions struct {
 }
 
 func listCommand(backend api.Service) *cobra.Command {
-	opts := lsOptions{Filter: opts.NewFilterOpt()}
+	lsOpts := lsOptions{Filter: opts.NewFilterOpt()}
 	lsCmd := &cobra.Command{
 		Use:   "ls",
 		Short: "List running compose projects",
 		RunE: Adapt(func(ctx context.Context, args []string) error {
-			return runList(ctx, backend, opts)
+			return runList(ctx, backend, lsOpts)
 		}),
 		ValidArgsFunction: noCompletion(),
 	}
-	lsCmd.Flags().StringVar(&opts.Format, "format", "pretty", "Format the output. Values: [pretty | json].")
-	lsCmd.Flags().BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs.")
-	lsCmd.Flags().Var(&opts.Filter, "filter", "Filter output based on conditions provided.")
-	lsCmd.Flags().BoolVarP(&opts.All, "all", "a", false, "Show all stopped Compose projects")
+	lsCmd.Flags().StringVar(&lsOpts.Format, "format", "pretty", "Format the output. Values: [pretty | json].")
+	lsCmd.Flags().BoolVarP(&lsOpts.Quiet, "quiet", "q", false, "Only display IDs.")
+	lsCmd.Flags().Var(&lsOpts.Filter, "filter", "Filter output based on conditions provided.")
+	lsCmd.Flags().BoolVarP(&lsOpts.All, "all", "a", false, "Show all stopped Compose projects")
 
 	return lsCmd
 }
@@ -60,18 +60,18 @@ var acceptedListFilters = map[string]bool{
 	"name": true,
 }
 
-func runList(ctx context.Context, backend api.Service, opts lsOptions) error {
-	filters := opts.Filter.Value()
+func runList(ctx context.Context, backend api.Service, lsOpts lsOptions) error {
+	filters := lsOpts.Filter.Value()
 	err := filters.Validate(acceptedListFilters)
 	if err != nil {
 		return err
 	}
 
-	stackList, err := backend.List(ctx, api.ListOptions{All: opts.All})
+	stackList, err := backend.List(ctx, api.ListOptions{All: lsOpts.All})
 	if err != nil {
 		return err
 	}
-	if opts.Quiet {
+	if lsOpts.Quiet {
 		for _, s := range stackList {
 			fmt.Println(s.Name)
 		}
@@ -90,7 +90,7 @@ func runList(ctx context.Context, backend api.Service, opts lsOptions) error {
 	}
 
 	view := viewFromStackList(stackList)
-	return formatter.Print(view, opts.Format, os.Stdout, func(w io.Writer) {
+	return formatter.Print(view, lsOpts.Format, os.Stdout, func(w io.Writer) {
 		for _, stack := range view {
 			_, _ = fmt.Fprintf(w, "%s\t%s\t%s\n", stack.Name, stack.Status, stack.ConfigFiles)
 		}

+ 13 - 11
cmd/compose/up.go

@@ -219,18 +219,20 @@ func runUp(ctx context.Context, backend api.Service, createOptions createOptions
 
 func setServiceScale(project *types.Project, name string, replicas uint64) error {
 	for i, s := range project.Services {
-		if s.Name == name {
-			service, err := project.GetService(name)
-			if err != nil {
-				return err
-			}
-			if service.Deploy == nil {
-				service.Deploy = &types.DeployConfig{}
-			}
-			service.Deploy.Replicas = &replicas
-			project.Services[i] = service
-			return nil
+		if s.Name != name {
+			continue
+		}
+
+		service, err := project.GetService(name)
+		if err != nil {
+			return err
+		}
+		if service.Deploy == nil {
+			service.Deploy = &types.DeployConfig{}
 		}
+		service.Deploy.Replicas = &replicas
+		project.Services[i] = service
+		return nil
 	}
 	return fmt.Errorf("unknown service %q", name)
 }

+ 25 - 24
pkg/compose/build.go

@@ -61,29 +61,30 @@ func (s *composeService) build(ctx context.Context, project *types.Project, opti
 	}
 
 	for _, service := range services {
-		if service.Build != nil {
-			imageName := getImageName(service, project.Name)
-			imagesToBuild = append(imagesToBuild, imageName)
-			buildOptions, err := s.toBuildOptions(project, service, imageName, options.SSHs)
-			if err != nil {
-				return err
-			}
-			buildOptions.Pull = options.Pull
-			buildOptions.BuildArgs = mergeArgs(buildOptions.BuildArgs, args)
-			buildOptions.NoCache = options.NoCache
-			buildOptions.CacheFrom, err = buildflags.ParseCacheEntry(service.Build.CacheFrom)
-			if err != nil {
-				return err
-			}
+		if service.Build == nil {
+			continue
+		}
+		imageName := getImageName(service, project.Name)
+		imagesToBuild = append(imagesToBuild, imageName)
+		buildOptions, err := s.toBuildOptions(project, service, imageName, options.SSHs)
+		if err != nil {
+			return err
+		}
+		buildOptions.Pull = options.Pull
+		buildOptions.BuildArgs = mergeArgs(buildOptions.BuildArgs, args)
+		buildOptions.NoCache = options.NoCache
+		buildOptions.CacheFrom, err = buildflags.ParseCacheEntry(service.Build.CacheFrom)
+		if err != nil {
+			return err
+		}
 
-			for _, image := range service.Build.CacheFrom {
-				buildOptions.CacheFrom = append(buildOptions.CacheFrom, bclient.CacheOptionsEntry{
-					Type:  "registry",
-					Attrs: map[string]string{"ref": image},
-				})
-			}
-			opts[imageName] = buildOptions
+		for _, image := range service.Build.CacheFrom {
+			buildOptions.CacheFrom = append(buildOptions.CacheFrom, bclient.CacheOptionsEntry{
+				Type:  "registry",
+				Attrs: map[string]string{"ref": image},
+			})
 		}
+		opts[imageName] = buildOptions
 	}
 
 	_, err = s.doBuild(ctx, project, opts, options.Progress)
@@ -312,11 +313,11 @@ func mergeArgs(m ...types.Mapping) types.Mapping {
 	return merged
 }
 
-func dockerFilePath(context string, dockerfile string) string {
-	if urlutil.IsGitURL(context) || filepath.IsAbs(dockerfile) {
+func dockerFilePath(ctxName string, dockerfile string) string {
+	if urlutil.IsGitURL(ctxName) || filepath.IsAbs(dockerfile) {
 		return dockerfile
 	}
-	return filepath.Join(context, dockerfile)
+	return filepath.Join(ctxName, dockerfile)
 }
 
 func sshAgentProvider(sshKeys types.SSHConfig) (session.Attachable, error) {

+ 1 - 1
pkg/compose/build_classic.go

@@ -214,7 +214,7 @@ func (s *composeService) doBuildClassicSimpleImage(ctx context.Context, options
 		if imageID == "" {
 			return "", errors.Errorf("Server did not provide an image ID. Cannot write %s", options.ImageIDFile)
 		}
-		if err := os.WriteFile(options.ImageIDFile, []byte(imageID), 0666); err != nil {
+		if err := os.WriteFile(options.ImageIDFile, []byte(imageID), 0o666); err != nil {
 			return "", err
 		}
 	}

+ 4 - 4
pkg/compose/create.go

@@ -893,7 +893,7 @@ func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount
 			continue
 		}
 
-		mount, err := buildMount(p, types.ServiceVolumeConfig{
+		mnt, err := buildMount(p, types.ServiceVolumeConfig{
 			Type:     types.VolumeTypeBind,
 			Source:   definedSecret.File,
 			Target:   target,
@@ -902,7 +902,7 @@ func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount
 		if err != nil {
 			return nil, err
 		}
-		mounts[target] = mount
+		mounts[target] = mnt
 	}
 	values := make([]mount.Mount, 0, len(mounts))
 	for _, v := range mounts {
@@ -911,8 +911,8 @@ func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount
 	return values, nil
 }
 
-func isUnixAbs(path string) bool {
-	return strings.HasPrefix(path, "/")
+func isUnixAbs(p string) bool {
+	return strings.HasPrefix(p, "/")
 }
 
 func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {

+ 1 - 1
pkg/compose/secrets.go

@@ -57,7 +57,7 @@ func createTar(env string, config types.ServiceSecretConfig) (bytes.Buffer, erro
 	value := []byte(env)
 	b := bytes.Buffer{}
 	tarWriter := tar.NewWriter(&b)
-	mode := uint32(0400)
+	mode := uint32(0o400)
 	if config.Mode != nil {
 		mode = *config.Mode
 	}

+ 2 - 2
pkg/e2e/framework.go

@@ -127,7 +127,7 @@ func initializePlugins(t testing.TB, configDir string) {
 		}
 	})
 
-	require.NoError(t, os.MkdirAll(filepath.Join(configDir, "cli-plugins"), 0755),
+	require.NoError(t, os.MkdirAll(filepath.Join(configDir, "cli-plugins"), 0o755),
 		"Failed to create cli-plugins directory")
 	composePlugin, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
 	if os.IsNotExist(err) {
@@ -175,7 +175,7 @@ func CopyFile(t testing.TB, sourceFile string, destinationFile string) {
 	// nolint: errcheck
 	defer src.Close()
 
-	dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
+	dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)
 	require.NoError(t, err, "Failed to open destination file: %s", destinationFile)
 	// nolint: errcheck
 	defer dst.Close()

+ 2 - 2
pkg/e2e/scan_message_test.go

@@ -71,9 +71,9 @@ func TestDisplayScanMessageAfterBuild(t *testing.T) {
 	})
 
 	t.Run("do not display if scan already invoked", func(t *testing.T) {
-		_ = os.MkdirAll(filepath.Join(c.ConfigDir, "scan"), 0755)
+		_ = os.MkdirAll(filepath.Join(c.ConfigDir, "scan"), 0o755)
 		scanConfigFile := filepath.Join(c.ConfigDir, "scan", "config.json")
-		err := os.WriteFile(scanConfigFile, []byte(`{"optin":true}`), 0644)
+		err := os.WriteFile(scanConfigFile, []byte(`{"optin":true}`), 0o644)
 		assert.NilError(t, err)
 
 		res := c.RunDockerCmd(t, "build", "-t", "test-image-scan-msg", "fixtures/simple-build-test/nginx-build")