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
+24 -5
+24 -5
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,12 +503,26 @@ 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
buf := make([]byte, chunkSize)
totalLines := 0
for {
n, err := f.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n == 0 {
break
}
// TODO: optimization could be introduced here
mimetype, err := filetype.Match(buf[:n])
if err != nil { if err != nil {
return err return err
} }
@@ -515,8 +530,11 @@ func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
return nil // skip binary files return nil // skip binary files
} }
// Count the number of newlines in this chunk
linesInChunk := strings.Count(string(buf[:n]), "\n")
totalLines += linesInChunk
fragment := Fragment{ fragment := Fragment{
Raw: string(b), Raw: string(buf[:n]),
FilePath: p.Path, FilePath: p.Path,
} }
if p.Symlink != "" { if p.Symlink != "" {
@@ -524,10 +542,11 @@ func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
} }
for _, finding := range d.Detect(fragment) { for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1 // need to add 1 since line counting starts at 1
finding.EndLine++ finding.StartLine += (totalLines - linesInChunk) + 1
finding.StartLine++ finding.EndLine += (totalLines - linesInChunk) + 1
d.addFinding(finding) d.addFinding(finding)
} }
}
return nil return nil
}) })