The following code converts a piece of source code to HTML, highlighting the lines that have changed compared to a previous (unshown) version of the code. Call the code with two arguments like perl bolddiff.pl oldfile newfile to show newfiles with the files that have been added or changed since old bolded.

#!perl use warnings; use strict; use CGI; 1 == @ARGV || 2 == @ARGV or die "usage: perl bolddiff.pl file1 file2"; my $two = 2 <= @ARGV; my ($f0n, $f1n) = @ARGV; my $key = "BOLDDIFF_" . join("", map { int(rand(10)) } 0..5); my $H; if ($two) { open $H, "-|", "diff", "-bD", $key, "--", $f1n, $f0n or die; } else { open $H, "<", $f0n or die; } print qq{<pre class="clisting">\n}; my $tap = 1; my $diff = 0; while (<$H>) { if (/\b\Q$key\E\b/) { if (/\A#ifdef \Q$key\E\b/) { $tap = 0; $diff = 1; } elsif (/\A#ifndef \Q$key\E\b/) { $tap = 1; $diff = 1; } elsif (/\A#else \/\* \Q$key\E\b/) { $tap = !$tap; } elsif (/\A#endif \/\* (! )?\Q$key\E\b/) { $tap = 1; $diff = 0; } else { die "ifdef key unexpected: $_"; } } else { if ($tap) { s/&/&amp;/g; s/</&lt;/g; s/>/&gt;/g; $diff and s/(.*)/<strong>$1<\/strong>/; print; } } } print qq{</pre>\n}; __END__

Replies are listed 'Best First'.
Re: Htmlify code with differences
by ambrus (Abbot) on Nov 14, 2008 at 20:53 UTC

    By the way, you may woner why I'm calling diff with the order of arguments swapped to generate a reverse diff.

    This is required because I'm ignoring the blanks so and a line is considered unchanged diff will show the version in the first file. So, for example, if the original file says

    bar
    and the new file says
    if foo bar
    this gives the right output
    if foo bar
    (with only the first line bold), instead of the wrong output
    if foo bar
    (with only the first line bold again).
Re: Htmlify code with differences
by Anonymous Monk on Nov 15, 2008 at 03:59 UTC