aboutsummaryrefslogtreecommitdiffstats
path: root/feature-tests/frog_reload.pl
blob: 678c87db0e887ab8f326d78123a008a619f526f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use strict;
use warnings;

use Irssi;
use File::ChangeNotify();
use File::Spec ();
use File::Basename qw(basename);

#my $THIS_SCRIPT = basename __FILE__;

my $irssi_dir = Irssi::get_irssi_dir();
my @watch_dirs = ($irssi_dir, $irssi_dir . '/scripts',
                  $irssi_dir . '/scripts/autorun');

my $watcher = File::ChangeNotify->instantiate_watcher
  (
   directories => \@watch_dirs,
   filter => qr/\.(?:pl|py)$/,
  );

my @watchers = File::ChangeNotify->usable_classes();
print "Started reloader watching: ", join(", ", @watch_dirs), " using $watchers[0]";

my %action_for = (
	create => sub {
		my ($path) = @_;
		Irssi::print ("CREATE: Loading $path");
        load_script($path);
	},

	modify => sub {
		my ($path) = @_;
		Irssi::print ("MODIFY: reloading $path");
        reload($path);
    },

	delete => sub {
		my ($path) = @_;
		Irssi::print ("DELETE: Unloading $path");
        unload_script($path);
	},
);

#TODO: change me back.
Irssi::timeout_add(3000, \&timer_sub, undef);

sub timer_sub {
    print "Timer sub called";
    my @new_events = $watcher->new_events;
	for my $event (@new_events) {

        print "Handling event: ", $event->type, " path: ", $event->path;

		if (my $callback = $action_for{$event->type}) {
			$callback->($event->path);
		}
	}
}

sub reload {
    my ($path) = @_;

    unload_script($path);
    load_script($path);
}

sub unload_script {
    my ($script_path) = @_;
    my $name = filepath_to_script($script_path);

    if (script_is_loaded($name)) {
        Irssi::print ("unloading $name...");
        Irssi::command("script unload $name");
    }
}

sub load_script {
    my ($script_path) = @_;
    Irssi::command("script load \"$script_path\"");
}

sub filepath_to_script {
    my ($path) = @_;

    my $name = basename $path;
    $name =~ s/\.pl$//i;

    return $name;
}

sub script_is_loaded {
    my $name = shift;
    print "Checking if $name is loaded";
    no strict 'refs';
    my $retval = defined %{ "Irssi::Script::${name}::" };
    use strict 'refs';

    return $retval;
}