Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: change text detect to check first and last 512 bytes #2310

Merged
merged 5 commits into from
Feb 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 30 additions & 11 deletions src/pkg/utils/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -475,22 +475,41 @@ func IsTextFile(path string) (bool, error) {
}
defer f.Close() // Make sure to close the file when we're done

// Read the first 512 bytes of the file
data := make([]byte, 512)
n, err := f.Read(data)
WeaponX314 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil && err != io.EOF {
// Get file stat
stat, err := f.Stat()
if err != nil {
return false, err
}

// Use http.DetectContentType to determine the MIME type of the file
mimeType := http.DetectContentType(data[:n])
// Clip offset to minimum of 0
lastOffset := max(0, stat.Size()-512)

// Take two passes checking front and back of the file
offsetPasses := []int64{0, lastOffset}
isTextCheck := []bool{false, false}
for idx, offset := range offsetPasses {
// Create 512 byte buffer
data := make([]byte, 512)

n, err := f.ReadAt(data, offset)
if err != nil && err != io.EOF {
return false, err
}

// Check if the MIME type indicates that the file is text
hasText := strings.HasPrefix(mimeType, "text/")
hasJSON := strings.Contains(mimeType, "json")
hasXML := strings.Contains(mimeType, "xml")
// Use http.DetectContentType to determine the MIME type of the file
mimeType := http.DetectContentType(data[:n])

// Check if the MIME type indicates that the file is text
hasText := strings.HasPrefix(mimeType, "text/")
hasJSON := strings.Contains(mimeType, "json")
hasXML := strings.Contains(mimeType, "xml")

// Save result
isTextCheck[idx] = hasText || hasJSON || hasXML
}

return hasText || hasJSON || hasXML, nil
// Returns true if both front and back show they are text
return isTextCheck[0] && isTextCheck[1], nil
}

// IsTrashBin checks if the given directory path corresponds to an operating system's trash bin.
Expand Down
Loading