files.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package detect
  2. import (
  3. "context"
  4. "os"
  5. "path/filepath"
  6. "sync"
  7. "golang.org/x/sync/errgroup"
  8. "github.com/zricethezav/gitleaks/v8/config"
  9. "github.com/zricethezav/gitleaks/v8/report"
  10. )
  11. // FromFiles opens the directory or file specified in source and checks each file against the rules
  12. // from the configuration. If any secrets are found, they are added to the list of findings.
  13. func FromFiles(source string, cfg config.Config, outputOptions Options) ([]report.Finding, error) {
  14. var (
  15. findings []report.Finding
  16. mu sync.Mutex
  17. )
  18. concurrentGoroutines := make(chan struct{}, MAXGOROUTINES)
  19. g, _ := errgroup.WithContext(context.Background())
  20. paths := make(chan string)
  21. g.Go(func() error {
  22. defer close(paths)
  23. return filepath.Walk(source,
  24. func(path string, fInfo os.FileInfo, err error) error {
  25. if err != nil {
  26. return err
  27. }
  28. if fInfo.Name() == ".git" {
  29. return filepath.SkipDir
  30. }
  31. if fInfo.Mode().IsRegular() {
  32. paths <- path
  33. }
  34. return nil
  35. })
  36. })
  37. for pa := range paths {
  38. p := pa
  39. concurrentGoroutines <- struct{}{}
  40. g.Go(func() error {
  41. defer func() {
  42. <-concurrentGoroutines
  43. }()
  44. b, err := os.ReadFile(p)
  45. if err != nil {
  46. return err
  47. }
  48. fis := DetectFindings(cfg, b, p, "")
  49. for _, fi := range fis {
  50. // need to add 1 since line counting starts at 1
  51. fi.StartLine++
  52. fi.EndLine++
  53. if outputOptions.Redact {
  54. fi.Redact()
  55. }
  56. if outputOptions.Verbose {
  57. printFinding(fi)
  58. }
  59. mu.Lock()
  60. findings = append(findings, fi)
  61. mu.Unlock()
  62. }
  63. return nil
  64. })
  65. }
  66. if err := g.Wait(); err != nil {
  67. return findings, err
  68. }
  69. return findings, nil
  70. }