mirror of
https://github.com/krau/SaveAny-Bot.git
synced 2026-09-05 23:56:50 +08:00
fix: remove cache files after reader closes (#231)
This commit is contained in:
@@ -0,0 +1,42 @@
|
|||||||
|
package fsutil_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/krau/SaveAny-Bot/common/utils/fsutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCloseAndRemove(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
preClose bool
|
||||||
|
}{
|
||||||
|
{name: "open file"},
|
||||||
|
{name: "already closed file", preClose: true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
filePath := filepath.Join(t.TempDir(), "cache-file")
|
||||||
|
file, err := fsutil.CreateFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateFile() failed: %v", err)
|
||||||
|
}
|
||||||
|
if tt.preClose {
|
||||||
|
if err := file.Close(); err != nil {
|
||||||
|
t.Fatalf("Close() failed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := file.CloseAndRemove(); err != nil {
|
||||||
|
t.Fatalf("CloseAndRemove() failed: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filePath); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("cache file still exists after CloseAndRemove(): %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package fsutil
|
package fsutil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -41,10 +42,11 @@ func (f *File) Remove() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *File) CloseAndRemove() error {
|
func (f *File) CloseAndRemove() error {
|
||||||
if err := f.Close(); err != nil {
|
closeErr := f.Close()
|
||||||
return err
|
if errors.Is(closeErr, os.ErrClosed) {
|
||||||
|
closeErr = nil
|
||||||
}
|
}
|
||||||
return f.Remove()
|
return errors.Join(closeErr, f.Remove())
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateFile(fp string) (*File, error) {
|
func CreateFile(fp string) (*File, error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user