Files
codeql/go/extractor/configurebaseline/configurebaseline.go
Chris Smowton 21366dd502 Go / configure-baseline: account for multiple vendor directories and the CODEQL_EXTRACTOR_GO_EXTRACT_VENDOR_DIRS setting
Our existing configure-baseline scripts would give the wrong result if a `vendor` directory wasn't at the root of the repository, or if the `CODEQL_EXTRACTOR_GO_EXTRACT_VENDOR_DIRS` variable was set to `true` indicating the user wants their vendored code scanned.

Here I replace the shell scripts that implemented the very simplest behaviour with a small Go program.
2024-08-20 15:56:22 +01:00

49 lines
1.2 KiB
Go

package configurebaseline
import (
"encoding/json"
"io/fs"
"os"
"path"
"path/filepath"
)
func fileExists(path string) bool {
stat, err := os.Stat(path)
return err == nil && stat.Mode().IsRegular()
}
func isGolangVendorDirectory(dirPath string) bool {
// Call a directory a Golang vendor directory if it contains a modules.txt file.
return path.Base(dirPath) == "vendor" && fileExists(path.Join(dirPath, "modules.txt"))
}
type PathsIgnoreStruct struct {
PathsIgnore []string `json:"paths-ignore"`
}
func GetConfigBaselineAsJSON(rootDir string) ([]byte, error) {
vendorDirs := make([]string, 0)
// If CODEQL_EXTRACTOR_GO_EXTRACT_VENDOR_DIRS is "true":
if os.Getenv("CODEQL_EXTRACTOR_GO_EXTRACT_VENDOR_DIRS") == "true" {
// The user wants vendor directories scanned; emit an empty report.
} else {
filepath.WalkDir(rootDir, func(dirPath string, d fs.DirEntry, err error) error {
if err != nil {
// Mask any unreadable paths.
return nil
}
if isGolangVendorDirectory(dirPath) {
vendorDirs = append(vendorDirs, path.Join(dirPath, "**"))
return filepath.SkipDir
} else {
return nil
}
})
}
outputStruct := PathsIgnoreStruct{PathsIgnore: vendorDirs}
return json.Marshal(outputStruct)
}