Centralize storage walk emission
This commit is contained in:
63
internal/storage/walk.go
Normal file
63
internal/storage/walk.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type WalkEmitter struct {
|
||||
ctx context.Context
|
||||
backend string
|
||||
opts WalkOptions
|
||||
fn WalkFunc
|
||||
count int
|
||||
}
|
||||
|
||||
func NewWalkEmitter(ctx context.Context, backend string, opts WalkOptions, fn WalkFunc) *WalkEmitter {
|
||||
return &WalkEmitter{
|
||||
ctx: ctx,
|
||||
backend: backend,
|
||||
opts: opts,
|
||||
fn: fn,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *WalkEmitter) Emit(entry Entry) error {
|
||||
if err := e.ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.opts.Limit > 0 && e.count >= e.opts.Limit {
|
||||
return ErrStopWalk
|
||||
}
|
||||
e.count++
|
||||
if err := e.fn(entry); err != nil {
|
||||
if errors.Is(err, ErrStopWalk) {
|
||||
return ErrStopWalk
|
||||
}
|
||||
return NewError(OpWalk, e.backend, entry.Path, ErrUnknown, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *WalkEmitter) LimitReached() bool {
|
||||
return e.opts.Limit > 0 && e.count >= e.opts.Limit
|
||||
}
|
||||
|
||||
func FinishWalk(err error) error {
|
||||
if errors.Is(err, ErrStopWalk) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func HasAny(ctx context.Context, backend Backend, prefix string) (bool, error) {
|
||||
found := false
|
||||
err := backend.Walk(ctx, prefix, WalkOptions{Recursive: false, Limit: 1}, func(Entry) error {
|
||||
found = true
|
||||
return ErrStopWalk
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
Reference in New Issue
Block a user