1 package Catalyst::Engine::HTTP::Restarter::Watcher;
5 use base 'Class::Accessor::Fast';
9 use Time::HiRes qw/sleep/;
11 __PACKAGE__->mk_accessors( qw/delay
18 my ( $class, %args ) = @_;
32 my $watch_list = $self->_index_directory;
33 $self->watch_list( $watch_list );
38 files => [ keys %{$watch_list} ],
49 sleep $self->delay || 1;
51 eval { @changes = $self->modified->changed };
53 # File::Modified will die if a file is deleted.
54 my ($deleted_file) = $@ =~ /stat '(.+)'/;
55 push @changed_files, $deleted_file || 'unknown file';
59 # update all mtime information
60 $self->modified->update;
62 # check if any files were changed
63 @changed_files = grep { -f $_ } @changes;
65 # Check if only directories were changed. This means
66 # a new file was created.
67 unless ( @changed_files ) {
68 # re-index to find new files
69 my $new_watch = $self->_index_directory;
71 # look through the new list for new files
72 my $old_watch = $self->watch_list;
73 @changed_files = grep { ! defined $old_watch->{$_} }
76 return unless @changed_files;
80 for my $file ( @changed_files ) {
81 next unless $file =~ /\.pm$/;
82 if ( my $error = $self->_test($file) ) {
84 qq/File "$file" modified, not restarting\n\n/;
85 print STDERR '*' x 80, "\n";
87 print STDERR '*' x 80, "\n";
93 return @changed_files;
96 sub _index_directory {
99 my $dir = $self->directory || die "No directory specified";
100 my $regex = $self->regex || '\.pm$';
106 my $file = File::Spec->rel2abs($File::Find::name);
107 return unless $file =~ /$regex/;
108 return unless -f $file;
109 $file =~ s{/script/..}{};
112 # also watch the directory for changes
113 my $cur_dir = File::Spec->rel2abs($File::Find::dir);
114 $cur_dir =~ s{/script/..}{};
125 my ( $self, $file ) = @_;
128 local $SIG{__WARN__} = sub { };
130 open my $olderr, '>&STDERR';
131 open STDERR, '>', File::Spec->devnull;
132 eval "require '$file'";
133 open STDERR, '>&', $olderr;
135 return ($@) ? $@ : 0;
143 Catalyst::Engine::HTTP::Restarter::Watcher - Watch for changed application
148 my $watcher = Catalyst::Engine::HTTP::Restarter::Watcher->new(
149 directory => '/path/to/MyApp',
150 regex => '\.yml$|\.yaml$|\.pm$',
155 my @changed_files = $watcher->watch();
160 This class monitors a directory of files for changes made to any file
161 matching a regular expression. It correctly handles new files added to the
162 application as well as files that are deleted.
166 =head2 new ( directory => $path [, regex => $regex, delay => $delay ] )
168 Creates a new Watcher object.
172 Returns a list of files that have been added, deleted, or changed since the
173 last time watch was called.
177 L<Catalyst>, L<Catalyst::Engine::HTTP::Restarter>, L<File::Modified>
181 Sebastian Riedel, <sri@cpan.org>
183 Andy Grundman, <andy@hybridized.org>
187 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
191 This program is free software, you can redistribute it and/or modify it under
192 the same terms as Perl itself.