@@ -3,6 +3,8 @@ package builders
3
3
import (
4
4
"errors"
5
5
"fmt"
6
+ "go/parser"
7
+ "go/token"
6
8
"io/ioutil"
7
9
"os"
8
10
"os/exec"
@@ -732,7 +734,46 @@ func (builder *GoBuilder) IsModule(target string) (bool, error) {
732
734
return false , errors .New ("IsModule is not implemented for GoBuilder" )
733
735
}
734
736
735
- // DiscoverModules is not implemented
737
+ // DiscoverModules walks subdirectories for a Go file with `package main`.
736
738
func (builder * GoBuilder ) DiscoverModules (dir string ) ([]config.ModuleConfig , error ) {
737
- return nil , errors .New ("DiscoverModules is not implemented for GoBuilder" )
739
+ var modules []config.ModuleConfig
740
+ err := filepath .Walk (dir , func (path string , info os.FileInfo , err error ) error {
741
+ if err != nil {
742
+ goLogger .Debugf ("Failed to access path %s: %s" , path , err .Error ())
743
+ return fmt .Errorf ("could not read path %s during go module discovery: %s" , path , err .Error ())
744
+ }
745
+ // Skip files (we parse a directory at a time)
746
+ if ! info .IsDir () {
747
+ return nil
748
+ }
749
+ // Skip vendor directories
750
+ if info .Name () == "vendor" {
751
+ goLogger .Debugf ("Skipping directory: %s" , info .Name ())
752
+ return filepath .SkipDir
753
+ }
754
+ // Parse directory, check for `main` package declaration.
755
+ files := token .NewFileSet ()
756
+ pkgs , err := parser .ParseDir (files , path , nil , parser .PackageClauseOnly )
757
+ if err != nil {
758
+ return fmt .Errorf ("could not parse directory %s during go module discovery: %s" , path , err .Error ())
759
+ }
760
+ for pkg := range pkgs {
761
+ if pkg == "main" {
762
+ modulePath , err := filepath .Rel (dir , path )
763
+ if err != nil {
764
+ return fmt .Errorf ("could not compute module path: %s" , err .Error ())
765
+ }
766
+ modules = append (modules , config.ModuleConfig {
767
+ Name : info .Name (),
768
+ Path : modulePath ,
769
+ Type : "go" ,
770
+ })
771
+ }
772
+ }
773
+ return nil
774
+ })
775
+ if err != nil {
776
+ return nil , fmt .Errorf ("could not discover go modules: %s" , err .Error ())
777
+ }
778
+ return modules , nil
738
779
}
0 commit comments