aboutsummaryrefslogtreecommitdiffstats
path: root/feature-tests/subscript.pl
blob: 8550409c63e1d521cdfed316eddf498bc7e20ef5 (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
use strict;
use Irssi;
use Irssi::TextUI; # for sbar_items_redraw

use vars qw($VERSION %IRSSI);

$VERSION = "0.1";

%IRSSI = (
	authors         => "shabble",
	contact         => 'shabble+irssi@metavore.org, shabble@#irssi/Freenode',
	name            => "",
	description     => "",
	license         => "Public Domain",
	changed         => ""
);

my $functions = {};

init();

sub _input {
    return int rand 1000;
}

sub load {
    my $file = shift;
    my $funcs;
    if (-f $file) {
        print "Loading from file: $file";
        $funcs = do $file;
    }
    if (not defined $funcs) {
        if ($@) {
            print "failed to parse $file: $@";

        } elsif ($!) {
            print "failed to read $file: $!";

        }
        return;
    }
    my $ref = ref $funcs;
    if ($ref ne 'HASH') {
        print "$file didn't return a hashref: ", defined $ref ? $ref : 'undef';
        return;
    }

    foreach my $name (keys %$funcs) {
        my $func = $funcs->{$name};
        if (exists $functions->{$name}) {
            print "Redefining function $name";
        } else {
            print "adding function: $name";
        }
        $functions->{$name} = $func;
    }

    print "Loaded " . scalar(keys(%$funcs)) . " functions";
}

sub init {
    Irssi::command_bind('subload', \&cmd_subload);
    Irssi::command_bind('sublist', \&cmd_sublist);
    Irssi::command_bind('subcall', \&cmd_subcall);
}

sub cmd_subload {
    my $args = shift;
    print "Going to load: $args";
    load($args);
}

sub cmd_sublist {
    foreach my $name (keys %$functions) {
        my $func = $functions->{$name};
        print "Function: $name => $func";
    }
}

sub cmd_subcall {
    my $args = shift;
    my ($cmd, $cmdargs);
    if ($args =~ m/^(\w+\b)(.*)$/) {
        $cmd = $1; $cmdargs = $2;
    } else {
        print "Couldn't parse $args";
        return;
    }
    my $fun = $functions->{$cmd};

    if (ref $fun eq 'CODE') {
        print "Calling $cmd with $cmdargs";
        $fun->($cmdargs);
    } else {
        print "$cmd is not a coderef. cannot run";
    }
}