Skip to content

Commit b210ef1

Browse files
committed
Linter fixes
1 parent 6e85de7 commit b210ef1

File tree

7 files changed

+82
-113
lines changed

7 files changed

+82
-113
lines changed

api.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ func PutIssueBuffer(issues []Issue) {
3636
issues[i].MatchingConst = ""
3737
issues[i].Str = ""
3838
}
39-
IssuePool.Put(issues[:0]) // Reset length but keep capacity
39+
// Return the slice to the pool
40+
issuesCopy := make([]Issue, 0, cap(issues))
41+
IssuePool.Put(&issuesCopy)
4042
}
4143

4244
// Config contains all configuration options for the goconst analyzer.

benchmarks_test.go

+13-3
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,11 @@ func BenchmarkParseDirectoryParallel(b *testing.B) {
185185
if err != nil {
186186
b.Fatalf("Failed to create temp dir: %v", err)
187187
}
188-
defer os.RemoveAll(tempDir)
188+
defer func() {
189+
if err := os.RemoveAll(tempDir); err != nil {
190+
b.Errorf("Failed to remove temp dir: %v", err)
191+
}
192+
}()
189193

190194
// Create subdirectories to test recursive processing
191195
subdirCount := 5
@@ -360,10 +364,16 @@ func BenchmarkFileReadingPerformance(b *testing.B) {
360364
if _, err := tempFile.Write(content); err != nil {
361365
b.Fatalf("Failed to write to temp file: %v", err)
362366
}
363-
tempFile.Close()
367+
if err := tempFile.Close(); err != nil {
368+
b.Fatalf("Failed to close temp file: %v", err)
369+
}
364370

365371
// Clean up the temp file when benchmark is done
366-
defer os.Remove(fileName)
372+
defer func() {
373+
if err := os.Remove(fileName); err != nil {
374+
b.Errorf("Failed to remove temp file: %v", err)
375+
}
376+
}()
367377

368378
// Benchmark the optimized file reading
369379
b.Run(fmt.Sprintf("OptimizedIO_%d", size), func(b *testing.B) {

cmd/goconst/main.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,9 @@ func run(path string) (bool, error) {
114114

115115
// usage prints the usage documentation to the specified writer.
116116
func usage(out io.Writer) {
117-
fmt.Fprintf(out, usageDoc)
117+
if _, err := fmt.Fprint(out, usageDoc); err != nil {
118+
log.Printf("Error writing usage doc: %v", err)
119+
}
118120
}
119121

120122
// printOutput formats and displays the analysis results based on the specified output format.
@@ -124,8 +126,8 @@ func printOutput(strs goconst.Strings, consts goconst.Constants, output string)
124126
case "json":
125127
enc := json.NewEncoder(os.Stdout)
126128
err := enc.Encode(struct {
127-
Strings goconst.Strings `json:"strings,omitEmpty"`
128-
Constants goconst.Constants `json:"constants,omitEmpty"`
129+
Strings goconst.Strings `json:"strings,omitempty"`
130+
Constants goconst.Constants `json:"constants,omitempty"`
129131
}{
130132
strs, consts,
131133
})
@@ -161,7 +163,7 @@ func printOutput(strs goconst.Strings, consts goconst.Constants, output string)
161163
}
162164
}
163165
default:
164-
return false, fmt.Errorf(`Unsupported output format: %s`, output)
166+
return false, fmt.Errorf("unsupported output format: %s", output)
165167
}
166168
return len(strs)+len(consts) > 0, nil
167169
}

cmd/goconst/main_test.go

+29-7
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,11 @@ func TestRun(t *testing.T) {
5656
if err != nil {
5757
t.Fatalf("Failed to create temp directory: %v", err)
5858
}
59-
defer os.RemoveAll(tempDir)
59+
defer func() {
60+
if err := os.RemoveAll(tempDir); err != nil {
61+
t.Errorf("Failed to remove temp directory: %v", err)
62+
}
63+
}()
6064

6165
// Create a test file with known constants and repeated strings
6266
testFile := filepath.Join(tempDir, "test.go")
@@ -86,7 +90,11 @@ func TestInvalidOutputFormat(t *testing.T) {
8690
if err != nil {
8791
t.Fatalf("Failed to create temp directory: %v", err)
8892
}
89-
defer os.RemoveAll(tempDir)
93+
defer func() {
94+
if err := os.RemoveAll(tempDir); err != nil {
95+
t.Errorf("Failed to remove temp directory: %v", err)
96+
}
97+
}()
9098

9199
testFile := filepath.Join(tempDir, "simple.go")
92100
testContent := `package test
@@ -122,7 +130,11 @@ func TestOutputFormatting(t *testing.T) {
122130
if err != nil {
123131
t.Fatalf("Failed to create temp directory: %v", err)
124132
}
125-
defer os.RemoveAll(tempDir)
133+
defer func() {
134+
if err := os.RemoveAll(tempDir); err != nil {
135+
t.Errorf("Failed to remove temp directory: %v", err)
136+
}
137+
}()
126138

127139
testFile := filepath.Join(tempDir, "format.go")
128140
testContent := `package test
@@ -163,7 +175,9 @@ func test() {
163175

164176
// Run analysis
165177
hasIssues, err := run(tempDir)
166-
w.Close()
178+
if err := w.Close(); err != nil {
179+
t.Errorf("Failed to close writer: %v", err)
180+
}
167181
out, _ := io.ReadAll(r)
168182
output := string(out)
169183

@@ -209,7 +223,9 @@ func test() {
209223

210224
// Run analysis
211225
hasIssues, err := run(tempDir)
212-
w.Close()
226+
if err := w.Close(); err != nil {
227+
t.Errorf("Failed to close writer: %v", err)
228+
}
213229
out, _ := io.ReadAll(r)
214230
output := string(out)
215231

@@ -241,7 +257,11 @@ func TestGroupedOutput(t *testing.T) {
241257
if err != nil {
242258
t.Fatalf("Failed to create temp directory: %v", err)
243259
}
244-
defer os.RemoveAll(tempDir)
260+
defer func() {
261+
if err := os.RemoveAll(tempDir); err != nil {
262+
t.Errorf("Failed to remove temp directory: %v", err)
263+
}
264+
}()
245265

246266
testFile := filepath.Join(tempDir, "grouped.go")
247267
testContent := `package test
@@ -279,7 +299,9 @@ func test() {
279299

280300
// Run analysis
281301
_, err := run(tempDir)
282-
w.Close()
302+
if err := w.Close(); err != nil {
303+
t.Errorf("Failed to close writer: %v", err)
304+
}
283305
out, _ := io.ReadAll(r)
284306
output := string(out)
285307

parser.go

+11-86
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,8 @@ func GetByteBuffer() []byte {
9595

9696
// PutByteBuffer returns a byte buffer to the pool
9797
func PutByteBuffer(buf []byte) {
98-
ByteBufferPool.Put(buf[:0]) // Reset length but keep capacity
98+
bufCopy := make([]byte, 0, cap(buf))
99+
ByteBufferPool.Put(&bufCopy)
99100
}
100101

101102
// GetStringBuffer retrieves a string slice from the pool
@@ -105,7 +106,8 @@ func GetStringBuffer() []string {
105106

106107
// PutStringBuffer returns a string slice to the pool
107108
func PutStringBuffer(slice []string) {
108-
StringBufferPool.Put(slice[:0]) // Reset length but keep capacity
109+
sliceCopy := make([]string, 0, cap(slice))
110+
StringBufferPool.Put(&sliceCopy)
109111
}
110112

111113
// GetExtendedPosBuffer retrieves an ExtendedPos slice from the pool
@@ -115,7 +117,8 @@ func GetExtendedPosBuffer() []ExtendedPos {
115117

116118
// PutExtendedPosBuffer returns an ExtendedPos slice to the pool
117119
func PutExtendedPosBuffer(slice []ExtendedPos) {
118-
ExtendedPosPool.Put(slice[:0]) // Reset length but keep capacity
120+
sliceCopy := make([]ExtendedPos, 0, cap(slice))
121+
ExtendedPosPool.Put(&sliceCopy)
119122
}
120123

121124
const (
@@ -596,7 +599,11 @@ func (p *Parser) readFileEfficiently(path string) ([]byte, error) {
596599
if err != nil {
597600
return nil, err
598601
}
599-
defer f.Close()
602+
defer func() {
603+
if closeErr := f.Close(); closeErr != nil {
604+
log.Printf("Error closing file: %v", closeErr)
605+
}
606+
}()
600607

601608
// Get file size to allocate buffer exactly once
602609
info, err := f.Stat()
@@ -730,88 +737,6 @@ func (p *Parser) ProcessResults() {
730737
}
731738
}
732739

733-
func (p *Parser) parseDir(dir string) error {
734-
fset := token.NewFileSet()
735-
pkgs, err := parser.ParseDir(fset, dir, func(info os.FileInfo) bool {
736-
valid, name := true, info.Name()
737-
738-
if p.ignoreTests {
739-
if strings.HasSuffix(name, testSuffix) {
740-
valid = false
741-
}
742-
}
743-
744-
if p.ignoreRegex != nil {
745-
if p.ignoreRegex.MatchString(dir + name) {
746-
valid = false
747-
}
748-
} else if len(p.ignore) != 0 {
749-
// Fallback to non-compiled regex if compilation failed
750-
match, err := regexp.MatchString(p.ignore, dir+name)
751-
if err != nil {
752-
log.Fatal(err)
753-
return true
754-
}
755-
if match {
756-
valid = false
757-
}
758-
}
759-
760-
return valid
761-
}, 0)
762-
if err != nil {
763-
return err
764-
}
765-
766-
// Process files concurrently with a workgroup
767-
var wg sync.WaitGroup
768-
769-
// Create a flattened list of all files
770-
type fileInfo struct {
771-
pkg string
772-
fileName string
773-
file *ast.File
774-
}
775-
776-
// Pre-allocate the slice with expected capacity to avoid resizing
777-
files := make([]fileInfo, 0, len(pkgs)*10) // Assuming average of 10 files per package
778-
for pkgName, pkg := range pkgs {
779-
for fn, f := range pkg.Files {
780-
files = append(files, fileInfo{
781-
pkg: pkgName,
782-
fileName: fn,
783-
file: f,
784-
})
785-
}
786-
}
787-
788-
// Process files concurrently using a semaphore to limit concurrency
789-
sem := make(chan struct{}, p.maxConcurrency)
790-
for _, fi := range files {
791-
wg.Add(1)
792-
sem <- struct{}{} // acquire semaphore
793-
794-
go func(pkg, fn string, f *ast.File) {
795-
defer func() {
796-
<-sem // release semaphore
797-
wg.Done()
798-
}()
799-
800-
// Create a separate visitor for this file with pre-compiled regex
801-
ast.Walk(&treeVisitor{
802-
fileSet: fset,
803-
packageName: pkg,
804-
fileName: fn,
805-
p: p,
806-
ignoreRegex: p.ignoreStringsRegex,
807-
}, f)
808-
}(fi.pkg, fi.fileName, fi.file)
809-
}
810-
811-
wg.Wait()
812-
return nil
813-
}
814-
815740
// Strings maps string literals to their positions in the code.
816741
type Strings map[string][]ExtendedPos
817742

parser_test.go

+15-3
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,11 @@ func TestParseTree(t *testing.T) {
209209
if err != nil {
210210
t.Fatalf("Failed to create temp directory: %v", err)
211211
}
212-
defer os.RemoveAll(tempDir)
212+
defer func() {
213+
if err := os.RemoveAll(tempDir); err != nil {
214+
t.Errorf("Failed to remove temp directory: %v", err)
215+
}
216+
}()
213217

214218
// Create a test file with known constants and repeated strings
215219
testFile := filepath.Join(tempDir, "test.go")
@@ -453,7 +457,11 @@ func BenchmarkFileTraversal(b *testing.B) {
453457
if err != nil {
454458
b.Fatalf("Failed to create temp directory: %v", err)
455459
}
456-
defer os.RemoveAll(tempDir)
460+
defer func() {
461+
if err := os.RemoveAll(tempDir); err != nil {
462+
b.Errorf("Failed to remove temp directory: %v", err)
463+
}
464+
}()
457465

458466
// Create a nested directory structure with test files
459467
createBenchmarkFiles(b, tempDir, 5, 10, 5)
@@ -666,7 +674,11 @@ func BenchmarkFileReading(b *testing.B) {
666674
if err != nil {
667675
b.Fatalf("Failed to create temp file: %v", err)
668676
}
669-
defer os.Remove(tempFile.Name())
677+
defer func() {
678+
if err := os.Remove(tempFile.Name()); err != nil {
679+
b.Errorf("Failed to remove temp file: %v", err)
680+
}
681+
}()
670682
tempFiles[i] = tempFile.Name()
671683

672684
// Write a large Go file for testing

visitor.go

+5-9
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,13 @@ import (
88
"strings"
99
)
1010

11-
// treeVisitor carries the package name and file name
12-
// for passing it to the imports map, and the fileSet for
13-
// retrieving the token.Position.
11+
// treeVisitor is used to walk the AST and find strings that could be constants.
1412
type treeVisitor struct {
15-
p *Parser
16-
fileSet *token.FileSet
17-
packageName, fileName string
18-
// Pre-compiled regex for early filtering
13+
fileSet *token.FileSet
14+
packageName string
15+
fileName string
16+
p *Parser
1917
ignoreRegex *regexp.Regexp
20-
// Reusable buffer to avoid allocations when unquoting strings
21-
buffer []byte
2218
}
2319

2420
// Visit browses the AST tree for strings that could be potentially

0 commit comments

Comments
 (0)