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
21 warn "E: FakeInotify->poll: $@\n" if $@;
22 PublicInbox::DS::add_timer($poll_intvl, poll_once($self));
27 my $self = bless { watch => {} }, __PACKAGE__;
28 PublicInbox::DS::add_timer($poll_intvl, poll_once($self));
32 # behaves like Linux::Inotify2->watch
34 my ($self, $path, $mask, $cb) = @_;
35 my @st = stat($path) or return;
36 my $k = "$path\0$mask";
37 $self->{watch}->{$k} = [ $st[10], $cb ]; # 10 - ctime
38 bless [ $self->{watch}, $k ], 'PublicInbox::FakeInotify::Watch';
41 sub on_new_files ($$$$) {
42 my ($dh, $cb, $path, $old_ctime) = @_;
43 while (defined(my $base = readdir($dh))) {
44 next if $base =~ /\A\.\.?\z/;
45 my $full = "$path/$base";
47 if (@st && $st[10] > $old_ctime) {
48 bless \$full, 'PublicInbox::FakeInotify::Event';
49 eval { $cb->(\$full) };
54 # behaves like non-blocking Linux::Inotify2->poll
57 my $watch = $self->{watch} or return;
58 for my $x (keys %$watch) {
59 my ($path, $mask) = split(/\0/, $x, 2);
60 my @now = stat($path) or next;
61 my $prv = $watch->{$x};
63 my $old_ctime = $prv->[0];
64 if ($old_ctime != $now[10]) {
65 if (($mask & $IN_CLOSE) == $IN_CLOSE) {
67 } elsif ($mask & MOVED_TO_OR_CREATE) {
68 opendir(my $dh, $path) or do {
69 warn "W: opendir $path: $!\n";
72 on_new_files($dh, $cb, $path, $old_ctime);
75 @$prv = ($now[10], $cb);
79 package PublicInbox::FakeInotify::Watch;
84 delete $self->[0]->{$self->[1]};
87 package PublicInbox::FakeInotify::Event;
90 sub fullname { ${$_[0]} }