Skip to content

Commit

Permalink
Fix closeafterusage linter for underscores in assign statements
Browse files Browse the repository at this point in the history
Also adds some additional test cases encountered
  • Loading branch information
josephschorr committed May 22, 2023
1 parent 37114b6 commit f1cb7ee
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 9 deletions.
10 changes: 1 addition & 9 deletions tools/analyzers/closeafterusagecheck/closeafterusagecheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package closeafterusagecheck

import (
"flag"
"fmt"
"go/ast"
"strings"

Expand Down Expand Up @@ -114,7 +113,7 @@ func Analyzer() *analysis.Analyzer {
for _, expr := range s.Lhs {
foundType := pass.TypesInfo.TypeOf(expr)
if foundType == nil {
return false
continue
}

varTypeString := foundType.String()
Expand Down Expand Up @@ -205,10 +204,3 @@ func min(x int, y int) int {
}
return x
}

func printTypes(nodes []ast.Node) {
for _, n := range nodes {
fmt.Printf("%T, ", n)
}
fmt.Println()
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,18 @@ type SomeIterator struct{}
func (si *SomeIterator) Close() {
}

func (si *SomeIterator) Err() error {
return nil
}

func (si *SomeIterator) Next() any {
return nil
}

func (si *SomeIterator) Cursor() (int, error) {
return 42, nil
}

func MissingNonDeferClose() {
si := CreateIterator() // want "variable MissingNonDeferClose.si is missing required non-defer-ed"
defer si.Close()
Expand Down Expand Up @@ -109,6 +117,44 @@ func SentToFunctionUnderSwitch() {
}
}

func AccessedAfterLoop() error {
cur := 0
for {
si, err := CreateIteratorOrError()
if err != nil {
return nil
}

for tpl := si.Next(); tpl != nil; tpl = si.Next() {
// do nothing
}
if si.Err() != nil {
return si.Err()
}

if cur == 0 {
si.Close()
continue
}

cur, err = si.Cursor()
si.Close()

if err != nil {
return err
}
fmt.Println(cur)
}
}

func AccessedDirectly() error {
var err error
si := CreateIterator()
_, err = si.Cursor()
si.Close()
return err
}

func ThirdFunction(si *SomeIterator) error {
return nil
}
Expand All @@ -120,3 +166,7 @@ func AnotherFunction(si *SomeIterator) {
func CreateIterator() *SomeIterator {
return &SomeIterator{}
}

func CreateIteratorOrError() (*SomeIterator, error) {
return &SomeIterator{}, nil
}

0 comments on commit f1cb7ee

Please sign in to comment.