aboutsummaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/editdiff.pm
blob: 015ce9c148d554c29a3db6a04227a2a50c88f02e (plain)
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
#!/usr/bin/perl
# This plugin adds a "Diff" button to the page edit form.
package IkiWiki::Plugin::editdiff;

use warnings;
use strict;
use IkiWiki 3.00;
use HTML::Entities;
use IPC::Open2;

sub import {
	hook(type => "getsetup", id => "editdiff", call => \&getsetup);
	hook(type => "formbuilder_setup", id => "editdiff",
		call => \&formbuilder_setup);
}

sub getsetup () {
	return
		plugin => {
			safe => 1,
			rebuild => 0,
			section => "web",
		},
}

sub diff ($$) {
	my $orig=shift;
	my $content=shift;

	my $sigpipe=0;
	$SIG{PIPE} = sub { $sigpipe=1; };

	my $pid = open2(*DIFFOUT, *DIFFIN, 'diff', '-u', $orig, '-');
	binmode($_, ':utf8') foreach (*DIFFIN, *DIFFOUT);

	print DIFFIN $content;
	close DIFFIN;
	my $ret='';
	while (<DIFFOUT>) {
		if (defined $ret) {
			$ret.=$_;
		}
		elsif (/^\@\@/) {
			$ret=$_;
		}
	}
	close DIFFOUT;
	waitpid $pid, 0;

	$SIG{PIPE}="default";
	return "couldn't run diff\n" if $sigpipe;

	return "<pre>".encode_entities($ret)."</pre>";
}

sub formbuilder_setup {
	my %params=@_;
	my $form=$params{form};

	return if ! defined $form->field("do") || $form->field("do") ne "edit";

	my $page=$form->field("page");
	$page = IkiWiki::possibly_foolish_untaint($page);
	return unless exists $pagesources{$page};

	push @{$params{buttons}}, "Diff";

	if ($form->submitted eq "Diff") {
		my $content=$form->field('editcontent');
		$content=~s/\r\n/\n/g;
		$content=~s/\r/\n/g;

		my $diff = diff(srcfile($pagesources{$page}), $content);
		$form->tmpl_param("page_diff", $diff);
	}
}

1