- #!/usr/bin/perl
- #
- # Copyright © 2013 Jonas Smedegaard <dr@jones.dk>
- # Description: Generate word-based diff for console or web
- #
- # This program is free software; you can redistribute it and/or modify
- # it under the terms of the GNU General Public License as published by
- # the Free Software Foundation; either version 3, or (at your option)
- # any later version.
- #
- # This program is distributed in the hope that it will be useful, but
- # WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- # General Public License for more details.
- #
- # You should have received a copy of the GNU General Public License
- # along with this program. If not, see <http://www.gnu.org/licenses/>.
- #
- # Depends: libtext-markdown-perl libhtml-html5-builder libcss-perl
- # Depends: libtext-worddiff-perl (>= 0.08)
- use Text::WordDiff;
- use Text::Markdown qw[markdown];
- use CSS::Tiny;
- use HTML::HTML5::Builder qw[:standard];
- use File::Slurp;
- use strictures 1;
- use autodie;
- my ( $infile1, $infile2, $outfile ) = @ARGV;
- die 'Missing input file arguments'
- unless ( $infile1 and $infile2 );
- # read infiles using File::Slurp (Text::WordDiff don't handle UTF-8)
- my $text1 = read_file( $infile1, binmode => ':utf8' );
- my $text2 = read_file( $infile2, binmode => ':utf8' );
- # use console if no output file provided as third argument
- unless ($outfile) {
- print word_diff \$text1, \$text2, { STYLE => 'ANSIColor' };
- exit 0;
- }
- # resolve diff
- my $diff = word_diff \$text1, \$text2, { STYLE => 'HTMLTwoLines' };
- # apply markup to each file div of resolved diff
- my $d = "<div class=\"file\">";
- my $d_ = "<\/div>";
- my $i;
- my @diffchunk;
- foreach ( split /(?:$d_\n)?$d/, $diff ) {
- if ($_) {
- $diffchunk[ $i++ ] = $d . markdown($_) . $d_;
- }
- }
- # parse styling
- my $css = CSS::Tiny->new();
- $css->read_string(<<'EOF');
- .fileheader {
- display: none;
- visibility: hidden;
- }
- .file {
- float: left;
- width: 49%;
- }
- .file .hunk del,
- .file .hunk ins {
- font-weight: bold;
- text-decoration: inherit;
- }
- .file .hunk del {
- color: darkred;
- }
- .file .hunk ins {
- color: darkgreen;
- }
- EOF
- # compose and save web page
- my $page = html(
- head(
- XML_CHUNK( $css->html ),
- ),
- body(
- CHUNK( $diffchunk[0] ),
- CHUNK( $diffchunk[1] ),
- ),
- );
- write_file( $outfile, { binmode => ':utf8' }, $page );
- 1;
|