Skip to content

Commit

Permalink
empty files should have not mimetype
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Goodman <[email protected]>
  • Loading branch information
wagoodman committed Feb 16, 2022
1 parent 25ebd49 commit e985f72
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 16 deletions.
22 changes: 21 additions & 1 deletion pkg/file/mime_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,31 @@ func MIMEType(reader io.Reader) string {
if reader == nil {
return ""
}

s := sizer{reader: reader}

var mTypeStr string
mType, err := mimetype.DetectReader(reader)
mType, err := mimetype.DetectReader(&s)
if err == nil {
// extract the string mimetype and ignore aux information (e.g. 'text/plain; charset=utf-8' -> 'text/plain')
mTypeStr = strings.Split(mType.String(), ";")[0]
}

// we may have a reader that is not nil but the observed contents was empty
if s.size == 0 {
return ""
}

return mTypeStr
}

type sizer struct {
reader io.Reader
size int64
}

func (s *sizer) Read(p []byte) (int, error) {
n, err := s.reader.Read(p)
s.size += int64(n)
return n, err
}
39 changes: 24 additions & 15 deletions pkg/file/mime_type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,50 @@ package file

import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io"
"os"
"strings"
"testing"
)

func Test_MIMEType(t *testing.T) {

fileReader := func(path string) io.Reader {
f, err := os.Open(path)
require.NoError(t, err)
return f
}

tests := []struct {
fixture string
name string
fixture io.Reader
expected string
}{
{
// darwin binary
fixture: "test-fixtures/mime/mach-binary",
name: "binary",
fixture: fileReader("test-fixtures/mime/mach-binary"),
expected: "application/x-mach-binary",
},
{
// script
fixture: "test-fixtures/mime/capture.sh",
name: "script",
fixture: fileReader("test-fixtures/mime/capture.sh"),
expected: "text/plain",
},
{
// no contents
fixture: "",
name: "no contents",
fixture: strings.NewReader(""),
expected: "",
},
{
name: "no reader",
fixture: nil,
expected: "",
},
}
for _, test := range tests {
t.Run(test.fixture, func(t *testing.T) {
var f *os.File
var err error
if test.fixture != "" {
f, err = os.Open(test.fixture)
assert.NoError(t, err)
}
assert.Equal(t, test.expected, MIMEType(f))
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.expected, MIMEType(test.fixture))
})
}
}

0 comments on commit e985f72

Please sign in to comment.