Skip to content

Commit

Permalink
Fix error closing files from Filesystem (#18)
Browse files Browse the repository at this point in the history
* Add Filesystem test

* Don't assign nil *os.File to closeBoth.c
  • Loading branch information
WillAbides authored Feb 17, 2025
1 parent 60ed3dc commit 335037c
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
5 changes: 4 additions & 1 deletion fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,10 @@ func (f ArchiveFS) Open(name string) (fs.File, error) {
return err
}

fsFile = closeBoth{File: innerFile, c: archiveFile}
fsFile = innerFile
if archiveFile != nil {
fsFile = closeBoth{File: innerFile, c: archiveFile}
}

if decompressor != nil {
fsFile = closeBoth{fsFile, decompressor}
Expand Down
68 changes: 68 additions & 0 deletions fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package archives

import (
"bytes"
"context"
_ "embed"
"fmt"
"io"
Expand Down Expand Up @@ -292,3 +293,70 @@ func TestArchiveFS_ReadDir(t *testing.T) {
})
}
}

func TestFileSystem(t *testing.T) {
ctx := context.Background()
filename := "testdata/test.zip"

checkFS := func(t *testing.T, fsys fs.FS) {
license, err := fsys.Open("LICENSE")
if err != nil {
t.Fatal(err)
}
b, err := io.ReadAll(license)
if err != nil {
t.Fatal(err)
}
if len(b) == 0 {
t.Fatal("empty file")
}
err = license.Close()
if err != nil {
t.Fatal(err)
}
}

t.Run("filename", func(t *testing.T) {
fsys, err := FileSystem(ctx, filename, nil)
if err != nil {
t.Fatal(err)
}
checkFS(t, fsys)
})

t.Run("stream", func(t *testing.T) {
f, err := os.Open(filename)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
err = f.Close()
if err != nil {
t.Error(err)
}
})
fsys, err := FileSystem(ctx, "", f)
if err != nil {
t.Fatal(err)
}
checkFS(t, fsys)
})

t.Run("filename and stream", func(t *testing.T) {
f, err := os.Open(filename)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
err = f.Close()
if err != nil {
t.Error(err)
}
})
fsys, err := FileSystem(ctx, "test.zip", f)
if err != nil {
t.Fatal(err)
}
checkFS(t, fsys)
})
}

0 comments on commit 335037c

Please sign in to comment.