reader.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package detect
  2. import (
  3. "bufio"
  4. "bytes"
  5. "io"
  6. "github.com/zricethezav/gitleaks/v8/report"
  7. )
  8. // DetectReader accepts an io.Reader and a buffer size for the reader in KB
  9. func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, error) {
  10. reader := bufio.NewReader(r)
  11. buf := make([]byte, 1000*bufSize)
  12. findings := []report.Finding{}
  13. for {
  14. n, err := reader.Read(buf)
  15. // "Callers should always process the n > 0 bytes returned before considering the error err."
  16. // https://pkg.go.dev/io#Reader
  17. if n > 0 {
  18. // Try to split chunks across large areas of whitespace, if possible.
  19. peekBuf := bytes.NewBuffer(buf[:n])
  20. if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
  21. return findings, readErr
  22. }
  23. fragment := Fragment{
  24. Raw: peekBuf.String(),
  25. }
  26. for _, finding := range d.Detect(fragment) {
  27. findings = append(findings, finding)
  28. if d.Verbose {
  29. printFinding(finding, d.NoColor)
  30. }
  31. }
  32. }
  33. if err != nil {
  34. if err == io.EOF {
  35. break
  36. }
  37. return findings, err
  38. }
  39. }
  40. return findings, nil
  41. }