1 package Catalyst::Restarter;
5 use Cwd qw( abs_path );
6 use File::ChangeNotify;
8 use namespace::clean -except => 'meta';
18 isa => 'File::ChangeNotify::Watcher',
30 delete $p->{start_sub};
32 $p->{filter} ||= qr/(?:\/|^)(?!\.\#).+(?:\.yml$|\.yaml$|\.conf|\.pm)$/;
33 $p->{directories} ||= abs_path( File::Spec->catdir( $FindBin::Bin, '..' ) );
35 # We could make this lazily, but this lets us check that we
36 # received valid arguments for the watcher up front.
37 $self->_watcher( File::ChangeNotify->instantiate_watcher( %{$p} ) );
43 $self->_fork_and_start;
45 return unless $self->_child;
47 $self->_restart_on_changes;
53 if ( my $pid = fork ) {
61 sub _restart_on_changes {
64 my @events = $self->_watcher->wait_for_events();
65 $self->_handle_events(@events);
73 print STDERR "Saw changes to the following files:\n";
75 for my $event (@events) {
76 my $path = $event->path();
77 my $type = $event->type();
79 print STDERR " - $path ($type)\n";
83 print STDERR "Attempting to restart the server\n\n";
87 $self->_fork_and_start;
89 $self->_restart_on_changes;
95 return unless $self->_child;
97 return unless kill 0, $self->_child;
99 local $SIG{CHLD} = 'IGNORE';
100 unless ( kill 'INT', $self->_child ) {
101 # The kill 0 thing does not work on Windows, but the restarter
102 # seems to work fine on Windows with this hack.
103 return if $^O eq 'MSWin32';
104 die "Cannot send INT signal to ", $self->_child, ": $!";
114 __PACKAGE__->meta->make_immutable;
122 Catalyst::Restarter - Uses File::ChangeNotify to check for changed files and restart the server
126 my $restarter = Catalyst::Restarter->new(
127 directories => '/path/to/MyApp',
128 regex => '\.yml$|\.yaml$|\.conf|\.pm$',
129 start_sub => sub { ... }
132 $restarter->run_and_watch;
136 This class uses L<File::ChangeNotify> to watch one or more directories
137 of files and restart the Catalyst server when any of those files
142 =head2 new ( start_sub => sub { ... }, ... )
144 This method creates a new restarter object.
146 The "start_sub" argument is required. This is a subroutine reference
147 that can be used to start the Catalyst server.
151 This method forks, starts the server in a child process, and then
152 watched for changed files in the parent. When files change, it kills
153 the child, forks again, and starts a new server.
157 L<Catalyst>, <File::ChangeNotify>
161 Catalyst Contributors, see Catalyst.pm
165 This program is free software, you can redistribute it and/or modify
166 it under the same terms as Perl itself.