Skip to content

Commit

Permalink
feat: customizable directory refresher (#45)
Browse files Browse the repository at this point in the history
This PR is intended to allow users to define the filesystem operations they want to be notified about (for example deletion).
  • Loading branch information
m-rcl authored Sep 8, 2022
1 parent cdf80a1 commit 6f48be8
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 5 deletions.
24 changes: 19 additions & 5 deletions loader/directory_refresher.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,32 @@ package loader
import "path/filepath"

type DirectoryRefresher struct {
currDir string
currDir string
watchOps map[FileSystemOp]bool
}

var defaultFileSystemOps = map[FileSystemOp]bool{
Write: true,
Create: true,
Chmod: true,
}

func (d *DirectoryRefresher) WatchDirectory(runtimePath string, appDirPath string) string {
d.currDir = filepath.Join(runtimePath, appDirPath)
return d.currDir
}

func (d *DirectoryRefresher) WatchFileSystemOps(fsops ...FileSystemOp) {
d.watchOps = map[FileSystemOp]bool{}
for _, op := range fsops {
d.watchOps[op] = true
}
}

func (d *DirectoryRefresher) ShouldRefresh(path string, op FileSystemOp) bool {
if filepath.Dir(path) == d.currDir &&
(op == Write || op == Create || op == Chmod) {
return true
watchOps := d.watchOps
if watchOps == nil {
watchOps = defaultFileSystemOps
}
return false
return filepath.Dir(path) == d.currDir && watchOps[op]
}
41 changes: 41 additions & 0 deletions loader/loader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,47 @@ func TestOnRuntimeChanged(t *testing.T) {
})
}

func TestShouldRefreshDefault(t *testing.T) {
assert := require.New(t)

refresher := DirectoryRefresher{currDir: "/tmp"}

assert.True(refresher.ShouldRefresh("/tmp/foo", Write))

assert.False(refresher.ShouldRefresh("/tmp/foo", Remove))
assert.False(refresher.ShouldRefresh("/bar/foo", Write))
assert.False(refresher.ShouldRefresh("/bar/foo", Remove))
}

func TestShouldRefreshRemove(t *testing.T) {
assert := require.New(t)

refresher := DirectoryRefresher{currDir: "/tmp", watchOps: map[FileSystemOp]bool{
Remove: true,
Chmod: true,
}}

assert.True(refresher.ShouldRefresh("/tmp/foo", Remove))
assert.True(refresher.ShouldRefresh("/tmp/foo", Chmod))

assert.False(refresher.ShouldRefresh("/bar/foo", Write))
}

func TestWatchFileSystemOps(t *testing.T) {
assert := require.New(t)

refresher := DirectoryRefresher{currDir: "/tmp"}

refresher.WatchFileSystemOps()
assert.False(refresher.ShouldRefresh("/tmp/foo", Write))

refresher.WatchFileSystemOps(Remove)
assert.True(refresher.ShouldRefresh("/tmp/foo", Remove))

refresher.WatchFileSystemOps(Chmod, Write)
assert.True(refresher.ShouldRefresh("/tmp/foo", Write))
}

func BenchmarkSnapshot(b *testing.B) {
var ll Loader
for i := 0; i < b.N; i++ {
Expand Down

0 comments on commit 6f48be8

Please sign in to comment.