-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: handle gno specific path imports (#26)
* fix: handle gno specific path imports * ignore to check usage when aliased as _
- Loading branch information
Showing
6 changed files
with
262 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
package lints | ||
|
||
import ( | ||
"fmt" | ||
"go/ast" | ||
"go/parser" | ||
"go/token" | ||
"os" | ||
"path/filepath" | ||
"strings" | ||
|
||
tt "github.com/gnoswap-labs/lint/internal/types" | ||
) | ||
|
||
const ( | ||
GNO_PKG_PREFIX = "gno.land/" | ||
GNO_STD_PACKAGE = "std" | ||
) | ||
|
||
// Dependency represents an imported package and its usage status. | ||
type Dependency struct { | ||
ImportPath string | ||
IsGno bool | ||
IsUsed bool | ||
IsIgnored bool // alias with `_` should be ignored | ||
} | ||
|
||
type ( | ||
// Dependencies is a map of import paths to their Dependency information. | ||
Dependencies map[string]*Dependency | ||
|
||
// FileMap is a map of filenames to their parsed AST representation. | ||
FileMap map[string]*ast.File | ||
) | ||
|
||
// Package represents a Go/Gno package with its name and files. | ||
type Package struct { | ||
Name string | ||
Files FileMap | ||
} | ||
|
||
// DetectGnoPackageImports analyzes the given file for Gno package imports and returns any issues found. | ||
func DetectGnoPackageImports(filename string) ([]tt.Issue, error) { | ||
dir := filepath.Dir(filename) | ||
|
||
pkg, deps, err := analyzePackage(dir) | ||
if err != nil { | ||
return nil, fmt.Errorf("error analyzing package: %w", err) | ||
} | ||
|
||
issues := runGnoPackageLinter(pkg, deps) | ||
|
||
for i := range issues { | ||
issues[i].Filename = filename | ||
} | ||
|
||
return issues, nil | ||
} | ||
|
||
// parses all gno files and collect their imports and usage. | ||
func analyzePackage(dir string) (*Package, Dependencies, error) { | ||
pkg := &Package{ | ||
Files: make(FileMap), | ||
} | ||
deps := make(Dependencies) | ||
|
||
files, err := filepath.Glob(filepath.Join(dir, "*.gno")) | ||
if err != nil { | ||
return nil, nil, err | ||
} | ||
|
||
// 1. Parse all file contents and collect dependencies | ||
for _, file := range files { | ||
f, err := parseFile(file) | ||
if err != nil { | ||
return nil, nil, err | ||
} | ||
|
||
pkg.Files[file] = f | ||
if pkg.Name == "" { | ||
pkg.Name = f.Name.Name | ||
} | ||
|
||
for _, imp := range f.Imports { | ||
impPath := strings.Trim(imp.Path.Value, `"`) | ||
if _, exists := deps[impPath]; !exists { | ||
deps[impPath] = &Dependency{ | ||
ImportPath: impPath, | ||
IsGno: isGnoPackage(impPath), | ||
IsUsed: false, | ||
IsIgnored: imp.Name != nil && imp.Name.Name == "_", | ||
} | ||
} | ||
} | ||
} | ||
|
||
// 2. Determine which dependencies are used | ||
for _, file := range pkg.Files { | ||
ast.Inspect(file, func(n ast.Node) bool { | ||
switch x := n.(type) { | ||
case *ast.SelectorExpr: | ||
if ident, ok := x.X.(*ast.Ident); ok { | ||
for _, imp := range file.Imports { | ||
if imp.Name != nil && imp.Name.Name == ident.Name { | ||
deps[strings.Trim(imp.Path.Value, `"`)].IsUsed = true | ||
} else if lastPart := getLastPart(strings.Trim(imp.Path.Value, `"`)); lastPart == ident.Name { | ||
deps[strings.Trim(imp.Path.Value, `"`)].IsUsed = true | ||
} | ||
} | ||
} | ||
} | ||
return true | ||
}) | ||
} | ||
|
||
return pkg, deps, nil | ||
} | ||
|
||
func runGnoPackageLinter(pkg *Package, deps Dependencies) []tt.Issue { | ||
var issues []tt.Issue | ||
|
||
for _, file := range pkg.Files { | ||
ast.Inspect(file, func(n ast.Node) bool { | ||
switch x := n.(type) { | ||
case *ast.SelectorExpr: | ||
// check unused imports | ||
if ident, ok := x.X.(*ast.Ident); ok { | ||
if dep, exists := deps[ident.Name]; exists { | ||
dep.IsUsed = true | ||
} | ||
} | ||
} | ||
return true | ||
}) | ||
} | ||
|
||
for impPath, dep := range deps { | ||
if !dep.IsUsed && !dep.IsIgnored { | ||
issue := tt.Issue{ | ||
Rule: "unused-import", | ||
Message: fmt.Sprintf("unused import: %s", impPath), | ||
} | ||
issues = append(issues, issue) | ||
} | ||
} | ||
|
||
return issues | ||
} | ||
|
||
func isGnoPackage(importPath string) bool { | ||
return strings.HasPrefix(importPath, GNO_PKG_PREFIX) || importPath == GNO_STD_PACKAGE | ||
} | ||
|
||
func parseFile(filename string) (*ast.File, error) { | ||
content, err := os.ReadFile(filename) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
fset := token.NewFileSet() | ||
return parser.ParseFile(fset, filename, content, parser.ParseComments) | ||
} | ||
|
||
func getLastPart(path string) string { | ||
parts := strings.Split(path, "/") | ||
return parts[len(parts)-1] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package lints | ||
|
||
import ( | ||
"path/filepath" | ||
"runtime" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestRunLinter(t *testing.T) { | ||
_, current, _, ok := runtime.Caller(0) | ||
require.True(t, ok) | ||
|
||
testDir := filepath.Join(filepath.Dir(current), "..", "..", "testdata", "pkg") | ||
|
||
pkg, deps, err := analyzePackage(testDir) | ||
require.NoError(t, err) | ||
require.NotNil(t, pkg) | ||
require.NotNil(t, deps) | ||
|
||
issues := runGnoPackageLinter(pkg, deps) | ||
|
||
expectedIssues := []struct { | ||
rule string | ||
message string | ||
}{ | ||
{"unused-import", "unused import: strings"}, | ||
} | ||
|
||
assert.Equal(t, len(expectedIssues), len(issues), "Number of issues doesn't match expected") | ||
|
||
for i, expected := range expectedIssues { | ||
assert.Equal(t, expected.rule, issues[i].Rule, "Rule doesn't match for issue %d", i) | ||
assert.Contains(t, issues[i].Message, expected.message, "Message doesn't match for issue %d", i) | ||
} | ||
|
||
expectedDeps := map[string]struct { | ||
isGno bool | ||
isUsed bool | ||
isIgnored bool | ||
}{ | ||
"fmt": {false, true, false}, | ||
"gno.land/p/demo/ufmt": {true, true, false}, | ||
"strings": {false, false, false}, | ||
"std": {true, true, false}, | ||
"gno.land/p/demo/diff": {true, false, true}, | ||
} | ||
|
||
for importPath, expected := range expectedDeps { | ||
dep, exists := deps[importPath] | ||
assert.True(t, exists, "Dependency %s not found", importPath) | ||
if exists { | ||
assert.Equal(t, expected.isGno, dep.IsGno, "IsGno mismatch for %s", importPath) | ||
assert.Equal(t, expected.isUsed, dep.IsUsed, "IsUsed mismatch for %s", importPath) | ||
assert.Equal(t, expected.isIgnored, dep.IsIgnored, "IsIgnored mismatch for %s", importPath) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"std" | ||
"strings" // unused import | ||
_ "gno.land/p/demo/diff" // unused import but ignored | ||
|
||
"gno.land/p/demo/ufmt" | ||
) | ||
|
||
func main() { | ||
fmt.Println("Hello, World!") | ||
ufmt.Printf("Formatted: %s\n", "test") | ||
|
||
std.Emit( | ||
"foo", | ||
"1", "2", | ||
) | ||
} |