po(refreshpot): define the input charset before read()'ing
[ikiwiki] / IkiWiki / Plugin / editdiff.pm
1 #!/usr/bin/perl
2 # This plugin adds a "Diff" button to the page edit form.
3 package IkiWiki::Plugin::editdiff;
4
5 use warnings;
6 use strict;
7 use IkiWiki 2.00;
8 use HTML::Entities;
9 use IPC::Open2;
10
11 sub import { #{{{
12         hook(type => "getsetup", id => "editdiff", call => \&getsetup);
13         hook(type => "formbuilder_setup", id => "editdiff",
14                 call => \&formbuilder_setup);
15 } #}}}
16
17 sub getsetup () { #{{{
18         return
19                 plugin => {
20                         safe => 1,
21                         rebuild => 0,
22                 },
23 } #}}}
24
25 sub diff ($$) { #{{{
26         my $orig=shift;
27         my $content=shift;
28
29         my $sigpipe=0;
30         $SIG{PIPE} = sub { $sigpipe=1; };
31
32         my $pid = open2(*DIFFOUT, *DIFFIN, 'diff', '-u', $orig, '-');
33         binmode($_, ':utf8') foreach (*DIFFIN, *DIFFOUT);
34
35         print DIFFIN $content;
36         close DIFFIN;
37         my $ret='';
38         while (<DIFFOUT>) {
39                 if (defined $ret) {
40                         $ret.=$_;
41                 }
42                 elsif (/^\@\@/) {
43                         $ret=$_;
44                 }
45         }
46         close DIFFOUT;
47         waitpid $pid, 0;
48
49         $SIG{PIPE}="default";
50         return "couldn't run diff\n" if $sigpipe;
51
52         return "<pre>".encode_entities($ret)."</pre>";
53 } #}}}
54
55 sub formbuilder_setup { #{{{
56         my %params=@_;
57         my $form=$params{form};
58
59         return if ! defined $form->field("do") || $form->field("do") ne "edit";
60
61         my $page=$form->field("page");
62         $page = IkiWiki::possibly_foolish_untaint($page);
63         return unless exists $pagesources{$page};
64
65         push @{$params{buttons}}, "Diff";
66
67         if ($form->submitted eq "Diff") {
68                 my $content=$form->field('editcontent');
69                 $content=~s/\r\n/\n/g;
70                 $content=~s/\r/\n/g;
71
72                 my $diff = diff(srcfile($pagesources{$page}), $content);
73                 $form->tmpl_param("page_preview", $diff);
74         }
75 } #}}}
76
77 1