File::Monitor(3pm)

πŸ“¦
version 1.00 Β· 3 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

okay so bestie, welcome to File::Monitor(3pm) β€” it's the User Contributed Perl Documentation and it's literally here to help you keep an eye on files and directories. πŸ‘€βœ¨

✨ NAME ✨

File::Monitor - monitor files and directories for changes. no cap, that's the whole job. πŸ’…

🌸 VERSION 🌸

This document describes File::Monitor version 1.00. yes bestie, 1.00. iconic.

πŸŽ€ SYNOPSIS πŸŽ€

okay so first you load it, then you watch stuff, then you scan. here's the group chat receipts:

use File::Monitor;

my $monitor = File::Monitor->new();

# Just watch
$monitor->watch('somefile.txt');

# Watch with callback
$monitor->watch('otherfile.txt', sub {
    my ($name, $event, $change) = @_;
    # Do stuff
});

# Watch a directory
$monitor->watch( {
    name        => 'somedir',
    recurse     => 1,
    callback    => {
        files_created => sub {
            my ($name, $event, $change) = @_;
            # Do stuff
        }
    }
} );

# First scan just finds out about the monitored files. No changes
# will be reported.
$object->scan;

# Later perform a scan and gather any changes
my @changes = $object->scan;

πŸ¦‹ DESCRIPTION πŸ¦‹

okay so this module provides a simple interface for monitoring one or more files or directories and reporting any changes that are made to them. it's giving watchdog but make it cute. πŸΆπŸ’–

It can:

  • monitor existing files for changes to any of the attributes returned by the stat function ✨
  • monitor files that don't yet exist and notify you if they are created πŸ¦‹
  • notify when a monitored file is deleted πŸ’€
  • notify when files are added or removed from a directory πŸ‘€

Some possible applications include:

  • monitoring the configuration file(s) of a long running process so they can be automatically re-read if they change πŸ”
  • implementing a 'drop box' directory that receives files to be processed in some way πŸ“₯
  • automatically rebuilding a cached object that depends on a number of files if any of those files changes πŸ› οΈ

In order to monitor a single file create a new monitor object:

my $monitor = File::Monitor->new();

Add the file to it:

$monitor->watch( 'somefile.txt' );

And then call scan periodically to check for changes:

my @changes = $monitor->scan;

The first call to scan will never report any changes; it captures a snapshot of the state of all monitored files and directories so that subsequent calls to scan can report any changes.

Note that File::Monitor doesn't provide asynchronous notifications of file changes; you have to call scan to learn if there have been any changes.

To monitor multiple files call watch for each of them:

for my $file ( @files ) {
    $monitor->watch( $file );
}

If there have been any changes scan will return a list of File::Monitor::Delta objects.

my @changes = $monitor->scan;
for my $change (@changes) {
    warn $change->name, " has changed\n";
}

Consult the documentation for File::Monitor::Delta for more information.

If you prefer you may register callbacks to be triggered when changes occur.

# Gets called for all changes
$monitor->callback( sub {
    my ($file_name, $event, $change) = @_;
    warn "$file_name has changed\n";
} );

# Called when file size changes
$monitor->callback( size => sub {
    my ($file_name, $event, $change) = @_;
    warn "$file_name has changed size\n";
} );

See File::Monitor::Delta for more information about the various event types for which callbacks may be registered.

You may register callbacks for a specific file or directory.

# Gets called for all changes to server.conf
$monitor->watch( 'server.conf', sub {
    my ($file_name, $event, $change) = @_;
    warn "Config file $file_name has changed\n";
} );

# Gets called if the owner of server.conf changes
$monitor->watch( {
    name        => 'server.conf',
    callback    => {
        uid => sub {
            my ($file_name, $event, $change) = @_;
            warn "$file_name has changed owner\n";
        }
    }
} );

This last example shows the canonical way of specifying the arguments to watch as a hash reference. See watch for more details.

πŸ“ Directories πŸ“

When monitoring a directory you can choose to ignore its contents, scan its contents one level deep or perform a recursive scan of all its subdirectories.

See File::Monitor::Object for more information and caveats.

πŸ’– INTERFACE πŸ’–

okay bestie, this is the actual toolkit β€” every method you'll ever call on a File::Monitor. let's get into it 🫢


new( %args )

spawns a brand-new File::Monitor object for you. options get passed as a reference to a hash, like so:

my $monitor = File::Monitor->new( {
    base     => $some_dir,
    callback => {
        uid => sub {
            my ($file_name, $event, $change) = @_;
            warn "$file_name has changed owner\n";
        },
        size => sub {
            my ($file_name, $event, $change) = @_;
            warn "$file_name has changed size\n";
        }
} );

both options β€” base and callback β€” are optional, so you can rawdog it with File::Monitor->new() if you want bestie, no pressure πŸ’…

the base option is your base directory. once you've set one, all the pathnames get stored internally relative to it. does that change the public interface? nope β€” the public interface still speaks absolute paths. what it does do is make it possible to relocate a File::Monitor if the directory it's watching gets moved. it's giving "portable", it's giving "adaptable" ✨

the callback option has to be a reference to a hash that maps event types β†’ handler subroutines. for the full list of available event types, go read File::Monitor::Delta. go on. we'll wait πŸ¦‹


watch( $name, $callback | { args } )

this makes a new File::Monitor::Object and bolts it onto this monitor. slay.

the hashref you pass in can carry a whole lil set of options:

$monitor->watch( {
    name        => $file_or_directory_name,
    recurse     => $should_recurse_directory,
    files       => $should_read_files_in_directory,
    callback    => {
        $some_event => sub {
            # Handler for $some_event
        },
        $other_event => sub {
            # Handler for $other_event
        }
    }
} );

and here's those options, explained properly πŸ‘‡

  • name β€” the name of the file or directory you want to monitor. relative paths get made absolute relative to the current directory at the time of the call. this one is mandatory β€” new will croak if it's missing. so like. don't forget it πŸ™ˆ
  • recurse β€” if this is a directory and recurse is true, you monitor the entire directory tree below this directory. the whole thing. every branch 🌸
  • files β€” if this is a directory and files is true, you monitor the files and directories immediately below this directory, but you don't recurse down the tree. just the one layer, bestie.
  • callback β€” a reference to a hash of callback handlers. the keys are the names of the events as described in File::Monitor::Delta.
⚠️ important: if you specify recurse or files, only the names of contained files will be monitored. changes to the contents of contained files are not detected. like, the file itself changing? spotted. the stuff inside it changing? girl, no. πŸ‘€

callback subroutines get called with these arguments:

  • $name β€” the name of the file or directory that has changed.
  • $event β€” the type of change. if the callback was registered for a specific event, it gets passed here. the actual event may be one of the events below the specified event in the event hierarchy. see File::Monitor::Delta for more details.
  • $delta β€” the File::Monitor::Delta object that describes this change. the receipts, basically πŸ’…

as a lil convenience, watch can also be called with a simpler form of arguments:

$monitor->watch( $name );

is equivalent to:

$monitor->watch( {
    name    => $name
} );

and:

$monitor->watch( $name, $callback );

is eqivalent to: (yep, that's the spelling in the source and we respect her for it πŸ’œ)

$monitor->watch( {
    name        => $name
    callback    => {
        change      => $callback
    }
} );

unwatch( $name )

removes the watcher (if there even is one) that corresponds with the specified file or directory. it's the "we're so over" button πŸŽ€

my $file = 'config.cfg';
$monitor->watch( $file );       # Now we're watching it

$monitor->unwatch( $file );     # Now we're not

scan()

does a full scan of all monitored files and directories and returns a list of changes. any callbacks you registered will have already fired before scan returns. so by the time you get your list back, the drama has already happened πŸ”₯

the very first time scan is called, it captures the current state of the various monitored files and directories β€” but reports no changes. it's just taking a lil mental snapshot. after that, we're cooking.

the return value is a list of File::Monitor::Delta objects, one for each changed file or directory:

my @changes = $monitor->scan;

for my $change ( @changes ) {
    warn $change->name, " changed\n";
}

callback( [ $event, ] $coderef )

registers a callback. if you leave out $event, the callback gets called for all changes. specify $event to limit the callback to certain event types. full list of events lives in File::Monitor::Delta, as always πŸ¦‹

$monitor->callback( sub {
    # called for all changes
} );

$monitor->callback( metadata => sub {
    # called for changes to file/directory metatdata
} );

the callback subroutine gets called with these arguments:

  • $name β€” the name of the file or directory that has changed.
  • $event β€” the type of change. if the callback was registered for a specific event, it gets passed here. the actual event may be one of the events below the specified event in the event hierarchy. see File::Monitor::Delta for more details.
  • $delta β€” the File::Monitor::Delta object that describes this change.

base

gets or sets the base directory. this is what lets the entire monitor tree get relocated. main character energy honestly πŸ‘‘

# Create a monitor and watch a couple of files
my $monitor = File::Monitor->new( { base => $some_dir } );
$monitor->watch( "$some_dir/source.c" );
$monitor->watch( "$some_dir/notes.text" );

# Now move the directory and patch up the monitor
rename( $some_dir, $other_dir );
$monitor->base( $other_dir );

# Still works
my @changes = $monitor->scan;
⚠️ if you're gonna specify a base directory, you must do it before any watches are added. that's the rule, bestie. no takesies backsies.

has_monitors

returns true if this File::Monitor has any monitors attached to it. it's used internally to police the restriction that a base directory may not be set when monitors have been added. so it's like, the bouncer at the door of the base-directory policy πŸ’…


πŸ’€ DIAGNOSTICS πŸ’€

  • A filename must be specified β€” you gotta pass unwatch the name of a file or directory to stop watching. like, we can't unwatch a vibe, we need a name πŸ™ˆ

🌈 CONFIGURATION AND ENVIRONMENT 🌈

File::Monitor requires no configuration files and no environment variables. zero setup. plug and play. we love low maintenance ✨


🧚 DEPENDENCIES 🧚

None. she's independent, she's self-sufficient, she owes nobody anything πŸ’–


🌸 INCOMPATIBILITIES 🌸

None reported. no beef, no drama, no haters πŸ’…


πŸ› BUGS AND LIMITATIONS πŸ›

No bugs have been reported. iconic behaviour honestly.

please report any bugs or feature requests to bug-file-monitor@rt.cpan.org, or through the web interface at <http://rt.cpan.org>.


πŸ‘‘ AUTHOR πŸ‘‘

Andy Armstrong <andy@hexten.net>

Faycal Chraibi originally registered the File::Monitor namespace and then kindly handed it to me. handing over a namespace is peak generosity fr fr 🫢


Copyright (c) 2007, Andy Armstrong <andy@hexten.net>. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.


πŸ”₯ DISCLAIMER OF WARRANTY πŸ”₯

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

and that's the whole page bestie πŸ₯Ή this copy was rendered by perl v5.36.0 on 2022-10-21, for File::Monitor(3pm) β€” go forth and monitor things, you absolute legend πŸ¦‹πŸ’–βœ¨

πŸ“¦ where this page comes from