Created
November 2, 2012 19:30
-
-
Save leedo/4003808 to your computer and use it in GitHub Desktop.
AnyEvent directory scanner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sub scan_dir { | |
my ($path, $filter, $cb) = @_; | |
my (@queue, @matches); | |
my $cv = AE::cv; | |
my $enqueue = sub { | |
$cv->begin; | |
push @queue, shift; | |
}; | |
$enqueue->($path); | |
my $scan = sub { | |
my $path = shift; | |
aio_scandir $path, 0, sub { | |
my ($dirs, $nondirs) = @_; | |
for (@$nondirs) { | |
push @matches, "$path/$_" if $filter->("$path/$_"); | |
} | |
$enqueue->("$path/$_") for @$dirs; | |
$cv->end; | |
}; | |
}; | |
my $t = AE::idle sub { | |
if (my $dir = pop @queue) { | |
$scan->($dir); | |
} | |
}; | |
$cv->cb(sub { | |
eval {shift->recv}; | |
undef $t; | |
if ($@) { | |
warn "scanner stopped"; | |
return; | |
} | |
$cb->(\@matches); | |
}); | |
return $cv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment