App-pfswatch

 view release on metacpan or  search on metacpan

lib/App/pfswatch.pm  view on Meta::CPAN


    my @path = @{ $self->{path} };
    warn sprintf "Start watching %s\n", join ',', @path
        unless $self->{quiet};

    my $watcher = Filesys::Notify::Simple->new( \@path );
    my $cb      = $self->_child_callback($watcher);

LOOP:
    if ( my $pid = fork ) {
        waitpid( $pid, 0 );
        goto LOOP;
    }
    elsif ( $pid == 0 ) {

        # child
        $watcher->wait($cb);
    }
    else {
        die "cannot fork: $!";
    }
}

sub _child_callback {
    my $self    = shift;
    my $watcher = shift;

    my @cmd             = @{ $self->{exec} };
    my $ignored_pattern = $self->ignored_pattern;

    sub {
        my @events = @_;
        my @files;
        for my $e (@events) {
            warn sprintf "[PFSWATCH_DEBUG] Path:%s\n", $e->{path}
                if $ENV{PFSWATCH_DEBUG};
            if ( $e->{path} !~ $ignored_pattern ) {
                push @files, $e->{path};
                last;
            }
        }
        if ( scalar @files > 0 ) {
            warn sprintf "exec %s\n", join ' ', @cmd
                unless $self->{quiet};
            if ( $self->{pipe} ) {
                open my $child_stdin, "|-", @cmd
                    or die $!;
                print $child_stdin @files;
                close $child_stdin or die $!;
                exit 0;
            }
            else {
                exec @cmd or die $!;
            }
        }
    };
}

sub parse_argv {
    my $class = shift;
    local @ARGV = @_;

    my $p = Getopt::Long::Parser->new( config => ['pass_through'] );
    $p->getoptions( \my %opts, 'pipe', 'quiet', 'help|h' );

    my ( @path, @cmd );
    my $exec_re = qr/^-(e|-exec)$/i;
    while ( my $arg = shift @ARGV ) {
        if ( $arg =~ $exec_re ) {
            @cmd = splice @ARGV, 0, scalar @ARGV;
        }
        else {
            push @path, $arg;
        }
    }
    $opts{path} = \@path;
    $opts{exec} = \@cmd;

    return %opts;
}

my @DEFAULT_IGNORED = (
    '',    # dotfile
);

sub ignored_pattern {
    qr{^.*/\..+$};    #dotfile
}

sub _is_arrayref {
    my $v = shift;
    $v && ref $v eq 'ARRAY' && scalar @$v > 0 ? 1 : 0;
}

1;
__END__

=head1 NAME

App::pfswatch - a simple utility that detects changes in a filesystem and run given command

=head1 SYNOPSIS

    use App::pfswatch->new;
    App::pfswatch->new_with_options(@ARGV)->run;

=head1 DESCRIPTION

Use L<pfswatch> instead of App::pfswatch.

=head1 AUTHOR

Yoshihiro Sasaki E<lt>ysasaki at cpan.orgE<gt>

=head1 SEE ALSO

L<Filesys::Notify::Simple>, L<App::watcher>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 5.588 seconds using v1.00-cache-2.02-grep-82fe00e-cpan-c30982ac1bc3 )