Skip to content

Commit

Permalink
Refactor cacheFolder to use filepath.WalkDir
Browse files Browse the repository at this point in the history
  • Loading branch information
zer0tonin committed Nov 13, 2023
1 parent 866940f commit 86e2ee9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
34 changes: 18 additions & 16 deletions backend/browser/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package browser
import (
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"sync"

"github.com/rjeczalik/notify"
Expand Down Expand Up @@ -37,24 +37,26 @@ func ResetCache() {
// recursively initalizes the cache
// we do not use filepath.Walk to avoid a mess with relative / absolute paths
func cacheFolder(cache map[string]fs.FileInfo, path string) {
dirEntries, err := os.ReadDir(getAbsolutePath(path))
rootPath := getAbsolutePath(path)
err := filepath.WalkDir(
rootPath,
func(path string, dirEntry fs.DirEntry, err error) error {
relativePath := strings.TrimPrefix(path, rootPath)
if relativePath == "" {
return nil
}
fileInfo, err := dirEntry.Info()
if err != nil {
return err
}

cache[relativePath] = fileInfo
return nil
},
)
if err != nil {
log.Panicf("Error while refreshing cache: %s", err.Error())
}

for _, dirEntry := range dirEntries {
relativePath := filepath.Clean(path + dirEntry.Name())
fileInfo, err := dirEntry.Info()
if err != nil {
log.Panicf("Error while refreshing cache: %s", err.Error())
}

cache[relativePath] = fileInfo

if dirEntry.IsDir() {
cacheFolder(cache, relativePath+"/")
}
}
}

// refreshes the cache on data dir changes
Expand Down
1 change: 1 addition & 0 deletions backend/browser/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func StreamFile(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"err": "Failed to stat file",
})
return
}

if dir {
Expand Down

0 comments on commit 86e2ee9

Please sign in to comment.