Skip to content

Commit d2f6dcf

Browse files
authored
Merge pull request #285 from compose-spec/add-gocritic-linter
Add gocritic to linters
2 parents 2b59fba + 8676d27 commit d2f6dcf

File tree

13 files changed

+81
-67
lines changed

13 files changed

+81
-67
lines changed

cli/options.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ package cli
1818

1919
import (
2020
"fmt"
21-
"io/ioutil"
21+
"io"
2222
"os"
2323
"path/filepath"
2424
"strings"
@@ -323,7 +323,7 @@ func ProjectFromOptions(options *ProjectOptions) (*types.Project, error) {
323323
for _, f := range configPaths {
324324
var b []byte
325325
if f == "-" {
326-
b, err = ioutil.ReadAll(os.Stdin)
326+
b, err = io.ReadAll(os.Stdin)
327327
if err != nil {
328328
return nil, err
329329
}
@@ -332,7 +332,7 @@ func ProjectFromOptions(options *ProjectOptions) (*types.Project, error) {
332332
if err != nil {
333333
return nil, err
334334
}
335-
b, err = ioutil.ReadFile(f)
335+
b, err = os.ReadFile(f)
336336
if err != nil {
337337
return nil, err
338338
}

cli/options_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ func TestProjectComposefilesFromWorkingDir(t *testing.T) {
182182
assert.NilError(t, err)
183183
currentDir, _ := os.Getwd()
184184
assert.DeepEqual(t, p.ComposeFiles, []string{
185-
filepath.Join(currentDir, "testdata/simple/compose.yaml"),
186-
filepath.Join(currentDir, "testdata/simple/compose-with-overrides.yaml"),
185+
filepath.Join(currentDir, "testdata", "simple", "compose.yaml"),
186+
filepath.Join(currentDir, "testdata", "simple", "compose-with-overrides.yaml"),
187187
})
188188
}
189189

compatibility/services.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -550,7 +550,7 @@ func (c *AllowList) CheckPortsTarget(p *types.ServicePortConfig) {
550550
}
551551

552552
func (c *AllowList) CheckPortsPublished(p *types.ServicePortConfig) {
553-
if !c.supported("services.ports.published") && len(p.Published) != 0 {
553+
if !c.supported("services.ports.published") && p.Published == "" {
554554
p.Published = ""
555555
c.Unsupported("services.ports.published")
556556
}

dotenv/godotenv.go

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import (
1717
"errors"
1818
"fmt"
1919
"io"
20-
"io/ioutil"
2120
"os"
2221
"os/exec"
2322
"regexp"
@@ -44,7 +43,7 @@ func Parse(r io.Reader) (map[string]string, error) {
4443

4544
// ParseWithLookup reads an env file from io.Reader, returning a map of keys and values.
4645
func ParseWithLookup(r io.Reader, lookupFn LookupFn) (map[string]string, error) {
47-
data, err := ioutil.ReadAll(r)
46+
data, err := io.ReadAll(r)
4847
if err != nil {
4948
return nil, err
5049
}
@@ -184,7 +183,7 @@ func Marshal(envMap map[string]string) (string, error) {
184183
if d, err := strconv.Atoi(v); err == nil {
185184
lines = append(lines, fmt.Sprintf(`%s=%d`, k, d))
186185
} else {
187-
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
186+
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v))) //nolint // Cannot use %q here
188187
}
189188
}
190189
sort.Strings(lines)
@@ -235,10 +234,9 @@ var exportRegex = regexp.MustCompile(`^\s*(?:export\s+)?(.*?)\s*$`)
235234
func parseLine(line string, envMap map[string]string) (key string, value string, err error) {
236235
return parseLineWithLookup(line, envMap, nil)
237236
}
238-
func parseLineWithLookup(line string, envMap map[string]string, lookupFn LookupFn) (key string, value string, err error) {
239-
if len(line) == 0 {
240-
err = errors.New("zero length string")
241-
return
237+
func parseLineWithLookup(line string, envMap map[string]string, lookupFn LookupFn) (string, string, error) {
238+
if line == "" {
239+
return "", "", errors.New("zero length string")
242240
}
243241

244242
// ditch the comments (but keep quoted hashes)
@@ -271,14 +269,14 @@ func parseLineWithLookup(line string, envMap map[string]string, lookupFn LookupF
271269
}
272270

273271
if len(splitString) != 2 {
274-
err = errors.New("can't separate key from value")
275-
return
272+
return "", "", errors.New("can't separate key from value")
276273
}
277-
key = exportRegex.ReplaceAllString(splitString[0], "$1")
274+
key := exportRegex.ReplaceAllString(splitString[0], "$1")
278275

279276
// Parse the value
280-
value = parseValue(splitString[1], envMap, lookupFn)
281-
return
277+
value := parseValue(splitString[1], envMap, lookupFn)
278+
279+
return key, value, nil
282280
}
283281

284282
var (
@@ -351,7 +349,7 @@ func doubleQuoteEscape(line string) string {
351349
if c == '\r' {
352350
toReplace = `\r`
353351
}
354-
line = strings.Replace(line, string(c), toReplace, -1)
352+
line = strings.ReplaceAll(line, string(c), toReplace)
355353
}
356354
return line
357355
}

golangci.yml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,23 @@ run:
44
linters:
55
disable-all: true
66
enable:
7+
- gocritic
78
- gofmt
89
- goimports
910
- revive
1011
- gosimple
1112
- ineffassign
1213
- misspell
1314
- govet
15+
linters-settings:
16+
gocritic:
17+
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
18+
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
19+
enabled-tags:
20+
- diagnostic
21+
- opinionated
22+
- style
23+
disabled-checks:
24+
- paramTypeCombine
25+
- unnamedResult
26+
- whyNoLint

loader/full-struct_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ func services(workingDir, homeDir string) []types.ServiceConfig {
6767
Target: "my_secret",
6868
UID: "103",
6969
GID: "103",
70-
Mode: uint32Ptr(0440),
70+
Mode: uint32Ptr(0o440),
7171
},
7272
},
7373
Tags: []string{"foo:v1.0.0", "docker.io/username/foo:my-other-tag", "full_example_project_name:1.0.0"},
@@ -85,7 +85,7 @@ func services(workingDir, homeDir string) []types.ServiceConfig {
8585
Target: "/my_config",
8686
UID: "103",
8787
GID: "103",
88-
Mode: uint32Ptr(0440),
88+
Mode: uint32Ptr(0o440),
8989
},
9090
},
9191
ContainerName: "my-web-container",
@@ -389,7 +389,7 @@ func services(workingDir, homeDir string) []types.ServiceConfig {
389389
Target: "my_secret",
390390
UID: "103",
391391
GID: "103",
392-
Mode: uint32Ptr(0440),
392+
Mode: uint32Ptr(0o440),
393393
},
394394
},
395395
SecurityOpt: []string{
@@ -420,7 +420,7 @@ func services(workingDir, homeDir string) []types.ServiceConfig {
420420
{Source: "/opt/data", Target: "/var/lib/mysql", Type: "bind", Bind: &types.ServiceVolumeBind{CreateHostPath: true}},
421421
{Source: workingDir, Target: "/code", Type: "bind", Bind: &types.ServiceVolumeBind{CreateHostPath: true}},
422422
{Source: filepath.Join(workingDir, "static"), Target: "/var/www/html", Type: "bind", Bind: &types.ServiceVolumeBind{CreateHostPath: true}},
423-
{Source: filepath.Join(homeDir, "/configs"), Target: "/etc/configs", Type: "bind", ReadOnly: true, Bind: &types.ServiceVolumeBind{CreateHostPath: true}},
423+
{Source: filepath.Join(homeDir, "configs"), Target: "/etc/configs", Type: "bind", ReadOnly: true, Bind: &types.ServiceVolumeBind{CreateHostPath: true}},
424424
{Source: "datavolume", Target: "/var/lib/mysql", Type: "volume", Volume: &types.ServiceVolumeVolume{}},
425425
{Source: filepath.Join(workingDir, "opt"), Target: "/opt", Consistency: "cached", Type: "bind"},
426426
{Target: "/opt", Type: "tmpfs", Tmpfs: &types.ServiceVolumeTmpfs{
@@ -1003,7 +1003,7 @@ x-nested:
10031003
bar: baz
10041004
foo: bar
10051005
`,
1006-
filepath.Join(workingDir),
1006+
workingDir,
10071007
filepath.Join(workingDir, "static"),
10081008
filepath.Join(homeDir, "configs"),
10091009
filepath.Join(workingDir, "opt"),

loader/loader.go

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,11 @@
1717
package loader
1818

1919
import (
20+
"bytes"
2021
"fmt"
21-
"io/ioutil"
22+
"io"
2223
"os"
23-
"path"
24+
paths "path"
2425
"path/filepath"
2526
"reflect"
2627
"regexp"
@@ -524,12 +525,12 @@ func loadServiceWithExtends(filename, name string, servicesDict map[string]inter
524525
// Resolve the path to the imported file, and load it.
525526
baseFilePath := absPath(workingDir, *file)
526527

527-
bytes, err := ioutil.ReadFile(baseFilePath)
528+
b, err := os.ReadFile(baseFilePath)
528529
if err != nil {
529530
return nil, err
530531
}
531532

532-
baseFile, err := parseConfig(bytes, opts)
533+
baseFile, err := parseConfig(b, opts)
533534
if err != nil {
534535
return nil, err
535536
}
@@ -629,8 +630,16 @@ func resolveEnvironment(serviceConfig *types.ServiceConfig, workingDir string, l
629630
if err != nil {
630631
return err
631632
}
632-
defer file.Close()
633-
fileVars, err := dotenv.ParseWithLookup(file, dotenv.LookupFn(lookupEnv))
633+
634+
b, err := io.ReadAll(file)
635+
if err != nil {
636+
return err
637+
}
638+
639+
// Do not defer to avoid it inside a loop
640+
file.Close() //nolint:errcheck
641+
642+
fileVars, err := dotenv.ParseWithLookup(bytes.NewBuffer(b), dotenv.LookupFn(lookupEnv))
634643
if err != nil {
635644
return err
636645
}
@@ -656,7 +665,7 @@ func resolveVolumePath(volume types.ServiceVolumeConfig, workingDir string, look
656665
// Note that this is not required for Docker for Windows when specifying
657666
// a local Windows path, because Docker for Windows translates the Windows
658667
// path into a valid path within the VM.
659-
if !path.IsAbs(filePath) && !isAbs(filePath) {
668+
if !paths.IsAbs(filePath) && !isAbs(filePath) {
660669
filePath = absPath(workingDir, filePath)
661670
}
662671
volume.Source = filePath
@@ -810,10 +819,8 @@ func loadFileObjectConfig(name string, objType string, obj types.FileObjectConfi
810819
logrus.Warnf("%[1]s %[2]s: %[1]s.external.name is deprecated in favor of %[1]s.name", objType, name)
811820
obj.Name = obj.External.Name
812821
obj.External.Name = ""
813-
} else {
814-
if obj.Name == "" {
815-
obj.Name = name
816-
}
822+
} else if obj.Name == "" {
823+
obj.Name = name
817824
}
818825
// if not "external: true"
819826
case obj.Driver != "":
@@ -945,7 +952,7 @@ func cleanTarget(target string) string {
945952
if target == "" {
946953
return ""
947954
}
948-
return path.Clean(target)
955+
return paths.Clean(target)
949956
}
950957

951958
var transformBuildConfig TransformerFunc = func(data interface{}) (interface{}, error) {

loader/loader_test.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package loader
1919
import (
2020
"bytes"
2121
"fmt"
22-
"io/ioutil"
2322
"os"
2423
"sort"
2524
"strings"
@@ -926,7 +925,7 @@ func uint32Ptr(value uint32) *uint32 {
926925
}
927926

928927
func TestFullExample(t *testing.T) {
929-
b, err := ioutil.ReadFile("full-example.yml")
928+
b, err := os.ReadFile("full-example.yml")
930929
assert.NilError(t, err)
931930

932931
homeDir, err := os.UserHomeDir()
@@ -1728,13 +1727,13 @@ secrets:
17281727
}
17291728

17301729
func TestComposeFileWithVersion(t *testing.T) {
1731-
bytes, err := ioutil.ReadFile("testdata/compose-test-with-version.yaml")
1730+
b, err := os.ReadFile("testdata/compose-test-with-version.yaml")
17321731
assert.NilError(t, err)
17331732

17341733
homeDir, err := os.UserHomeDir()
17351734
assert.NilError(t, err)
17361735
env := map[string]string{"HOME": homeDir, "QUX": "qux_from_environment"}
1737-
config, err := loadYAMLWithEnv(string(bytes), env)
1736+
config, err := loadYAMLWithEnv(string(b), env)
17381737
assert.NilError(t, err)
17391738

17401739
workingDir, err := os.Getwd()
@@ -1751,13 +1750,13 @@ func TestComposeFileWithVersion(t *testing.T) {
17511750
}
17521751

17531752
func TestLoadWithExtends(t *testing.T) {
1754-
bytes, err := ioutil.ReadFile("testdata/compose-test-extends.yaml")
1753+
b, err := os.ReadFile("testdata/compose-test-extends.yaml")
17551754
assert.NilError(t, err)
17561755

17571756
configDetails := types.ConfigDetails{
17581757
WorkingDir: "testdata",
17591758
ConfigFiles: []types.ConfigFile{
1760-
{Filename: "testdata/compose-test-extends.yaml", Content: bytes},
1759+
{Filename: "testdata/compose-test-extends.yaml", Content: b},
17611760
},
17621761
}
17631762

@@ -1896,7 +1895,7 @@ services:
18961895
assert.NilError(t, err)
18971896
svc, err := actual.GetService("test")
18981897
assert.NilError(t, err)
1899-
assert.Check(t, nil == svc.Build.SSH)
1898+
assert.Check(t, svc.Build.SSH == nil)
19001899
}
19011900

19021901
func TestLoadSSHWithoutValueInBuildConfig(t *testing.T) {

loader/merge.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -299,15 +299,15 @@ func mergeLoggingConfig(dst, src reflect.Value) error {
299299
return nil
300300
}
301301

302-
// nolint: unparam
302+
//nolint: unparam
303303
func mergeUlimitsConfig(dst, src reflect.Value) error {
304304
if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() {
305305
dst.Elem().Set(src.Elem())
306306
}
307307
return nil
308308
}
309309

310-
// nolint: unparam
310+
//nolint: unparam
311311
func mergeServiceNetworkConfig(dst, src reflect.Value) error {
312312
if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() {
313313
dst.Elem().FieldByName("Aliases").Set(src.Elem().FieldByName("Aliases"))

loader/validate.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,9 @@ func checkConsistency(project *types.Project) error {
5252
}
5353

5454
for _, volume := range s.Volumes {
55-
switch volume.Type {
56-
case types.VolumeTypeVolume:
57-
if volume.Source != "" { // non anonymous volumes
58-
if _, ok := project.Volumes[volume.Source]; !ok {
59-
return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q refers to undefined volume %s", s.Name, volume.Source))
60-
}
55+
if volume.Type == types.VolumeTypeVolume && volume.Source != "" { // non anonymous volumes
56+
if _, ok := project.Volumes[volume.Source]; !ok {
57+
return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q refers to undefined volume %s", s.Name, volume.Source))
6158
}
6259
}
6360
}

0 commit comments

Comments
 (0)