dont crash on 100gb files pls (#1292)

This commit is contained in:
Zachary Rice authored and GitHub committed 2023-11-17 14:56:02 -06:00
1 parent e63b657bcf
commit dab7d0292a
1 file changed
+39 -20
+39 -20
View File
@@ -37,6 +37,7 @@ const (
ProtectStagedType ProtectStagedType
gitleaksAllowSignature = "gitleaks:allow" gitleaksAllowSignature = "gitleaks:allow"
chunkSize = 10 * 1_000 // 10kb
) )
// Detector is the main detector struct // Detector is the main detector struct
@@ -502,31 +503,49 @@ func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
for pa := range paths { for pa := range paths {
p := pa p := pa
s.Go(func() error { s.Go(func() error {
b, err := os.ReadFile(p.Path) f, err := os.Open(p.Path)
if err != nil { if err != nil {
return err return err
} }
defer f.Close()
mimetype, err := filetype.Match(b) // Buffer to hold file chunks
if err != nil { buf := make([]byte, chunkSize)
return err totalLines := 0
} for {
if mimetype.MIME.Type == "application" { n, err := f.Read(buf)
return nil // skip binary files if err != nil && err != io.EOF {
} return err
}
if n == 0 {
break
}
fragment := Fragment{ // TODO: optimization could be introduced here
Raw: string(b), mimetype, err := filetype.Match(buf[:n])
FilePath: p.Path, if err != nil {
} return err
if p.Symlink != "" { }
fragment.SymlinkFile = p.Symlink if mimetype.MIME.Type == "application" {
} return nil // skip binary files
for _, finding := range d.Detect(fragment) { }
// need to add 1 since line counting starts at 1
finding.EndLine++ // Count the number of newlines in this chunk
finding.StartLine++ linesInChunk := strings.Count(string(buf[:n]), "\n")
d.addFinding(finding) totalLines += linesInChunk
fragment := Fragment{
Raw: string(buf[:n]),
FilePath: p.Path,
}
if p.Symlink != "" {
fragment.SymlinkFile = p.Symlink
}
for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1
finding.StartLine += (totalLines - linesInChunk) + 1
finding.EndLine += (totalLines - linesInChunk) + 1
d.addFinding(finding)
}
} }
return nil return nil