Skip to content

Commit 08c721e

Browse files
authored
Merge pull request #483 from numtide/more-linter
Enable more golangci-linter
2 parents 3a8454e + 1eeee48 commit 08c721e

File tree

14 files changed

+123
-82
lines changed

14 files changed

+123
-82
lines changed

.golangci.yml

Lines changed: 21 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,23 @@
11
# taken from https://github.com/nix-community/go-nix/blob/main/.golangci.yml
22
linters:
3-
enable:
4-
- errname
5-
- exhaustive
6-
- gci
7-
- gochecknoglobals
8-
- gochecknoinits
9-
- goconst
10-
- godot
11-
- gofumpt
12-
- goheader
13-
- goimports
14-
- gosec
15-
- importas
16-
- ireturn
17-
- lll
18-
- makezero
19-
- misspell
20-
- nakedret
21-
- nestif
22-
- nilerr
23-
- nilnil
24-
- nlreturn
25-
- noctx
26-
- nolintlint
27-
- prealloc
28-
- predeclared
29-
- revive
30-
- rowserrcheck
31-
- stylecheck
32-
- tagliatelle
33-
- tenv
34-
- testpackage
35-
- unconvert
36-
- unparam
37-
- wastedassign
38-
- whitespace
39-
- wsl
3+
enable-all: true
4+
disable:
5+
- depguard
6+
- execinquery
7+
- exhaustruct
8+
- exportloopref
9+
- funlen
10+
- godox
11+
- gomnd
12+
- mnd
13+
- varnamelen
14+
- forbidigo
15+
- gocognit
16+
- gocyclo
17+
- cyclop
18+
- err113
19+
- maintidx
20+
# would be nice to have but too many tests depend on environment variables, which is not allowed for t.Parallel()
21+
- paralleltest
22+
# would be also nice to enable because I also found some cases confusing
23+
- nonamedreturns

cmd/format/format.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ func Run(v *viper.Viper, statz *stats.Stats, cmd *cobra.Command, paths []string)
123123

124124
if walkType == walk.Stdin && len(paths) != 1 {
125125
// check we have only received one path arg which we use for the file extension / matching to formatters
126-
return fmt.Errorf("exactly one path should be specified when using the --stdin flag")
126+
return errors.New("exactly one path should be specified when using the --stdin flag")
127127
}
128128

129129
// checks all paths are contained within the tree root and exist
@@ -136,7 +136,7 @@ func Run(v *viper.Viper, statz *stats.Stats, cmd *cobra.Command, paths []string)
136136

137137
relativePath, err := filepath.Rel(cfg.TreeRoot, absolutePath)
138138
if err != nil {
139-
return fmt.Errorf("error computing relative path from %s to %s: %s", cfg.TreeRoot, absolutePath, err)
139+
return fmt.Errorf("error computing relative path from %s to %s: %w", cfg.TreeRoot, absolutePath, err)
140140
}
141141

142142
if strings.HasPrefix(relativePath, "..") {
@@ -204,7 +204,7 @@ func Run(v *viper.Viper, statz *stats.Stats, cmd *cobra.Command, paths []string)
204204

205205
if formatErr != nil {
206206
// return an error if any formatting failures were detected
207-
return formatErr
207+
return formatErr //nolint:wrapcheck
208208
} else if cfg.FailOnChange && statz.Value(stats.Changed) != 0 {
209209
// if fail on change has been enabled, check that no files were actually changed, throwing an error if so
210210
return ErrFailOnChange

cmd/root.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ func NewRoot() (*cobra.Command, *stats.Stats) {
3232

3333
// create out root command
3434
cmd := &cobra.Command{
35-
Use: fmt.Sprintf("%s <paths...>", build.Name),
35+
Use: build.Name + " <paths...>",
3636
Short: "One CLI to format your repo",
3737
Version: build.Version,
3838
RunE: func(cmd *cobra.Command, args []string) error {
@@ -91,7 +91,12 @@ func runE(v *viper.Viper, statz *stats.Stats, cmd *cobra.Command, args []string)
9191
if init, err := flags.GetBool("init"); err != nil {
9292
return fmt.Errorf("failed to read init flag: %w", err)
9393
} else if init {
94-
return _init.Run()
94+
err := _init.Run()
95+
if err != nil {
96+
return fmt.Errorf("failed to run init command: %w", err)
97+
}
98+
99+
return nil
95100
}
96101

97102
// otherwise attempt to load the config file
@@ -149,5 +154,5 @@ func runE(v *viper.Viper, statz *stats.Stats, cmd *cobra.Command, args []string)
149154
}
150155

151156
// format
152-
return format.Run(v, statz, cmd, args)
157+
return format.Run(v, statz, cmd, args) //nolint:wrapcheck
153158
}

cmd/root_test.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ func TestOnUnmatched(t *testing.T) {
8080
// should exit with error when using fatal
8181
t.Run("fatal", func(t *testing.T) {
8282
errorFn := func(err error) {
83-
as.ErrorContains(err, fmt.Sprintf("no formatter for path: %s", expectedPaths[0]))
83+
as.ErrorContains(err, "no formatter for path: "+expectedPaths[0])
8484
}
8585

8686
treefmt(t, withArgs("--on-unmatched", "fatal"), withError(errorFn))
@@ -718,6 +718,7 @@ func TestChangeWorkingDirectory(t *testing.T) {
718718
})
719719

720720
execute := func(t *testing.T, configFile string, env bool) {
721+
t.Helper()
721722
t.Run(configFile, func(t *testing.T) {
722723
// capture current cwd, so we can replace it after the test is finished
723724
cwd, err := os.Getwd()
@@ -1075,7 +1076,7 @@ func TestCacheBusting(t *testing.T) {
10751076
formatter, err := os.OpenFile(scriptPath, os.O_WRONLY|os.O_APPEND, 0o755)
10761077
as.NoError(err, "failed to open elm formatter")
10771078

1078-
_, err = formatter.Write([]byte(" ")) // add some whitespace
1079+
_, err = formatter.WriteString(" ") // add some whitespace
10791080
as.NoError(err, "failed to append to elm formatter")
10801081
as.NoError(formatter.Close(), "failed to close elm formatter")
10811082

@@ -1839,6 +1840,8 @@ func withConfigFunc(path string, fn func() *config.Config) option {
18391840
}
18401841

18411842
func withStats(t *testing.T, expected map[stats.Type]int) option {
1843+
t.Helper()
1844+
18421845
return func(o *options) {
18431846
o.assertStats = func(s *stats.Stats) {
18441847
for k, v := range expected {
@@ -1855,6 +1858,8 @@ func withError(fn func(error)) option {
18551858
}
18561859

18571860
func withNoError(t *testing.T) option {
1861+
t.Helper()
1862+
18581863
return func(o *options) {
18591864
o.assertError = func(err error) {
18601865
require.NoError(t, err)

config/config.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,20 @@ import (
1414
// Config is used to represent the list of configured Formatters.
1515
type Config struct {
1616
AllowMissingFormatter bool `mapstructure:"allow-missing-formatter" toml:"allow-missing-formatter,omitempty"`
17-
CI bool `mapstructure:"ci" toml:"-"` // not allowed in config
18-
ClearCache bool `mapstructure:"clear-cache" toml:"-"` // not allowed in config
19-
CPUProfile string `mapstructure:"cpu-profile" toml:"cpu-profile,omitempty"`
20-
Excludes []string `mapstructure:"excludes" toml:"excludes,omitempty"`
21-
FailOnChange bool `mapstructure:"fail-on-change" toml:"fail-on-change,omitempty"`
22-
Formatters []string `mapstructure:"formatters" toml:"formatters,omitempty"`
23-
NoCache bool `mapstructure:"no-cache" toml:"-"` // not allowed in config
24-
OnUnmatched string `mapstructure:"on-unmatched" toml:"on-unmatched,omitempty"`
25-
TreeRoot string `mapstructure:"tree-root" toml:"tree-root,omitempty"`
26-
TreeRootFile string `mapstructure:"tree-root-file" toml:"tree-root-file,omitempty"`
27-
Verbose uint8 `mapstructure:"verbose" toml:"verbose,omitempty"`
28-
Walk string `mapstructure:"walk" toml:"walk,omitempty"`
29-
WorkingDirectory string `mapstructure:"working-dir" toml:"-"`
30-
Stdin bool `mapstructure:"stdin" toml:"-"` // not allowed in config
17+
CI bool `mapstructure:"ci" toml:"-"` // not allowed in config
18+
ClearCache bool `mapstructure:"clear-cache" toml:"-"` // not allowed in config
19+
CPUProfile string `mapstructure:"cpu-profile" toml:"cpu-profile,omitempty"`
20+
Excludes []string `mapstructure:"excludes" toml:"excludes,omitempty"`
21+
FailOnChange bool `mapstructure:"fail-on-change" toml:"fail-on-change,omitempty"`
22+
Formatters []string `mapstructure:"formatters" toml:"formatters,omitempty"`
23+
NoCache bool `mapstructure:"no-cache" toml:"-"` // not allowed in config
24+
OnUnmatched string `mapstructure:"on-unmatched" toml:"on-unmatched,omitempty"`
25+
TreeRoot string `mapstructure:"tree-root" toml:"tree-root,omitempty"`
26+
TreeRootFile string `mapstructure:"tree-root-file" toml:"tree-root-file,omitempty"`
27+
Verbose uint8 `mapstructure:"verbose" toml:"verbose,omitempty"`
28+
Walk string `mapstructure:"walk" toml:"walk,omitempty"`
29+
WorkingDirectory string `mapstructure:"working-dir" toml:"-"`
30+
Stdin bool `mapstructure:"stdin" toml:"-"` // not allowed in config
3131

3232
FormatterConfigs map[string]*Formatter `mapstructure:"formatter" toml:"formatter,omitempty"`
3333

config/config_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -670,7 +670,7 @@ func TestSampleConfigFile(t *testing.T) {
670670
as.True(ok, "shfmt formatter not found")
671671
as.Equal("shfmt", shfmt.Command)
672672
as.Equal(2, shfmt.Priority)
673-
as.Equal(shfmt.Options, []string{"-i", "2", "-s", "-w"})
673+
as.Equal([]string{"-i", "2", "-s", "-w"}, shfmt.Options)
674674
as.Equal([]string{"*.sh"}, shfmt.Includes)
675675
as.Nil(shfmt.Excludes)
676676

format/formatter.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"os"
99
"os/exec"
1010
"regexp"
11+
"strconv"
1112
"strings"
1213
"time"
1314

@@ -61,7 +62,7 @@ func (f *Formatter) Hash(h hash.Hash) error {
6162
// if options change, the outcome of applying the formatter might be different
6263
h.Write([]byte(strings.Join(f.config.Options, " ")))
6364
// if priority changes, the outcome of applying a sequence of formatters might be different
64-
h.Write([]byte(fmt.Sprintf("%d", f.config.Priority)))
65+
h.Write([]byte(strconv.Itoa(f.config.Priority)))
6566

6667
// stat the formatter's executable
6768
info, err := os.Lstat(f.executable)
@@ -163,7 +164,7 @@ func newFormatter(
163164
if cfg.Priority > 0 {
164165
f.log = log.WithPrefix(fmt.Sprintf("formatter | %s[%d]", name, cfg.Priority))
165166
} else {
166-
f.log = log.WithPrefix(fmt.Sprintf("formatter | %s", name))
167+
f.log = log.WithPrefix("formatter | " + name)
167168
}
168169

169170
// check there is at least one include

test/test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,15 @@ func WriteConfig(t *testing.T, path string, cfg *config.Config) {
2929
}
3030

3131
func TempExamples(t *testing.T) string {
32+
t.Helper()
3233
tempDir := t.TempDir()
3334
TempExamplesInDir(t, tempDir)
3435

3536
return tempDir
3637
}
3738

3839
func TempExamplesInDir(t *testing.T, dir string) {
40+
t.Helper()
3941
require.NoError(t, cp.Copy("../test/examples", dir), "failed to copy test data to dir")
4042

4143
// we have second precision mod time tracking, so we wait a second before returning, so we don't trigger false

walk/cache/cache.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,17 @@ func Open(root string) (*bolt.DB, error) {
3333
// open db
3434
db, err := bolt.Open(path, 0o600, &bolt.Options{Timeout: 1 * time.Second})
3535
if err != nil {
36-
return nil, err
36+
return nil, fmt.Errorf("failed to open cache db: %w", err)
3737
}
3838

3939
// ensure bucket exist
4040
err = db.Update(func(tx *bolt.Tx) error {
4141
_, err := tx.CreateBucketIfNotExists([]byte(bucketPaths))
42+
if err != nil {
43+
return fmt.Errorf("failed to create bucket: %w", err)
44+
}
4245

43-
return err
46+
return nil
4447
})
4548
if err != nil {
4649
return nil, fmt.Errorf("failed to create bucket: %w", err)
@@ -65,7 +68,17 @@ func deleteAll(bucket *bolt.Bucket) error {
6568
}
6669

6770
func Clear(db *bolt.DB) error {
68-
return db.Update(func(tx *bolt.Tx) error {
69-
return deleteAll(PathsBucket(tx))
71+
err := db.Update(func(tx *bolt.Tx) error {
72+
err := deleteAll(PathsBucket(tx))
73+
if err != nil {
74+
return fmt.Errorf("failed to clear cache: %w", err)
75+
}
76+
77+
return nil
7078
})
79+
if err != nil {
80+
return fmt.Errorf("failed to clear cache: %w", err)
81+
}
82+
83+
return nil
7184
}

walk/cached.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ func (c *CachedReader) Read(ctx context.Context, files []*File) (n int, err erro
9999
n, err = c.delegate.Read(ctx, files)
100100
c.log.Debugf("read %d files from delegate", n)
101101

102-
for i := 0; i < n; i++ {
102+
for i := range n {
103103
file := files[i]
104104

105105
file.CachedFormatSignature = bucket.Get([]byte(file.RelPath))
@@ -115,15 +115,15 @@ func (c *CachedReader) Read(ctx context.Context, files []*File) (n int, err erro
115115
}
116116

117117
if errors.Is(err, io.EOF) {
118-
return err
118+
return err //nolint:wrapcheck
119119
} else if err != nil {
120120
return fmt.Errorf("failed to read files from delegate: %w", err)
121121
}
122122

123123
return nil
124124
})
125125

126-
return n, err
126+
return n, err //nolint:wrapcheck
127127
}
128128

129129
// Close waits for any processing to complete.
@@ -132,7 +132,12 @@ func (c *CachedReader) Close() error {
132132
close(c.updateCh)
133133

134134
// wait for any pending releases to be processed
135-
return c.eg.Wait()
135+
err := c.eg.Wait()
136+
if err != nil {
137+
return fmt.Errorf("failed to wait for processing to complete: %w", err)
138+
}
139+
140+
return nil
136141
}
137142

138143
// NewCachedReader creates a cache Reader instance, backed by a bolt DB and delegating reads to delegate.

0 commit comments

Comments
 (0)