git.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package detect
  2. import (
  3. "github.com/gitleaks/go-gitdiff/gitdiff"
  4. "github.com/zricethezav/gitleaks/v8/logging"
  5. "github.com/zricethezav/gitleaks/v8/report"
  6. "github.com/zricethezav/gitleaks/v8/sources"
  7. )
  8. func (d *Detector) DetectGit(gitCmd *sources.GitCmd) ([]report.Finding, error) {
  9. defer gitCmd.Wait()
  10. diffFilesCh := gitCmd.DiffFilesCh()
  11. errCh := gitCmd.ErrCh()
  12. // loop to range over both DiffFiles (stdout) and ErrCh (stderr)
  13. for diffFilesCh != nil || errCh != nil {
  14. select {
  15. case gitdiffFile, open := <-diffFilesCh:
  16. if !open {
  17. diffFilesCh = nil
  18. break
  19. }
  20. // skip binary files
  21. if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
  22. continue
  23. }
  24. // Check if commit is allowed
  25. commitSHA := ""
  26. if gitdiffFile.PatchHeader != nil {
  27. commitSHA = gitdiffFile.PatchHeader.SHA
  28. if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
  29. continue
  30. }
  31. }
  32. d.addCommit(commitSHA)
  33. d.Sema.Go(func() error {
  34. for _, textFragment := range gitdiffFile.TextFragments {
  35. if textFragment == nil {
  36. return nil
  37. }
  38. fragment := Fragment{
  39. Raw: textFragment.Raw(gitdiff.OpAdd),
  40. CommitSHA: commitSHA,
  41. FilePath: gitdiffFile.NewName,
  42. }
  43. for _, finding := range d.Detect(fragment) {
  44. d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
  45. }
  46. }
  47. return nil
  48. })
  49. case err, open := <-errCh:
  50. if !open {
  51. errCh = nil
  52. break
  53. }
  54. return d.findings, err
  55. }
  56. }
  57. if err := d.Sema.Wait(); err != nil {
  58. return d.findings, err
  59. }
  60. logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
  61. logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
  62. return d.findings, nil
  63. }