add AbortableScanView function (#23245)

This commit is contained in:
Rachel Culpepper
2023-09-22 10:03:53 -04:00
committed by GitHub
parent a074bf9cbf
commit 68dd82c902

View File

@@ -97,6 +97,40 @@ func ScanView(ctx context.Context, view ClearableView, cb func(path string)) err
return nil
}
// AbortableScanView is used to scan all the keys in a view iteratively,
// but will abort the scan if cb returns false
func AbortableScanView(ctx context.Context, view ClearableView, cb func(path string) (cont bool)) error {
frontier := []string{""}
for len(frontier) > 0 {
n := len(frontier)
current := frontier[n-1]
frontier = frontier[:n-1]
// List the contents
contents, err := view.List(ctx, current)
if err != nil {
return errwrap.Wrapf(fmt.Sprintf("list failed at path %q: {{err}}", current), err)
}
// Handle the contents in the directory
for _, c := range contents {
// Exit if the context has been canceled
if ctx.Err() != nil {
return ctx.Err()
}
fullPath := current + c
if strings.HasSuffix(c, "/") {
frontier = append(frontier, fullPath)
} else {
if !cb(fullPath) {
return nil
}
}
}
}
return nil
}
// CollectKeys is used to collect all the keys in a view
func CollectKeys(ctx context.Context, view ClearableView) ([]string, error) {
return CollectKeysWithPrefix(ctx, view, "")