|
| 1 | +package configurebaseline |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "io/fs" |
| 6 | + "os" |
| 7 | + "path" |
| 8 | + "path/filepath" |
| 9 | + |
| 10 | + "github.com/github/codeql-go/extractor/util" |
| 11 | +) |
| 12 | + |
| 13 | +func fileExists(path string) bool { |
| 14 | + stat, err := os.Stat(path) |
| 15 | + return err == nil && stat.Mode().IsRegular() |
| 16 | +} |
| 17 | + |
| 18 | +// Decides if `dirPath` is a vendor directory by testing whether it is called `vendor` |
| 19 | +// and contains a `modules.txt` file. |
| 20 | +func isGolangVendorDirectory(dirPath string) bool { |
| 21 | + return filepath.Base(dirPath) == "vendor" && fileExists(filepath.Join(dirPath, "modules.txt")) |
| 22 | +} |
| 23 | + |
| 24 | +type BaselineConfig struct { |
| 25 | + PathsIgnore []string `json:"paths-ignore"` |
| 26 | +} |
| 27 | + |
| 28 | +func GetConfigBaselineAsJSON(rootDir string) ([]byte, error) { |
| 29 | + vendorDirs := make([]string, 0) |
| 30 | + |
| 31 | + if util.IsVendorDirExtractionEnabled() { |
| 32 | + // The user wants vendor directories scanned; emit an empty report. |
| 33 | + } else { |
| 34 | + filepath.WalkDir(rootDir, func(dirPath string, d fs.DirEntry, err error) error { |
| 35 | + if err != nil { |
| 36 | + // Ignore any unreadable paths -- if this script can't see it, very likely |
| 37 | + // it will not be extracted either. |
| 38 | + return nil |
| 39 | + } |
| 40 | + if isGolangVendorDirectory(dirPath) { |
| 41 | + // Note that CodeQL expects a forward-slash-separated path, even on Windows. |
| 42 | + vendorDirs = append(vendorDirs, path.Join(filepath.ToSlash(dirPath), "**")) |
| 43 | + return filepath.SkipDir |
| 44 | + } else { |
| 45 | + return nil |
| 46 | + } |
| 47 | + }) |
| 48 | + } |
| 49 | + |
| 50 | + outputStruct := BaselineConfig{PathsIgnore: vendorDirs} |
| 51 | + return json.Marshal(outputStruct) |
| 52 | +} |
0 commit comments