github.com/joey-fossa/fossa-cli@v0.7.34-0.20190708193710-569f1e8679f0/analyzers/golang/discover.go (about)

     1  package golang
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  
     7  	"github.com/apex/log"
     8  	"github.com/mitchellh/mapstructure"
     9  	"github.com/pkg/errors"
    10  
    11  	"github.com/fossas/fossa-cli/buildtools/gocmd"
    12  	"github.com/fossas/fossa-cli/exec"
    13  	"github.com/fossas/fossa-cli/module"
    14  	"github.com/fossas/fossa-cli/pkg"
    15  )
    16  
    17  type DiscoverOptions struct {
    18  	Strategy string
    19  
    20  	Cmd       string
    21  	BuildOS   string
    22  	BuildArch string
    23  }
    24  
    25  // Discover runs `go list ./...`.
    26  func Discover(dir string, opts map[string]interface{}) ([]module.Module, error) {
    27  	log.Debugf("%#v", opts)
    28  
    29  	// Parse and validate options.
    30  	var options DiscoverOptions
    31  	err := mapstructure.Decode(opts, &options)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	log.WithField("options", options).Debug("parsed analyzer options")
    36  
    37  	cmd, _, err := exec.Which("version", options.Cmd, "go")
    38  	if err != nil {
    39  		return nil, errors.New("`go` not found, skipping searching for Go projects")
    40  	}
    41  
    42  	g := gocmd.Go{
    43  		Cmd: cmd,
    44  		Dir: dir,
    45  	}
    46  	found, err := g.List([]string{"./..."}, nil)
    47  	if err != nil {
    48  		return nil, errors.Wrap(err, "could not find Go projects")
    49  	}
    50  
    51  	cwd, err := os.Getwd()
    52  	if err != nil {
    53  		return nil, errors.Wrap(err, "could not find Go projects")
    54  	}
    55  	var projects []module.Module
    56  	for _, f := range found {
    57  		log.Debugf("Found Go module: %#v", f)
    58  		path, err := filepath.Rel(cwd, f.Dir)
    59  		if err != nil {
    60  			return nil, errors.Wrap(err, "could not find Go projects")
    61  		}
    62  		projects = append(projects, module.Module{
    63  			Name:         Unvendor(f.ImportPath),
    64  			Type:         pkg.Go,
    65  			IsExecutable: f.Name == "main",
    66  			BuildTarget:  f.ImportPath,
    67  			Dir:          path,
    68  		})
    69  	}
    70  	return projects, nil
    71  }