Skip to content

Commit 46d1dbd

Browse files
authored
feat(go): Implement Go module discovery (#97)
1 parent b476653 commit 46d1dbd

File tree

2 files changed

+47
-6
lines changed

2 files changed

+47
-6
lines changed

.fossa.yaml renamed to .fossa.yml

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
version: 1
44
cli:
55
server: https://app.fossa.io
6-
project: github.com/fossas/fossa-cli
6+
project: git@github.com:fossas/fossa-cli.git
77
fetcher: git
88
analyze:
99
modules:
10-
- name: fossa-cli
11-
path: ./cmd/fossa
12-
type: gopackage
10+
- name: fossa
11+
path: cmd/fossa
12+
type: go

builders/golang.go

+43-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package builders
33
import (
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`.
736738
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
738779
}

0 commit comments

Comments
 (0)