aboutsummaryrefslogtreecommitdiff
path: root/lib/ScanDir.rakumod
blob: 0f33a8bc4f8cbd592741ba3828f23f2d4757e175 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use v6.d;
unit module ScanDir;
 
class End {};
 
sub scan-dir(*@paths --> Supplyis export {
    my $s = supply {
        my %watched-dirs;
 
        CATCH { when X::IO { }default { warn $_ } }
 
        sub start-watching(IO::Path $dir{
            return unless $dir ~~ :e;
            return if %watched-dirs{$dir.Str};
            %watched-dirs{$dir.Str} = True;
            
            whenever $dir.watch {
                my $path-io = .path.IO;
                emit $path-io;
                when $path-io ~~ :e & :d {
                    add-dir($path-iounless %watched-dirs{$path-io.Str};
                }
                when $path-io ~~ :!e {
                    %watched-dirs{$path-io.Str}:delete
                }
            }
        }
 
        sub add-dir(*@todo{
            while @todo {
                my $next = @todo.shift;
 
                next unless $next ~~ :e & :r & :d;
                start-watching($next);
 
                for $next.dir {
                    emit $_;
                    when .e && .d {
                        @todo.push($_);
                        start-watching($_);
                    }
                }
            }
 
        }
 
        add-dir(@paths».IO);
        emit End;
    };
 
    # let's not return multiple events for the same path too quickly, 
    # otherwise the consumer will get overwhelmed when (for example) a 
    # large file is being written 
    return $s.unique(
        with => sub { $^a !~~ End && $^b !~~ End && $^a eq $^b },
        expires => 0.1,
    );
}