1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # for systems lacking Linux::Inotify2 or IO::KQueue, just emulates
5 # enough of Linux::Inotify2
6 package PublicInbox::FakeInotify;
8 use Time::HiRes qw(stat);
10 my $IN_CLOSE = 0x08 | 0x10; # match Linux inotify
11 # my $IN_MOVED_TO = 0x80;
12 # my $IN_CREATE = 0x100;
13 sub MOVED_TO_OR_CREATE () { 0x80 | 0x100 }
15 my $poll_intvl = 2; # same as Filesys::Notify::Simple
20 warn "E: FakeInotify->poll: $@\n" if $@;
21 PublicInbox::DS::add_timer($poll_intvl, \&poll_once, $self);
25 my $self = bless { watch => {} }, __PACKAGE__;
26 PublicInbox::DS::add_timer($poll_intvl, \&poll_once, $self);
30 # behaves like Linux::Inotify2->watch
32 my ($self, $path, $mask, $cb) = @_;
33 my @st = stat($path) or return;
34 my $k = "$path\0$mask";
35 $self->{watch}->{$k} = [ $st[10], $cb ]; # 10 - ctime
36 bless [ $self->{watch}, $k ], 'PublicInbox::FakeInotify::Watch';
39 sub on_new_files ($$$$) {
40 my ($dh, $cb, $path, $old_ctime) = @_;
41 while (defined(my $base = readdir($dh))) {
42 next if $base =~ /\A\.\.?\z/;
43 my $full = "$path/$base";
45 if (@st && $st[10] > $old_ctime) {
46 bless \$full, 'PublicInbox::FakeInotify::Event';
47 eval { $cb->(\$full) };
52 # behaves like non-blocking Linux::Inotify2->poll
55 my $watch = $self->{watch} or return;
56 for my $x (keys %$watch) {
57 my ($path, $mask) = split(/\0/, $x, 2);
58 my @now = stat($path) or next;
59 my $prv = $watch->{$x};
61 my $old_ctime = $prv->[0];
62 if ($old_ctime != $now[10]) {
63 if (($mask & $IN_CLOSE) == $IN_CLOSE) {
65 } elsif ($mask & MOVED_TO_OR_CREATE) {
66 opendir(my $dh, $path) or do {
67 warn "W: opendir $path: $!\n";
70 on_new_files($dh, $cb, $path, $old_ctime);
73 @$prv = ($now[10], $cb);
77 package PublicInbox::FakeInotify::Watch;
82 delete $self->[0]->{$self->[1]};
85 package PublicInbox::FakeInotify::Event;
88 sub fullname { ${$_[0]} }