summaryrefslogtreecommitdiff
path: root/localworddiff
blob: 86c6f00e3afaa959a5e41368ab7e9b76707ad960 (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. # read infiles using File::Slurp (Text::WordDiff don't handle UTF-8)
  32. my $text1 = read_file( $infile1, binmode => ':utf8' );
  33. my $text2 = read_file( $infile2, binmode => ':utf8' );
  34. # use console if no output file provided as third argument
  35. unless ($outfile) {
  36. print word_diff \$text1, \$text2, { STYLE => 'ANSIColor' };
  37. exit 0;
  38. }
  39. # resolve diff
  40. my $diff = word_diff \$text1, \$text2, { STYLE => 'HTMLTwoLines' };
  41. # apply markup to each file div of resolved diff
  42. my $d = "<div class=\"file\">";
  43. my $d_ = "<\/div>";
  44. my $i;
  45. my @diffchunk;
  46. foreach ( split /(?:$d_\n)?$d/, $diff ) {
  47. if ($_) {
  48. $diffchunk[ $i++ ] = $d . markdown($_) . $d_;
  49. }
  50. }
  51. # parse styling
  52. my $css = CSS::Tiny->new();
  53. $css->read_string(<<'EOF');
  54. .fileheader {
  55. display: none;
  56. visibility: hidden;
  57. }
  58. .file {
  59. float: left;
  60. width: 49%;
  61. }
  62. .file .hunk del,
  63. .file .hunk ins {
  64. font-weight: bold;
  65. text-decoration: inherit;
  66. }
  67. .file .hunk del {
  68. color: darkred;
  69. }
  70. .file .hunk ins {
  71. color: darkgreen;
  72. }
  73. EOF
  74. # compose and save web page
  75. my $page = html(
  76. head(
  77. XML_CHUNK( $css->html ),
  78. ),
  79. body(
  80. CHUNK( $diffchunk[0] ),
  81. CHUNK( $diffchunk[1] ),
  82. ),
  83. );
  84. write_file( $outfile, { binmode => ':utf8' }, $page );
  85. 1;