Skip to content

Commit 10f9edc

Browse files
authored
Merge pull request #108 from vlalanne/imports
fix: missing imports if not present in first package file
2 parents 2d00f2b + 22fe878 commit 10f9edc

File tree

2 files changed

+27
-18
lines changed

2 files changed

+27
-18
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package test

internal/accessor/parser.go

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"go/types"
66
"path/filepath"
77
"reflect"
8+
"slices"
89
"strings"
910

1011
"golang.org/x/tools/go/packages"
@@ -53,24 +54,31 @@ func Parse(dir string) (*ParsedSource, error) {
5354
}
5455

5556
func parseImports(pkg *packages.Package) []*Import {
56-
imports := make([]*Import, len(pkg.Syntax[0].Imports))
57-
58-
for i, imp := range pkg.Syntax[0].Imports {
59-
// Extract the path from the import. Remove the leading and trailing quotes.
60-
path := strings.Trim(imp.Path.Value, "\"")
61-
62-
// Extract the name from the import. If the import is not named, use the base name of the path.
63-
name := filepath.Base(path)
64-
isNamed := false
65-
if imp.Name != nil {
66-
name = imp.Name.Name
67-
isNamed = true
68-
}
69-
70-
imports[i] = &Import{
71-
Name: name,
72-
Path: path,
73-
IsNamed: isNamed,
57+
var imports []*Import
58+
59+
for _, syntax := range pkg.Syntax {
60+
for _, imp := range syntax.Imports {
61+
// Extract the path from the import. Remove the leading and trailing quotes.
62+
path := strings.Trim(imp.Path.Value, "\"")
63+
64+
// Extract the name from the import. If the import is not named, use the base name of the path.
65+
name := filepath.Base(path)
66+
isNamed := false
67+
if imp.Name != nil {
68+
name = imp.Name.Name
69+
isNamed = true
70+
}
71+
if !slices.ContainsFunc(imports, func(imp *Import) bool {
72+
return imp.Name == name &&
73+
imp.Path == path &&
74+
imp.IsNamed == isNamed
75+
}) {
76+
imports = append(imports, &Import{
77+
Name: name,
78+
Path: path,
79+
IsNamed: isNamed,
80+
})
81+
}
7482
}
7583
}
7684

0 commit comments

Comments
 (0)