Skip to content
Merged
Show file tree
Hide file tree
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
19 changes: 17 additions & 2 deletions internal/panels/preview/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package preview
import (
"bytes"
"context"
"crypto/sha256"
"fmt"
"os"
"path/filepath"
Expand Down Expand Up @@ -770,7 +771,7 @@ func (p *Preview) loadFileCmd(path string) tea.Cmd {
mime := mimetype.Detect(header)
if !isTextMIME(mime.String()) {
result.isBinary = true
result.lines = append(buildMetadataLines(path, info), "", "Type: "+mime.String())
result.lines = buildBinaryMetadataLines(path, info, mime.String(), nil)
return result
}
// Read file content
Expand All @@ -783,7 +784,7 @@ func (p *Preview) loadFileCmd(path string) tea.Cmd {
// check but contain null bytes (polyglot / binary-after-header).
if bytes.ContainsRune(data, 0) {
result.isBinary = true
result.lines = append(buildMetadataLines(path, info), "", "Type: binary (null bytes detected)")
result.lines = buildBinaryMetadataLines(path, info, "binary (null bytes detected)", data)
return result
}
// Normalize line endings so \r doesn't corrupt rendering
Expand Down Expand Up @@ -1098,6 +1099,20 @@ func buildMetadataLines(path string, info os.FileInfo) []string {
}
}

func buildBinaryMetadataLines(path string, info os.FileInfo, mimeType string, data []byte) []string {
lines := buildMetadataLines(path, info)
if len(data) == 0 {
var err error
data, err = os.ReadFile(path)
if err != nil {
return append(lines, "", "Type: "+mimeType)
}
}
sum := sha256.Sum256(data)
lines = append(lines, "SHA-256: "+fmt.Sprintf("%x", sum))
return append(lines, "", "Type: "+mimeType)
}

// --- Scrolling ---
func (p *Preview) scrollDown(n int) {
p.scrollY += n
Expand Down
7 changes: 7 additions & 0 deletions internal/panels/preview/preview_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package preview

import (
"context"
"crypto/sha256"
"fmt"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -324,6 +326,10 @@ func TestBinaryFileDetection(t *testing.T) {
view := p.View(60, 20)
assert.Contains(t, view, "Binary file")
assert.Contains(t, view, "image.png")
assert.Contains(t, view, "Type: image/png")
data, err := os.ReadFile(path)
require.NoError(t, err)
assert.Contains(t, strings.Join(p.lines, "\n"), "SHA-256: "+fmt.Sprintf("%x", sha256.Sum256(data)))
}

func TestLargeFileRejection(t *testing.T) {
Expand Down Expand Up @@ -362,6 +368,7 @@ func TestLargeFileShowsMetadata(t *testing.T) {
assert.Contains(t, view, "200 B")
assert.Contains(t, view, "Mode:")
assert.Contains(t, view, "Modified:")
assert.NotContains(t, view, "SHA-256:")
}

func TestMaxFileSizeZeroDisablesCheck(t *testing.T) {
Expand Down
Loading