Skip to content
This repository has been archived by the owner on Nov 19, 2024. It is now read-only.

Retain underlying reader if it's an io.Seeker #327

Merged
merged 9 commits into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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
7 changes: 7 additions & 0 deletions formats.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,14 @@ func (rr *rewindReader) rewind() {
// bytes, then from the underlying stream. After calling this,
// no more rewinding is allowed since reads from the stream are
// not recorded, so rewinding properly is impossible.
// If the underlying reader implements io.Seeker, then the
// underlying reader will be used directly.
func (rr *rewindReader) reader() io.Reader {
if ras, ok := rr.Reader.(io.Seeker); ok {
if _, err := ras.Seek(-int64(rr.buf.Len()), io.SeekCurrent); err == nil {
jhwz marked this conversation as resolved.
Show resolved Hide resolved
return rr.Reader
}
}
return io.MultiReader(bytes.NewReader(rr.buf.Bytes()), rr.Reader)
}

Expand Down
23 changes: 23 additions & 0 deletions formats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,3 +387,26 @@ func TestIdentifyFindFormatByStreamContent(t *testing.T) {
})
}
}

func TestIdentifyAndOpenZip(t *testing.T) {
f, err := os.Open("testdata/test.zip")
checkErr(t, err, "opening zip")
defer f.Close()

format, reader, err := Identify("test.zip", f)
checkErr(t, err, "identifying zip")
if format.Name() != ".zip" {
t.Fatalf("unexpected format found: expected=.zip actual:%s", format.Name())
}

err = format.(Extractor).Extract(context.Background(), reader, nil, func(ctx context.Context, f File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
_, err = io.ReadAll(rc)
return err
})
checkErr(t, err, "extracting zip")
}