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

Commit

Permalink
Return underlying Seeker from Identify if possible (#327)
Browse files Browse the repository at this point in the history
* [feat] don't require io.Seeker for identify

* tidy up

* Refactor and simplify with some bug fixes

* Clarify returned Reader in godoc comment

* if underlying reader supports seek use that

* update comment

* Update formats.go

Co-authored-by: Matt Holt <mholt@users.noreply.github.com>

Co-authored-by: Matthew Holt <mholt@users.noreply.github.com>
  • Loading branch information
jhwz and mholt authored Mar 21, 2022
1 parent dda6eaa commit d3e979a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
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(0, io.SeekStart); err == nil {
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")
}

0 comments on commit d3e979a

Please sign in to comment.