@@ -3,6 +3,8 @@ package builders
33import (
44 "errors"
55 "fmt"
6+ "go/parser"
7+ "go/token"
68 "io/ioutil"
79 "os"
810 "os/exec"
@@ -732,7 +734,46 @@ func (builder *GoBuilder) IsModule(target string) (bool, error) {
732734 return false , errors .New ("IsModule is not implemented for GoBuilder" )
733735}
734736
735- // DiscoverModules is not implemented
737+ // DiscoverModules walks subdirectories for a Go file with `package main`.
736738func (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
738779}
0 commit comments