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

Add gocritic to linters #9643

Merged
merged 5 commits into from
Jul 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ linters:
- deadcode
- depguard
- errcheck
- gocritic
- gocyclo
- gofmt
- goimports
Expand All @@ -32,6 +33,17 @@ linters-settings:
# The io/ioutil package has been deprecated.
# https://go.dev/doc/go1.16#ioutil
- io/ioutil
gocritic:
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- diagnostic
- opinionated
- style
disabled-checks:
- paramTypeCombine
- unnamedResult
- whyNoLint
gocyclo:
min-complexity: 16
lll:
Expand Down
6 changes: 4 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
# limitations under the License.

ARG GO_VERSION=1.18.4-alpine
ARG GOLANGCI_LINT_VERSION=v1.40.1-alpine
ARG GOLANGCI_LINT_VERSION=v1.46.2-alpine
ARG PROTOC_GEN_GO_VERSION=v1.4.3

FROM --platform=${BUILDPLATFORM} golangci/golangci-lint:${GOLANGCI_LINT_VERSION} AS local-golangci-lint

FROM --platform=${BUILDPLATFORM} golang:${GO_VERSION} AS base
WORKDIR /compose-cli
RUN apk add --no-cache -vv \
Expand All @@ -34,7 +36,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \

FROM base AS lint
ENV CGO_ENABLED=0
COPY --from=golangci/golangci-lint /usr/bin/golangci-lint /usr/bin/golangci-lint
COPY --from=local-golangci-lint /usr/bin/golangci-lint /usr/bin/golangci-lint
ARG BUILD_TAGS
ARG GIT_TAG
RUN --mount=target=. \
Expand Down
28 changes: 14 additions & 14 deletions cmd/compose/compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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),
Expand All @@ -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 {
Expand All @@ -355,7 +355,7 @@ func setEnvWithDotEnv(prjOpts *projectOptions) error {
}
for k, v := range envFromFile {
if _, ok := os.LookupEnv(k); !ok {
if err = os.Setenv(k, v); err != nil {
if err := os.Setenv(k, v); err != nil {
return err
}
}
Expand Down
3 changes: 1 addition & 2 deletions cmd/compose/down.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ func downCommand(p *projectOptions, backend api.Service) *cobra.Command {
flags.BoolVarP(&opts.volumes, "volumes", "v", false, " Remove named volumes declared in the `volumes` section of the Compose file and anonymous volumes attached to containers.")
flags.StringVar(&opts.images, "rmi", "", `Remove images used by services. "local" remove only images that don't have a custom tag ("local"|"all")`)
flags.SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName {
switch name {
case "volume":
if name == "volume" {
name = "volumes"
logrus.Warn("--volume is deprecated, please use --volumes")
}
Expand Down
22 changes: 11 additions & 11 deletions cmd/compose/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
}
Expand All @@ -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)
}
Expand Down
24 changes: 13 additions & 11 deletions cmd/compose/up.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
24 changes: 12 additions & 12 deletions cmd/formatter/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ import (
"github.com/docker/compose/v2/pkg/api"
)

// LogConsumer consume logs from services and format them
type logConsumer struct {
ctx context.Context
presenters sync.Map // map[string]*presenter
width int
writer io.Writer
color bool
prefix bool
}

// NewLogConsumer creates a new LogConsumer
func NewLogConsumer(ctx context.Context, w io.Writer, color bool, prefix bool) api.LogConsumer {
return &logConsumer{
Expand Down Expand Up @@ -79,14 +89,14 @@ func (l *logConsumer) Log(container, service, message string) {
}
p := l.getPresenter(container)
for _, line := range strings.Split(message, "\n") {
fmt.Fprintf(l.writer, "%s%s\n", p.prefix, line) // nolint:errcheck
fmt.Fprintf(l.writer, "%s%s\n", p.prefix, line) //nolint:errcheck
}
}

func (l *logConsumer) Status(container, msg string) {
p := l.getPresenter(container)
s := p.colors(fmt.Sprintf("%s %s\n", container, msg))
l.writer.Write([]byte(s)) // nolint:errcheck
l.writer.Write([]byte(s)) //nolint:errcheck
}

func (l *logConsumer) computeWidth() {
Expand All @@ -101,16 +111,6 @@ func (l *logConsumer) computeWidth() {
l.width = width + 1
}

// LogConsumer consume logs from services and format them
type logConsumer struct {
ctx context.Context
presenters sync.Map // map[string]*presenter
width int
writer io.Writer
color bool
prefix bool
}

type presenter struct {
colors colorFunc
name string
Expand Down
2 changes: 1 addition & 1 deletion pkg/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
)

const (
//ExitCodeLoginRequired exit code when command cannot execute because it requires cloud login
// ExitCodeLoginRequired exit code when command cannot execute because it requires cloud login
// This will be used by VSCode to detect when creating context if the user needs to login first
ExitCodeLoginRequired = 5
)
Expand Down
4 changes: 2 additions & 2 deletions pkg/compose/attach.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,9 @@ func (s *composeService) attachContainerStreams(ctx context.Context, container s
if stdout != nil {
go func() {
if tty {
io.Copy(stdout, streamOut) // nolint:errcheck
io.Copy(stdout, streamOut) //nolint:errcheck
} else {
stdcopy.StdCopy(stdout, stderr, streamOut) // nolint:errcheck
stdcopy.StdCopy(stdout, stderr, streamOut) //nolint:errcheck
}
}()
}
Expand Down
49 changes: 25 additions & 24 deletions pkg/compose/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand Down
10 changes: 5 additions & 5 deletions pkg/compose/build_classic.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (s *composeService) doBuildClassic(ctx context.Context, project *types.Proj
return nameDigests, errs
}

// nolint: gocyclo
//nolint: gocyclo
func (s *composeService) doBuildClassicSimpleImage(ctx context.Context, options buildx.Options) (string, error) {
var (
buildCtx io.ReadCloser
Expand Down Expand Up @@ -96,7 +96,7 @@ func (s *composeService) doBuildClassicSimpleImage(ctx context.Context, options
if err != nil {
return "", errors.Errorf("unable to open Dockerfile: %v", err)
}
defer dockerfileCtx.Close() // nolint:errcheck
defer dockerfileCtx.Close() //nolint:errcheck
}
case urlutil.IsGitURL(specifiedContext):
tempDir, relDockerfile, err = build.GetContextFromGitURL(specifiedContext, dockerfileName)
Expand All @@ -111,7 +111,7 @@ func (s *composeService) doBuildClassicSimpleImage(ctx context.Context, options
}

if tempDir != "" {
defer os.RemoveAll(tempDir) // nolint:errcheck
defer os.RemoveAll(tempDir) //nolint:errcheck
contextDir = tempDir
}

Expand Down Expand Up @@ -175,7 +175,7 @@ func (s *composeService) doBuildClassicSimpleImage(ctx context.Context, options
if err != nil {
return "", err
}
defer response.Body.Close() // nolint:errcheck
defer response.Body.Close() //nolint:errcheck

imageID := ""
aux := func(msg jsonmessage.JSONMessage) {
Expand Down Expand Up @@ -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
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/compose/convergence.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ func (s composeService) getLinks(ctx context.Context, projectName string, servic
containerName := getCanonicalContainerName(c)
links = append(links,
format(containerName, linkName),
format(containerName, strings.Join([]string{linkServiceName, strconv.Itoa(number)}, Separator)),
format(containerName, linkServiceName+Separator+strconv.Itoa(number)),
format(containerName, strings.Join([]string{projectName, linkServiceName, strconv.Itoa(number)}, Separator)),
)
}
Expand Down
Loading