User:AnomieBOT/source/diff.pl

#!/usr/bin/perl -w -CASDL

# Note, this script requires dwdiff

use utf8;
use strict;

# binmodes
$|=1;
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';

# Define filehandle variables and prepare cleanup
my ($fh,$tmpfile)=(undef,undef);
END {
    if(defined($fh)){
        close $fh;
        unlink $tmpfile;
    }
}

# Catch various signals so the END block gets called
$SIG{$_}=sub { exit 0x80; } foreach (qw/HUP INT QUIT PIPE TERM/);

die "USAGE: $0 file\n" if @ARGV!=1;
my $file=shift;
die "USAGE: $0 file\n" unless -e $file;
die "Invalid filename\n" unless $file=~m{(?:^|/)([^</]+)<(\d+|new)>\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ\.txt$};
my ($title, $oldid)=($1,$2);
$title=~s/#/\//g;

use Cwd;
use File::Basename;
use lib File::Basename::dirname( Cwd::realpath( __FILE__ ) );
use AnomieBOT::API;
use File::Spec;
use File::Temp qw/tempfile/;

my $api=AnomieBOT::API->new('conf.ini', 1, { db => 0 });
$api->{'nopause'}=1;
my $page;
if($oldid eq 'new'){
    $page='';
} else {
    $page=$api->rawpage($title,$oldid);
    die "Could not fetch page: ".$page->{'error'}."\n" if($page->{'code'} ne 'success');
    $page=$page->{'content'};
}

($fh, $tmpfile)=tempfile('AnomieBOT-Diff-XXXXXXXXXX', DIR=>File::Spec->tmpdir());
binmode $fh, ":encoding(utf8)";
print $fh $page;
print "\e[35m$title\e[0m\n";
open(X, '-|:utf8', '/usr/bin/dwdiff', '-P', '-c:red,:green', $tmpfile, $file) or die "Couldn't exec: $!\n";
{
    local $/=undef;
    $_=<X>;
}
$_ .= "\n" unless /\n$/s;
print;