@@ -4,6 +4,8 @@ package main
44
55import (
66 "bytes"
7+ "go/parser"
8+ "go/token"
79 "io/ioutil"
810 "log"
911 "os"
@@ -157,35 +159,16 @@ func findPackagesInSourceCode(root string) map[string]bool {
157159
158160 // Only process Go files
159161 if ! info .IsDir () && strings .HasSuffix (path , ".go" ) {
160- content , err := os .ReadFile (path )
162+ fset := token .NewFileSet ()
163+ file , err := parser .ParseFile (fset , path , nil , parser .ImportsOnly )
161164 if err != nil {
162165 return err
163166 }
164167
165- // Simple parsing to find import statements
166- // This is a basic implementation - a more robust solution would use go/parser
167- lines := strings .Split (string (content ), "\n " )
168- inImport := false
169- for _ , line := range lines {
170- line = strings .TrimSpace (line )
171-
172- if strings .HasPrefix (line , "import (" ) {
173- inImport = true
174- continue
175- }
176-
177- if inImport && strings .HasPrefix (line , ")" ) {
178- inImport = false
179- continue
180- }
181-
182- if strings .HasPrefix (line , "import " ) || inImport {
183- // Extract package path from import line
184- pkgPath := extractPackagePath (line )
185- if pkgPath != "" {
186- packages [pkgPath ] = true
187- }
188- }
168+ // Extract import paths from the AST
169+ for _ , imp := range file .Imports {
170+ pkgPath := strings .Trim (imp .Path .Value , "\" " )
171+ packages [pkgPath ] = true
189172 }
190173 }
191174 return nil
@@ -198,36 +181,6 @@ func findPackagesInSourceCode(root string) map[string]bool {
198181 return packages
199182}
200183
201- // extractPackagePath parses an import line to extract the package path
202- func extractPackagePath (line string ) string {
203- line = strings .TrimSpace (line )
204-
205- // Skip if not an import line
206- if ! (strings .HasPrefix (line , "import " ) || strings .Contains (line , "\" " ) || strings .Contains (line , "`" )) {
207- return ""
208- }
209-
210- // Handle quoted imports
211- if strings .Contains (line , "\" " ) {
212- start := strings .Index (line , "\" " )
213- end := strings .LastIndex (line , "\" " )
214- if start >= 0 && end > start {
215- return line [start + 1 : end ]
216- }
217- }
218-
219- // Handle backtick imports
220- if strings .Contains (line , "`" ) {
221- start := strings .Index (line , "`" )
222- end := strings .LastIndex (line , "`" )
223- if start >= 0 && end > start {
224- return line [start + 1 : end ]
225- }
226- }
227-
228- return ""
229- }
230-
231184// findSubmodulesForModule returns the submodules of a given module that are actually used in the source code
232185func findSubmodulesForModule (modulePath string , usedPackages map [string ]bool ) []string {
233186 var submodules []string
0 commit comments