@@ -333,12 +333,25 @@ func (gosec *Analyzer) load(pkgPath string, conf *packages.Config) ([]*packages.
333
333
return []* packages.Package {}, fmt .Errorf ("importing dir %q: %w" , pkgPath , err )
334
334
}
335
335
336
- var packageFiles []string
337
- for _ , filename := range basePackage .GoFiles {
338
- packageFiles = append (packageFiles , path .Join (pkgPath , filename ))
336
+ var goModFile string
337
+ goModDir := abspath [0 : len (abspath )- len (pkgPath )] // get root dir
338
+ if modPkgs , err := packages .Load (& packages.Config {Mode : packages .NeedModule , Dir : abspath }, abspath ); err == nil && len (modPkgs ) == 1 {
339
+ goModFile = modPkgs [0 ].Module .GoMod
340
+ goModDir = path .Dir (goModFile )
339
341
}
340
- for _ , filename := range basePackage .CgoFiles {
341
- packageFiles = append (packageFiles , path .Join (pkgPath , filename ))
342
+
343
+ var packageFiles []string
344
+ for _ , filename := range append (basePackage .GoFiles , basePackage .CgoFiles ... ) {
345
+ if goModDir == "" {
346
+ packageFiles = append (packageFiles , path .Join (pkgPath , filename ))
347
+ } else {
348
+ filePath := path .Join (abspath , filename )
349
+ relPath , err := filepath .Rel (goModDir , filePath )
350
+ if err != nil {
351
+ return []* packages.Package {}, fmt .Errorf ("get relative path between %q and %q: %w" , goModDir , filePath , err )
352
+ }
353
+ packageFiles = append (packageFiles , relPath )
354
+ }
342
355
}
343
356
344
357
if gosec .tests {
@@ -354,6 +367,7 @@ func (gosec *Analyzer) load(pkgPath string, conf *packages.Config) ([]*packages.
354
367
gosec .mu .Lock ()
355
368
conf .BuildFlags = nil
356
369
defer gosec .mu .Unlock ()
370
+ conf .Dir = goModDir
357
371
pkgs , err := packages .Load (conf , packageFiles ... )
358
372
if err != nil {
359
373
return []* packages.Package {}, fmt .Errorf ("loading files from package %q: %w" , pkgPath , err )
0 commit comments