* Allow plugins to add new types of tests that can be used in PageSpecs.
[ikiwiki] / IkiWiki / Plugin / conditional.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::conditional;
3
4 use warnings;
5 use strict;
6 use IkiWiki;
7 use UNIVERSAL;
8
9 # Globals used to pass information into the PageSpec functions.
10 our ($sourcepage, $destpage);
11
12 sub import { #{{{
13         hook(type => "preprocess", id => "if", call => \&preprocess_if);
14 } # }}}
15
16 sub preprocess_if (@) { #{{{
17         my %params=@_;
18
19         if (! exists $params{test} || ! exists $params{then}) {
20                 return "[[if requires \"test\" and \"then\" parameters]]";
21         }
22
23         my $result=0;
24         $sourcepage=$params{page};
25         $destpage=$params{destpage};
26         # An optimisation to avoid needless looping over every page
27         # and adding of dependencies for simple uses of some of the
28         # tests.
29         if ($params{test} =~ /^(enabled|sourcepage|destpage)\((.*)\)$/) {
30                 $result=eval "IkiWiki::PageSpec::match_$1(undef, ".
31                         IkiWiki::safequote($2).")";
32         }
33         else {
34                 add_depends($params{page}, $params{test});
35
36                 foreach my $page (keys %pagesources) {
37                         if (pagespec_match($page, $params{test}, $params{page})) {
38                                 $result=1;
39                                 last;
40                         }
41                 }
42         }
43         $sourcepage="";
44         $destpage="";
45
46         my $ret;
47         if ($result) {
48                 $ret=$params{then};
49         }
50         elsif (exists $params{else}) {
51                 $ret=$params{else};
52         }
53         else {
54                 $ret="";
55         }
56         return IkiWiki::preprocess($params{page}, $params{destpage}, $ret);
57 } # }}}
58
59 package IkiWiki::PageSpec;
60
61 sub match_enabled ($$) { #{{{
62         shift;
63         my $plugin=shift;
64         
65         # test if the plugin is enabled
66         return UNIVERSAL::can("IkiWiki::Plugin::".$plugin, "import");
67 } #}}}
68
69 sub match_sourcepage ($$) { #{{{
70         shift;
71         my $glob=shift;
72         
73         return match_glob($IkiWiki::Plugin::conditional::sourcepage, $glob,
74                 $IkiWiki::Plugin::conditional::sourcepage);
75 } #}}}
76
77 sub match_destpage ($$) { #{{{
78         shift;
79         my $glob=shift;
80         
81         return match_glob($IkiWiki::Plugin::conditional::destpage, $glob,
82                 $IkiWiki::Plugin::conditional::sourcepage);
83 } #}}}
84
85 sub match_included ($$) { #{{{
86         return $IkiWiki::Plugin::conditional::sourcepage ne $IkiWiki::Plugin::conditional::destpage;
87 } #}}}
88
89 1