summaryrefslogtreecommitdiff
path: root/localworddiff
blob: 1561684ed85f48f159de0899689170189057132a (plain)
  1. #!/usr/bin/perl
  2. #
  3. # Copyright © 2013 Jonas Smedegaard <dr@jones.dk>
  4. # Description: Generate word-based diff for console or web
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 3, or (at your option)
  9. # any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful, but
  12. # WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. # Depends: libtext-markdown-perl libhtml-html5-builder libcss-perl
  20. # Depends: libtext-worddiff-perl (>= 0.08)
  21. use Text::WordDiff;
  22. use Text::Markdown qw[markdown];
  23. use CSS::Tiny;
  24. use HTML::HTML5::Builder qw[:standard];
  25. use File::Slurp;
  26. use strictures 1;
  27. use autodie;
  28. my ( $infile1, $infile2, $outfile ) = @ARGV;
  29. die 'Missing input file arguments'
  30. unless ( $infile1 and $infile2 );
  31. # use console if no output file provided as third argument
  32. unless ($outfile) {
  33. print word_diff $infile1, $infile2, { STYLE => 'ANSIColor' };
  34. exit 0;
  35. }
  36. # resolve diff
  37. my $diff = word_diff $infile1, $infile2, { STYLE => 'HTMLTwoLines' };
  38. # apply markup to each file div of resolved diff
  39. my $d = "<div class=\"file\">";
  40. my $d_ = "<\/div>";
  41. my $i;
  42. my @diffchunk;
  43. foreach ( split /(?:$d_\n)?$d/, $diff ) {
  44. if ($_) {
  45. $diffchunk[ $i++ ] = $d . markdown($_) . $d_;
  46. }
  47. }
  48. # parse styling
  49. my $css = CSS::Tiny->new();
  50. $css->read_string(<<'EOF');
  51. .fileheader {
  52. display: none;
  53. visibility: hidden;
  54. }
  55. .file {
  56. float: left;
  57. width: 49%;
  58. }
  59. .file .hunk del,
  60. .file .hunk ins {
  61. font-weight: bold;
  62. text-decoration: inherit;
  63. }
  64. .file .hunk del {
  65. color: darkred;
  66. }
  67. .file .hunk ins {
  68. color: darkgreen;
  69. }
  70. EOF
  71. # compose and save web page
  72. my $page = html(
  73. head(
  74. XML_CHUNK( $css->html ),
  75. ),
  76. body(
  77. CHUNK( $diffchunk[0] ),
  78. CHUNK( $diffchunk[1] ),
  79. ),
  80. );
  81. write_file( $outfile, $page );
  82. 1;