Skip to content

Commit

Permalink
Support cancellation in DirWalk
Browse files Browse the repository at this point in the history
  • Loading branch information
empijei committed Dec 23, 2024
1 parent 5fa13ce commit 65f3dfb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
6 changes: 6 additions & 0 deletions from/from.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ type DirStep struct {
func DirWalk(ctx context.Context, fsys fs.FS, root string) iter.Seq2[DirStep, error] {
return func(yield func(DirStep, error) bool) {
fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {
select {
case <-ctx.Done():
yield(DirStep{}, ctx.Err())
return ctx.Err()
default:
}
if !yield(DirStep{Path: path, Entry: d}, err) {
return errors.New("consumer stopped")
}
Expand Down
23 changes: 23 additions & 0 deletions from/from_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,26 @@ func TestDirWalk(t *testing.T) {
t.Errorf("DirWalk errors: got %v want none", errs)
}
}

func TestDirWalkCancellation(t *testing.T) {
fsys := fstest.MapFS(map[string]*fstest.MapFile{
"root/foo/bar.txt": {Data: []byte("hello bar")},
"root/empty": {Mode: fs.ModeDir},
"root/cat.txt": {Data: []byte("hello cat")},
})
ctx, cancel := context.WithCancel(context.Background())
cancel()

var errs []error
var dirs []string
from.DirWalk(ctx, fsys, "root")(func(ds from.DirStep, err error) bool {
if err != nil {
errs = append(errs, err)
}
dirs = append(dirs, ds.Path)
return true
})
if len(errs) == 0 {
t.Errorf("DirWalk interruption: got err nil, wanted err")
}
}

0 comments on commit 65f3dfb

Please sign in to comment.