668f331a654055471fda26e3d84cfb68bbcbe8df
[WebKit-https.git] / Websites / bugs.webkit.org / PrettyPatch / PrettyPatch.rb
1 require 'cgi'
2 require 'diff'
3 require 'open3'
4 require 'open-uri'
5 require 'pp'
6 require 'set'
7 require 'tempfile'
8
9 module PrettyPatch
10
11 public
12
13     GIT_PATH = "git"
14
15     def self.prettify(string)
16         $last_prettify_file_count = -1
17         $last_prettify_part_count = { "remove" => 0, "add" => 0, "shared" => 0, "binary" => 0, "extract-error" => 0 }
18         string = normalize_line_ending(string)
19         str = "#{HEADER}<body>\n"
20
21         # Just look at the first line to see if it is an SVN revision number as added
22         # by webkit-patch for git checkouts.
23         $svn_revision = 0
24         string.each_line do |line|
25             match = /^Subversion\ Revision: (\d*)$/.match(line)
26             unless match.nil?
27                 str << "<span class='revision'>#{match[1]}</span>\n"
28                 $svn_revision = match[1].to_i;
29             end
30             break
31         end
32
33         fileDiffs = FileDiff.parse(string)
34
35         $last_prettify_file_count = fileDiffs.length
36         str << fileDiffs.collect{ |diff| diff.to_html }.join
37         str << "</body></html>"
38     end
39
40     def self.filename_from_diff_header(line)
41         DIFF_HEADER_FORMATS.each do |format|
42             match = format.match(line)
43             return match[1] unless match.nil?
44         end
45         nil
46     end
47
48     def self.diff_header?(line)
49         RELAXED_DIFF_HEADER_FORMATS.any? { |format| line =~ format }
50     end
51
52 private
53     DIFF_HEADER_FORMATS = [
54         /^Index: (.*)\r?$/,
55         /^diff --git "?a\/.+"? "?b\/(.+)"?\r?$/,
56         /^\+\+\+ ([^\t]+)(\t.*)?\r?$/
57     ]
58
59     RELAXED_DIFF_HEADER_FORMATS = [
60         /^Index:/,
61         /^diff/
62     ]
63
64     BINARY_FILE_MARKER_FORMAT = /^Cannot display: file marked as a binary type.$/
65
66     IMAGE_FILE_MARKER_FORMAT = /^svn:mime-type = image\/png$/
67
68     GIT_INDEX_MARKER_FORMAT = /^index ([0-9a-f]{40})\.\.([0-9a-f]{40})/
69
70     GIT_BINARY_FILE_MARKER_FORMAT = /^GIT binary patch$/
71
72     GIT_BINARY_PATCH_FORMAT = /^(literal|delta) \d+$/
73
74     GIT_LITERAL_FORMAT = /^literal \d+$/
75
76     GIT_DELTA_FORMAT = /^delta \d+$/
77
78     START_OF_BINARY_DATA_FORMAT = /^[0-9a-zA-Z\+\/=]{20,}/ # Assume 20 chars without a space is base64 binary data.
79
80     START_OF_SECTION_FORMAT = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@\s*(.*)/
81
82     START_OF_EXTENT_STRING = "%c" % 0
83     END_OF_EXTENT_STRING = "%c" % 1
84
85     # We won't search for intra-line diffs in lines longer than this length, to avoid hangs. See <http://webkit.org/b/56109>.
86     MAXIMUM_INTRALINE_DIFF_LINE_LENGTH = 10000
87
88     SMALLEST_EQUAL_OPERATION = 3
89
90     OPENSOURCE_TRAC_URL = "http://trac.webkit.org/"
91
92     OPENSOURCE_DIRS = Set.new %w[
93         Examples
94         LayoutTests
95         PerformanceTests
96         Source
97         Tools
98         WebKitLibraries
99         Websites
100     ]
101
102     IMAGE_CHECKSUM_ERROR = "INVALID: Image lacks a checksum. This will fail with a MISSING error in run-webkit-tests. Always generate new png files using run-webkit-tests."
103
104     def self.normalize_line_ending(s)
105         if RUBY_VERSION >= "1.9"
106             # Transliteration table from http://stackoverflow.com/a/6609998
107             transliteration_table = { '\xc2\x82' => ',',        # High code comma
108                                       '\xc2\x84' => ',,',       # High code double comma
109                                       '\xc2\x85' => '...',      # Tripple dot
110                                       '\xc2\x88' => '^',        # High carat
111                                       '\xc2\x91' => '\x27',     # Forward single quote
112                                       '\xc2\x92' => '\x27',     # Reverse single quote
113                                       '\xc2\x93' => '\x22',     # Forward double quote
114                                       '\xc2\x94' => '\x22',     # Reverse double quote
115                                       '\xc2\x95' => ' ',
116                                       '\xc2\x96' => '-',        # High hyphen
117                                       '\xc2\x97' => '--',       # Double hyphen
118                                       '\xc2\x99' => ' ',
119                                       '\xc2\xa0' => ' ',
120                                       '\xc2\xa6' => '|',        # Split vertical bar
121                                       '\xc2\xab' => '<<',       # Double less than
122                                       '\xc2\xbb' => '>>',       # Double greater than
123                                       '\xc2\xbc' => '1/4',      # one quarter
124                                       '\xc2\xbd' => '1/2',      # one half
125                                       '\xc2\xbe' => '3/4',      # three quarters
126                                       '\xca\xbf' => '\x27',     # c-single quote
127                                       '\xcc\xa8' => '',         # modifier - under curve
128                                       '\xcc\xb1' => ''          # modifier - under line
129                                    }
130             encoded_string = s.force_encoding('UTF-8').encode('UTF-16', :invalid => :replace, :replace => '', :fallback => transliteration_table).encode('UTF-8')
131             encoded_string.gsub /\r\n?/, "\n"
132         else
133             s.gsub /\r\n?/, "\n"
134         end
135     end
136
137     def self.find_url_and_path(file_path)
138         # Search file_path from the bottom up, at each level checking whether
139         # we've found a directory we know exists in the source tree.
140
141         dirname, basename = File.split(file_path)
142         dirname.split(/\//).reverse.inject(basename) do |path, directory|
143             path = directory + "/" + path
144
145             return [OPENSOURCE_TRAC_URL, path] if OPENSOURCE_DIRS.include?(directory)
146
147             path
148         end
149
150         [nil, file_path]
151     end
152
153     def self.linkifyFilename(filename)
154         url, pathBeneathTrunk = find_url_and_path(filename)
155
156         url.nil? ? filename : "<a href='#{url}browser/trunk/#{pathBeneathTrunk}'>#{filename}</a>"
157     end
158
159
160     HEADER =<<EOF
161 <html>
162 <head>
163 <style>
164 :link, :visited {
165     text-decoration: none;
166     border-bottom: 1px dotted;
167 }
168
169 :link {
170     color: #039;
171 }
172
173 .FileDiff {
174     background-color: #f8f8f8;
175     border: 1px solid #ddd;
176     font-family: monospace;
177     margin: 1em 0;
178     position: relative;
179 }
180
181 h1 {
182     color: #333;
183     font-family: sans-serif;
184     font-size: 1em;
185     margin-left: 0.5em;
186     display: table-cell;
187     width: 100%;
188     padding: 0.5em;
189 }
190
191 h1 :link, h1 :visited {
192     color: inherit;
193 }
194
195 h1 :hover {
196     color: #555;
197     background-color: #eee;
198 }
199
200 .DiffLinks {
201     float: right;
202 }
203
204 .FileDiffLinkContainer {
205     opacity: 0;
206     display: table-cell;
207     padding-right: 0.5em;
208     white-space: nowrap;
209 }
210
211 .DiffSection {
212     background-color: white;
213     border: solid #ddd;
214     border-width: 1px 0px;
215 }
216
217 .ExpansionLine, .LineContainer {
218     white-space: nowrap;
219 }
220
221 .sidebyside .DiffBlockPart.add:first-child {
222     float: right;
223 }
224
225 .LineSide,
226 .sidebyside .DiffBlockPart.remove,
227 .sidebyside .DiffBlockPart.add {
228     display:inline-block;
229     width: 50%;
230     vertical-align: top;
231 }
232
233 .sidebyside .resizeHandle {
234     width: 5px;
235     height: 100%;
236     cursor: move;
237     position: absolute;
238     top: 0;
239     left: 50%;
240 }
241
242 .sidebyside .resizeHandle:hover {
243     background-color: grey;
244     opacity: 0.5;
245 }
246
247 .sidebyside .DiffBlockPart.remove .to,
248 .sidebyside .DiffBlockPart.add .from {
249     display: none;
250 }
251
252 .lineNumber, .expansionLineNumber {
253     border-bottom: 1px solid #998;
254     border-right: 1px solid #ddd;
255     color: #444;
256     display: inline-block;
257     padding: 1px 5px 0px 0px;
258     text-align: right;
259     vertical-align: bottom;
260     width: 3em;
261 }
262
263 .lineNumber {
264   background-color: #eed;
265 }
266
267 .expansionLineNumber {
268   background-color: #eee;
269 }
270
271 .text {
272     padding-left: 5px;
273     white-space: pre-wrap;
274     word-wrap: break-word;
275 }
276
277 .image {
278     border: 2px solid black;
279 }
280
281 .context, .context .lineNumber {
282     color: #849;
283     background-color: #fef;
284 }
285
286 .Line.add, .FileDiff .add {
287     background-color: #dfd;
288 }
289
290 .Line.add ins {
291     background-color: #9e9;
292     text-decoration: none;
293 }
294
295 .Line.remove, .FileDiff .remove {
296     background-color: #fdd;
297 }
298
299 .Line.remove del {
300     background-color: #e99;
301     text-decoration: none;
302 }
303
304 /* Support for inline comments */
305
306 .author {
307   font-style: italic;
308 }
309
310 .comment {
311   position: relative;
312 }
313
314 .comment textarea {
315   height: 6em;
316 }
317
318 .overallComments textarea {
319   height: 2em;
320   max-width: 100%;
321 }
322
323 .comment textarea, .overallComments textarea {
324   display: block;
325   width: 100%;
326 }
327
328 .overallComments .open {
329   -webkit-transition: height .2s;
330   height: 4em;
331 }
332
333 #statusBubbleContainer.wrap {
334   display: block;
335 }
336
337 body {
338   margin-bottom: 40px;
339 }
340
341 #toolbar {
342   display: -webkit-box;
343   display: -moz-box;
344   padding: 3px;
345   left: 0;
346   right: 0;
347   border: 1px solid #ddd;
348   background-color: #eee;
349   font-family: sans-serif;
350   position: fixed;
351 }
352
353 #toolbar.anchored {
354   bottom: 0;
355 }
356
357 #toolbar .actions {
358   float: right;
359 }
360
361 .winter {
362   position: fixed;
363   z-index: 5;
364   left: 0;
365   right: 0;
366   top: 0;
367   bottom: 0;
368   background-color: black;
369   opacity: 0.8;
370 }
371
372 .inactive {
373   display: none;
374 }
375
376 .lightbox {
377   position: fixed;
378   z-index: 6;
379   left: 10%;
380   right: 10%;
381   top: 10%;
382   bottom: 10%;
383   background: white;
384 }
385
386 .lightbox iframe {
387   width: 100%;
388   height: 100%;
389 }
390
391 .commentContext .lineNumber {
392   background-color: yellow;
393 }
394
395 .selected .lineNumber {
396   background-color: #69F;
397   border-bottom-color: #69F;
398   border-right-color: #69F;
399 }
400
401 .ExpandLinkContainer {
402   opacity: 0;
403   border-top: 1px solid #ddd;
404   border-bottom: 1px solid #ddd;
405 }
406
407 .ExpandArea {
408   margin: 0;
409 }
410
411 .ExpandText {
412   margin-left: 0.67em;
413 }
414
415 .LinkContainer {
416   font-family: sans-serif;
417   font-size: small;
418   font-style: normal;
419   -webkit-transition: opacity 0.5s;
420 }
421
422 .LinkContainer a {
423   border: 0;
424 }
425
426 .LinkContainer a:after {
427   content: " | ";
428   color: black;
429 }
430
431 .LinkContainer a:last-of-type:after {
432   content: "";
433 }
434
435 .help {
436  color: gray;
437  font-style: italic;
438 }
439
440 #message {
441   font-size: small;
442   font-family: sans-serif;
443 }
444
445 .commentStatus {
446   font-style: italic;
447 }
448
449 .comment, .previousComment, .frozenComment {
450   background-color: #ffd;
451 }
452
453 .overallComments {
454   -webkit-box-flex: 1;
455   -moz-box-flex: 1;
456   margin-right: 3px;
457 }
458
459 .previousComment, .frozenComment {
460   border: inset 1px;
461   padding: 5px;
462   white-space: pre-wrap;
463 }
464
465 .comment button {
466   width: 6em;
467 }
468
469 div:focus {
470   outline: 1px solid blue;
471   outline-offset: -1px;
472 }
473
474 .statusBubble {
475   /* The width/height get set to the bubble contents via postMessage on browsers that support it. */
476   width: 450px;
477   height: 20px;
478   margin: 2px 2px 0 0;
479   border: none;
480   vertical-align: middle;
481 }
482
483 .pseudo_resize_event_iframe {
484   height: 10%;
485   width: 10%;
486   position: absolute;
487   top: -11%;
488 }
489
490 .revision {
491   display: none;
492 }
493
494 .autosave-state {
495   position: absolute;
496   right: 0;
497   top: -1.3em;
498   padding: 0 3px;
499   outline: 1px solid #DDD;
500   color: #8FDF5F;
501   font-size: small;   
502   background-color: #EEE;
503 }
504
505 .autosave-state:empty {
506   outline: 0px;
507 }
508 .autosave-state.saving {
509   color: #E98080;
510 }
511
512 .clear_float {
513     clear: both;
514 }
515 </style>
516 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
517 <script src="code-review.js?version=43"></script>
518 </head>
519 EOF
520
521     def self.revisionOrDescription(string)
522         case string
523         when /\(revision \d+\)/
524             /\(revision (\d+)\)/.match(string)[1]
525         when /\(.*\)/
526             /\((.*)\)/.match(string)[1]
527         end
528     end
529
530     def self.has_image_suffix(filename)
531         filename =~ /\.(png|jpg|gif)$/
532     end
533
534     class FileDiff
535         def initialize(lines)
536             @filename = PrettyPatch.filename_from_diff_header(lines[0].chomp)
537             startOfSections = 1
538             for i in 0...lines.length
539                 case lines[i]
540                 when /^--- /
541                     @from = PrettyPatch.revisionOrDescription(lines[i])
542                 when /^\+\+\+ /
543                     @filename = PrettyPatch.filename_from_diff_header(lines[i].chomp) if @filename.nil?
544                     @to = PrettyPatch.revisionOrDescription(lines[i])
545                     startOfSections = i + 1
546                     break
547                 when BINARY_FILE_MARKER_FORMAT
548                     @binary = true
549                     if (IMAGE_FILE_MARKER_FORMAT.match(lines[i + 1]) or PrettyPatch.has_image_suffix(@filename)) then
550                         @image = true
551                         startOfSections = i + 2
552                         for x in startOfSections...lines.length
553                             # Binary diffs often have property changes listed before the actual binary data.  Skip them.
554                             if START_OF_BINARY_DATA_FORMAT.match(lines[x]) then
555                                 startOfSections = x
556                                 break
557                             end
558                         end
559                     end
560                     break
561                 when GIT_INDEX_MARKER_FORMAT
562                     @git_indexes = [$1, $2]
563                 when GIT_BINARY_FILE_MARKER_FORMAT
564                     @binary = true
565                     if (GIT_BINARY_PATCH_FORMAT.match(lines[i + 1]) and PrettyPatch.has_image_suffix(@filename)) then
566                         @git_image = true
567                         startOfSections = i + 1
568                     end
569                     break
570                 end
571             end
572             lines_with_contents = lines[startOfSections...lines.length]
573             @sections = DiffSection.parse(lines_with_contents) unless @binary
574             if @image and not lines_with_contents.empty?
575                 @image_url = "data:image/png;base64," + lines_with_contents.join
576                 @image_checksum = FileDiff.read_checksum_from_png(lines_with_contents.join.unpack("m").join)
577             elsif @git_image
578                 begin
579                     raise "index line is missing" unless @git_indexes
580
581                     chunks = nil
582                     for i in 0...lines_with_contents.length
583                         if lines_with_contents[i] =~ /^$/
584                             chunks = [lines_with_contents[i + 1 .. -1], lines_with_contents[0 .. i]]
585                             break
586                         end
587                     end
588
589                     raise "no binary chunks" unless chunks
590
591                     from_filepath = FileDiff.extract_contents_of_from_revision(@filename, chunks[0], @git_indexes[0])
592                     to_filepath = FileDiff.extract_contents_of_to_revision(@filename, chunks[1], @git_indexes[1], from_filepath, @git_indexes[0])
593                     filepaths = from_filepath, to_filepath
594
595                     binary_contents = filepaths.collect { |filepath| File.exists?(filepath) ? File.read(filepath) : nil }
596                     @image_urls = binary_contents.collect { |content| (content and not content.empty?) ? "data:image/png;base64," + [content].pack("m") : nil }
597                     @image_checksums = binary_contents.collect { |content| FileDiff.read_checksum_from_png(content) }
598                 rescue
599                     $last_prettify_part_count["extract-error"] += 1
600                     @image_error = "Exception raised during decoding git binary patch:<pre>#{CGI.escapeHTML($!.to_s + "\n" + $!.backtrace.join("\n"))}</pre>"
601                 ensure
602                     File.unlink(from_filepath) if (from_filepath and File.exists?(from_filepath))
603                     File.unlink(to_filepath) if (to_filepath and File.exists?(to_filepath))
604                 end
605             end
606             nil
607         end
608
609         def image_to_html
610             if not @image_url then
611                 return "<span class='text'>Image file removed</span>"
612             end
613
614             image_checksum = ""
615             if @image_checksum
616                 image_checksum = @image_checksum
617             elsif @filename.include? "-expected.png" and @image_url
618                 image_checksum = IMAGE_CHECKSUM_ERROR
619             end
620
621             return "<p>" + image_checksum + "</p><img class='image' src='" + @image_url + "' />"
622         end
623
624         def to_html
625             str = "<div class='FileDiff'>\n"
626             str += "<h1>#{PrettyPatch.linkifyFilename(@filename)}</h1>\n"
627             if @image then
628                 str += self.image_to_html
629             elsif @git_image then
630                 if @image_error
631                     str += @image_error
632                 else
633                     for i in (0...2)
634                         image_url = @image_urls[i]
635                         image_checksum = @image_checksums[i]
636
637                         style = ["remove", "add"][i]
638                         str += "<p class=\"#{style}\">"
639
640                         if image_checksum
641                             str += image_checksum
642                         elsif @filename.include? "-expected.png" and image_url
643                             str += IMAGE_CHECKSUM_ERROR
644                         end
645
646                         str += "<br>"
647
648                         if image_url
649                             str += "<img class='image' src='" + image_url + "' />"
650                         else
651                             str += ["</p>Added", "</p>Removed"][i]
652                         end
653                     end
654                 end
655             elsif @binary then
656                 $last_prettify_part_count["binary"] += 1
657                 str += "<span class='text'>Binary file, nothing to see here</span>"
658             else
659                 str += @sections.collect{ |section| section.to_html }.join("<br>\n") unless @sections.nil?
660             end
661
662             if @from then
663                 str += "<span class='revision'>" + @from + "</span>"
664             end
665
666             str += "</div>\n"
667         end
668
669         def self.parse(string)
670             haveSeenDiffHeader = false
671             linesForDiffs = []
672             string.each_line do |line|
673                 if (PrettyPatch.diff_header?(line))
674                     linesForDiffs << []
675                     haveSeenDiffHeader = true
676                 elsif (!haveSeenDiffHeader && line =~ /^--- /)
677                     linesForDiffs << []
678                     haveSeenDiffHeader = false
679                 end
680                 linesForDiffs.last << line unless linesForDiffs.last.nil?
681             end
682
683             linesForDiffs.collect { |lines| FileDiff.new(lines) }
684         end
685
686         def self.read_checksum_from_png(png_bytes)
687             match = png_bytes && png_bytes.match(/tEXtchecksum\0([a-fA-F0-9]{32})/)
688             match ? match[1] : nil
689         end
690
691         def self.git_new_file_binary_patch(filename, encoded_chunk, git_index)
692             return <<END
693 diff --git a/#{filename} b/#{filename}
694 new file mode 100644
695 index 0000000000000000000000000000000000000000..#{git_index}
696 GIT binary patch
697 #{encoded_chunk.join("")}literal 0
698 HcmV?d00001
699
700 END
701         end
702
703         def self.git_changed_file_binary_patch(to_filename, from_filename, encoded_chunk, to_git_index, from_git_index)
704             return <<END
705 diff --git a/#{from_filename} b/#{to_filename}
706 copy from #{from_filename}
707 +++ b/#{to_filename}
708 index #{from_git_index}..#{to_git_index}
709 GIT binary patch
710 #{encoded_chunk.join("")}literal 0
711 HcmV?d00001
712
713 END
714         end
715
716         def self.get_svn_uri(repository_path)
717             "http://svn.webkit.org/repository/webkit/!svn/bc/" + $svn_revision.to_s + "/trunk/" + (repository_path)
718         end
719
720         def self.get_new_temp_filepath_and_name
721             tempfile = Tempfile.new("PrettyPatch")
722             filepath = tempfile.path + '.bin'
723             filename = File.basename(filepath)
724             return filepath, filename
725         end
726
727         def self.download_from_revision_from_svn(repository_path)
728             filepath, filename = get_new_temp_filepath_and_name
729             svn_uri = get_svn_uri(repository_path)
730             open(filepath, 'wb') do |to_file|
731                 to_file << open(svn_uri) { |from_file| from_file.read }
732             end
733             return filepath
734         end
735
736         def self.run_git_apply_on_patch(output_filepath, patch)
737             # Apply the git binary patch using git-apply.
738             cmd = GIT_PATH + " apply --directory=" + File.dirname(output_filepath)
739             stdin, stdout, stderr = *Open3.popen3(cmd)
740             begin
741                 stdin.puts(patch)
742                 stdin.close
743
744                 error = stderr.read
745                 if error != ""
746                     error = "Error running " + cmd + "\n" + "with patch:\n" + patch[0..500] + "...\n" + error
747                 end
748                 raise error if error != ""
749             ensure
750                 stdin.close unless stdin.closed?
751                 stdout.close
752                 stderr.close
753             end
754         end
755
756         def self.extract_contents_from_git_binary_literal_chunk(encoded_chunk, git_index)
757             filepath, filename = get_new_temp_filepath_and_name
758             patch = FileDiff.git_new_file_binary_patch(filename, encoded_chunk, git_index)
759             run_git_apply_on_patch(filepath, patch)
760             return filepath
761         end
762
763         def self.extract_contents_from_git_binary_delta_chunk(from_filepath, from_git_index, encoded_chunk, to_git_index)
764             to_filepath, to_filename = get_new_temp_filepath_and_name
765             from_filename = File.basename(from_filepath)
766             patch = FileDiff.git_changed_file_binary_patch(to_filename, from_filename, encoded_chunk, to_git_index, from_git_index)
767             run_git_apply_on_patch(to_filepath, patch)
768             return to_filepath
769         end
770
771         def self.extract_contents_of_from_revision(repository_path, encoded_chunk, git_index)
772             # For literal encoded, simply reconstruct.
773             if GIT_LITERAL_FORMAT.match(encoded_chunk[0])
774                 return extract_contents_from_git_binary_literal_chunk(encoded_chunk, git_index)
775             end
776             #  For delta encoded, download from svn.
777             if GIT_DELTA_FORMAT.match(encoded_chunk[0])
778                 return download_from_revision_from_svn(repository_path)
779             end
780             raise "Error: unknown git patch encoding"
781         end
782
783         def self.extract_contents_of_to_revision(repository_path, encoded_chunk, git_index, from_filepath, from_git_index)
784             # For literal encoded, simply reconstruct.
785             if GIT_LITERAL_FORMAT.match(encoded_chunk[0])
786                 return extract_contents_from_git_binary_literal_chunk(encoded_chunk, git_index)
787             end
788             # For delta encoded, reconstruct using delta and previously constructed 'from' revision.
789             if GIT_DELTA_FORMAT.match(encoded_chunk[0])
790                 return extract_contents_from_git_binary_delta_chunk(from_filepath, from_git_index, encoded_chunk, git_index)
791             end
792             raise "Error: unknown git patch encoding"
793         end
794     end
795
796     class DiffBlock
797         attr_accessor :parts
798
799         def initialize(container)
800             @parts = []
801             container << self
802         end
803
804         def to_html
805             str = "<div class='DiffBlock'>\n"
806             str += @parts.collect{ |part| part.to_html }.join
807             str += "<div class='clear_float'></div></div>\n"
808         end
809     end
810
811     class DiffBlockPart
812         attr_reader :className
813         attr :lines
814
815         def initialize(className, container)
816             $last_prettify_part_count[className] += 1
817             @className = className
818             @lines = []
819             container.parts << self
820         end
821
822         def to_html
823             str = "<div class='DiffBlockPart %s'>\n" % @className
824             str += @lines.collect{ |line| line.to_html }.join
825             # Don't put white-space after this so adjacent inline-block DiffBlockParts will not wrap.
826             str += "</div>"
827         end
828     end
829
830     class DiffSection
831         def initialize(lines)
832             lines.length >= 1 or raise "DiffSection.parse only received %d lines" % lines.length
833
834             matches = START_OF_SECTION_FORMAT.match(lines[0])
835
836             if matches
837                 from, to = [matches[1].to_i, matches[3].to_i]
838                 if matches[2] and matches[4]
839                     from_end = from + matches[2].to_i
840                     to_end = to + matches[4].to_i
841                 end
842             end
843
844             @blocks = []
845             diff_block = nil
846             diff_block_part = nil
847
848             for line in lines[1...lines.length]
849                 startOfLine = line =~ /^[-\+ ]/ ? 1 : 0
850                 text = line[startOfLine...line.length].chomp
851                 case line[0]
852                 when ?-
853                     if (diff_block_part.nil? or diff_block_part.className != 'remove')
854                         diff_block = DiffBlock.new(@blocks)
855                         diff_block_part = DiffBlockPart.new('remove', diff_block)
856                     end
857
858                     diff_block_part.lines << CodeLine.new(from, nil, text)
859                     from += 1 unless from.nil?
860                 when ?+
861                     if (diff_block_part.nil? or diff_block_part.className != 'add')
862                         # Put add lines that immediately follow remove lines into the same DiffBlock.
863                         if (diff_block.nil? or diff_block_part.className != 'remove')
864                             diff_block = DiffBlock.new(@blocks)
865                         end
866
867                         diff_block_part = DiffBlockPart.new('add', diff_block)
868                     end
869
870                     diff_block_part.lines << CodeLine.new(nil, to, text)
871                     to += 1 unless to.nil?
872                 else
873                     if (diff_block_part.nil? or diff_block_part.className != 'shared')
874                         diff_block = DiffBlock.new(@blocks)
875                         diff_block_part = DiffBlockPart.new('shared', diff_block)
876                     end
877
878                     diff_block_part.lines << CodeLine.new(from, to, text)
879                     from += 1 unless from.nil?
880                     to += 1 unless to.nil?
881                 end
882
883                 break if from_end and to_end and from == from_end and to == to_end
884             end
885
886             changes = [ [ [], [] ] ]
887             for block in @blocks
888                 for block_part in block.parts
889                     for line in block_part.lines
890                         if (!line.fromLineNumber.nil? and !line.toLineNumber.nil?) then
891                             changes << [ [], [] ]
892                             next
893                         end
894                         changes.last.first << line if line.toLineNumber.nil?
895                         changes.last.last << line if line.fromLineNumber.nil?
896                     end
897                 end
898             end
899
900             for change in changes
901                 next unless change.first.length == change.last.length
902                 for i in (0...change.first.length)
903                     from_text = change.first[i].text
904                     to_text = change.last[i].text
905                     next if from_text.length > MAXIMUM_INTRALINE_DIFF_LINE_LENGTH or to_text.length > MAXIMUM_INTRALINE_DIFF_LINE_LENGTH
906                     raw_operations = HTMLDiff::DiffBuilder.new(from_text, to_text).operations
907                     operations = []
908                     back = 0
909                     raw_operations.each_with_index do |operation, j|
910                         if operation.action == :equal and j < raw_operations.length - 1
911                            length = operation.end_in_new - operation.start_in_new
912                            if length < SMALLEST_EQUAL_OPERATION
913                                back = length
914                                next
915                            end
916                         end
917                         operation.start_in_old -= back
918                         operation.start_in_new -= back
919                         back = 0
920                         operations << operation
921                     end
922                     change.first[i].operations = operations
923                     change.last[i].operations = operations
924                 end
925             end
926
927             @blocks.unshift(ContextLine.new(matches[5])) unless matches.nil? || matches[5].empty?
928         end
929
930         def to_html
931             str = "<div class='DiffSection'>\n"
932             str += @blocks.collect{ |block| block.to_html }.join
933             str += "</div>\n"
934         end
935
936         def self.parse(lines)
937             linesForSections = lines.inject([[]]) do |sections, line|
938                 sections << [] if line =~ /^@@/
939                 sections.last << line
940                 sections
941             end
942
943             linesForSections.delete_if { |lines| lines.nil? or lines.empty? }
944             linesForSections.collect { |lines| DiffSection.new(lines) }
945         end
946     end
947
948     class Line
949         attr_reader :fromLineNumber
950         attr_reader :toLineNumber
951         attr_reader :text
952
953         def initialize(from, to, text)
954             @fromLineNumber = from
955             @toLineNumber = to
956             @text = text
957         end
958
959         def text_as_html
960             CGI.escapeHTML(text)
961         end
962
963         def classes
964             lineClasses = ["Line", "LineContainer"]
965             lineClasses << ["add"] unless @toLineNumber.nil? or !@fromLineNumber.nil?
966             lineClasses << ["remove"] unless @fromLineNumber.nil? or !@toLineNumber.nil?
967             lineClasses
968         end
969
970         def to_html
971             markedUpText = self.text_as_html
972             str = "<div class='%s'>\n" % self.classes.join(' ')
973             str += "<span class='from lineNumber'>%s</span><span class='to lineNumber'>%s</span>" %
974                    [@fromLineNumber.nil? ? '&nbsp;' : @fromLineNumber,
975                     @toLineNumber.nil? ? '&nbsp;' : @toLineNumber] unless @fromLineNumber.nil? and @toLineNumber.nil?
976             str += "<span class='text'>%s</span>\n" % markedUpText
977             str += "</div>\n"
978         end
979     end
980
981     class CodeLine < Line
982         attr :operations, true
983
984         def text_as_html
985             html = []
986             tag = @fromLineNumber.nil? ? "ins" : "del"
987             if @operations.nil? or @operations.empty?
988                 return CGI.escapeHTML(@text)
989             end
990             @operations.each do |operation|
991                 start = @fromLineNumber.nil? ? operation.start_in_new : operation.start_in_old
992                 eend = @fromLineNumber.nil? ? operation.end_in_new : operation.end_in_old
993                 escaped_text = CGI.escapeHTML(@text[start...eend])
994                 if eend - start === 0 or operation.action === :equal
995                     html << escaped_text
996                 else
997                     html << "<#{tag}>#{escaped_text}</#{tag}>"
998                 end
999             end
1000             html.join
1001         end
1002     end
1003
1004     class ContextLine < Line
1005         def initialize(context)
1006             super("@", "@", context)
1007         end
1008
1009         def classes
1010             super << "context"
1011         end
1012     end
1013 end