14 def self.prettify(string)
15 fileDiffs = FileDiff.parse(string)
18 str += fileDiffs.collect{ |diff| diff.to_html }.join
21 def self.filename_from_diff_header(line)
22 DIFF_HEADER_FORMATS.each do |format|
23 match = format.match(line)
24 return match[1] unless match.nil?
29 def self.diff_header?(line)
30 RELAXED_DIFF_HEADER_FORMATS.any? { |format| line =~ format }
34 DIFF_HEADER_FORMATS = [
36 /^diff --git "?a\/.+"? "?b\/(.+)"?\r?$/,
37 /^\+\+\+ ([^\t]+)(\t.*)?\r?$/
40 RELAXED_DIFF_HEADER_FORMATS = [
45 BINARY_FILE_MARKER_FORMAT = /^Cannot display: file marked as a binary type.$/
47 IMAGE_FILE_MARKER_FORMAT = /^svn:mime-type = image\/png$/
49 GIT_INDEX_MARKER_FORMAT = /^index ([0-9a-f]{40})\.\.([0-9a-f]{40})/
51 GIT_BINARY_FILE_MARKER_FORMAT = /^GIT binary patch$/
53 GIT_LITERAL_FORMAT = /^literal \d+$/
55 START_OF_BINARY_DATA_FORMAT = /^[0-9a-zA-Z\+\/=]{20,}/ # Assume 20 chars without a space is base64 binary data.
57 START_OF_SECTION_FORMAT = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@\s*(.*)/
59 START_OF_EXTENT_STRING = "%c" % 0
60 END_OF_EXTENT_STRING = "%c" % 1
62 SMALLEST_EQUAL_OPERATION = 3
64 OPENSOURCE_TRAC_URL = "http://trac.webkit.org/"
66 OPENSOURCE_DIRS = Set.new %w[
77 def self.find_url_and_path(file_path)
78 # Search file_path from the bottom up, at each level checking whether
79 # we've found a directory we know exists in the source tree.
81 dirname, basename = File.split(file_path)
82 dirname.split(/\//).reverse.inject(basename) do |path, directory|
83 path = directory + "/" + path
85 return [OPENSOURCE_TRAC_URL, path] if OPENSOURCE_DIRS.include?(directory)
93 def self.linkifyFilename(filename)
94 url, pathBeneathTrunk = find_url_and_path(filename)
96 url.nil? ? filename : "<a href='#{url}browser/trunk/#{pathBeneathTrunk}'>#{filename}</a>"
103 text-decoration: none;
104 border-bottom: 1px dotted;
112 background-color: #f8f8f8;
113 border: 1px solid #ddd;
114 font-family: monospace;
120 font-family: sans-serif;
128 h1 :link, h1 :visited {
134 background-color: #eee;
141 .FileDiffLinkContainer {
144 padding-right: 0.5em;
149 background-color: white;
151 border-width: 1px 0px;
154 .ExpansionLine, .LineContainer {
158 .sidebyside .DiffBlockPart.add:first-child {
163 .sidebyside .DiffBlockPart.remove,
164 .sidebyside .DiffBlockPart.add {
165 display:inline-block;
170 .sidebyside .DiffBlockPart.remove .to,
171 .sidebyside .DiffBlockPart.add .from {
175 .lineNumber, .expansionLineNumber {
176 border-bottom: 1px solid #998;
177 border-right: 1px solid #ddd;
179 display: inline-block;
180 padding: 1px 5px 0px 0px;
182 vertical-align: bottom;
187 background-color: #eed;
190 .expansionLineNumber {
191 background-color: #eee;
196 white-space: pre-wrap;
197 word-wrap: break-word;
201 border: 2px solid black;
204 .context, .context .lineNumber {
206 background-color: #fef;
210 background-color: #dfd;
214 background-color: #9e9;
215 text-decoration: none;
219 background-color: #fdd;
223 background-color: #e99;
224 text-decoration: none;
227 /* Support for inline comments */
241 .overallComments textarea {
245 .comment textarea, .overallComments textarea {
250 .overallComments .open {
251 -webkit-transition: height .2s;
255 #statusBubbleContainer.wrap {
264 display: -webkit-box;
270 border: 1px solid #ddd;
271 background-color: #eee;
272 font-family: sans-serif;
290 background-color: black;
312 .commentContext .lineNumber {
313 background-color: yellow;
316 .selected .lineNumber {
317 background-color: #69F;
318 border-bottom-color: #69F;
319 border-right-color: #69F;
322 .ExpandLinkContainer {
324 border-top: 1px solid #ddd;
325 border-bottom: 1px solid #ddd;
337 font-family: sans-serif;
340 -webkit-transition: opacity 0.5s;
347 .LinkContainer a:after {
352 .LinkContainer a:last-of-type:after {
363 font-family: sans-serif;
370 .comment, .previousComment, .frozenComment {
371 background-color: #ffd;
380 .previousComment, .frozenComment {
383 white-space: pre-wrap;
391 outline: 1px solid blue;
392 outline-offset: -1px;
396 /* The width/height get set to the bubble contents via postMessage on browsers that support it. */
401 vertical-align: middle;
404 .pseudo_resize_event_iframe {
415 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
416 <script src="code-review.js?version=25"></script>
419 def self.revisionOrDescription(string)
421 when /\(revision \d+\)/
422 /\(revision (\d+)\)/.match(string)[1]
424 /\((.*)\)/.match(string)[1]
428 def self.has_image_suffix(filename)
429 filename =~ /\.(png|jpg|gif)$/
433 def initialize(lines)
434 @filename = PrettyPatch.filename_from_diff_header(lines[0].chomp)
436 for i in 0...lines.length
439 @from = PrettyPatch.revisionOrDescription(lines[i])
441 @filename = PrettyPatch.filename_from_diff_header(lines[i].chomp) if @filename.nil?
442 @to = PrettyPatch.revisionOrDescription(lines[i])
443 startOfSections = i + 1
445 when BINARY_FILE_MARKER_FORMAT
447 if (IMAGE_FILE_MARKER_FORMAT.match(lines[i + 1]) or PrettyPatch.has_image_suffix(@filename)) then
449 startOfSections = i + 2
450 for x in startOfSections...lines.length
451 # Binary diffs often have property changes listed before the actual binary data. Skip them.
452 if START_OF_BINARY_DATA_FORMAT.match(lines[x]) then
459 when GIT_INDEX_MARKER_FORMAT
460 @git_indexes = [$1, $2]
461 when GIT_BINARY_FILE_MARKER_FORMAT
463 if (GIT_LITERAL_FORMAT.match(lines[i + 1]) and PrettyPatch.has_image_suffix(@filename)) then
465 startOfSections = i + 1
470 lines_with_contents = lines[startOfSections...lines.length]
471 @sections = DiffSection.parse(lines_with_contents) unless @binary
473 @image_url = "data:image/png;base64," + lines_with_contents.join
476 raise "index line is missing" unless @git_indexes
479 for i in 0...lines_with_contents.length
480 if lines_with_contents[i] =~ /^$/
481 chunks = [lines_with_contents[i + 1 .. -1], lines_with_contents[0 .. i]]
486 raise "no binary chunks" unless chunks
488 @image_urls = chunks.zip(@git_indexes).collect do |chunk, git_index|
489 FileDiff.extract_contents_from_git_binary_chunk(chunk, git_index)
492 @image_error = "Exception raised during decoding git binary patch:<pre>#{CGI.escapeHTML($!.to_s + "\n" + $!.backtrace.join("\n"))}</pre>"
499 str = "<div class='FileDiff'>\n"
500 str += "<h1>#{PrettyPatch.linkifyFilename(@filename)}</h1>\n"
502 str += "<img class='image' src='" + @image_url + "' />"
503 elsif @git_image then
508 image_url = @image_urls[i]
509 style = ["remove", "add"][i]
510 str += "<p class=\"#{style}\">"
512 str += "<img class='image' src='" + image_url + "' />"
514 str += ["Added", "Removed"][i]
519 str += "<span class='text'>Binary file, nothing to see here</span>"
521 str += @sections.collect{ |section| section.to_html }.join("<br>\n") unless @sections.nil?
525 str += "<span class='revision'>" + @from + "</span>"
531 def self.parse(string)
532 haveSeenDiffHeader = false
534 string.each_line do |line|
535 if (PrettyPatch.diff_header?(line))
537 haveSeenDiffHeader = true
538 elsif (!haveSeenDiffHeader && line =~ /^--- /)
540 haveSeenDiffHeader = false
542 linesForDiffs.last << line unless linesForDiffs.last.nil?
545 linesForDiffs.collect { |lines| FileDiff.new(lines) }
548 def self.git_new_file_binary_patch(filename, encoded_chunk, git_index)
550 diff --git a/#{filename} b/#{filename}
552 index 0000000000000000000000000000000000000000..#{git_index}
554 #{encoded_chunk.join("")}literal 0
560 def self.extract_contents_from_git_binary_chunk(encoded_chunk, git_index)
561 # We use Tempfile we need a unique file among processes.
562 tempfile = Tempfile.new("PrettyPatch")
563 # We need a filename which doesn't exist to apply a patch
564 # which creates a new file. Append a suffix so filename
566 filepath = tempfile.path + '.bin'
567 filename = File.basename(filepath)
569 patch = FileDiff.git_new_file_binary_patch(filename, encoded_chunk, git_index)
571 # Apply the git binary patch using git-apply.
572 cmd = GIT_PATH + " apply --directory=" + File.dirname(filepath)
573 stdin, stdout, stderr = *Open3.popen3(cmd)
579 raise error if error != ""
581 contents = File.read(filepath)
583 stdin.close unless stdin.closed?
586 File.unlink(filename) if File.exists?(filename)
589 return nil if contents.empty?
590 return "data:image/png;base64," + [contents].pack("m")
597 def initialize(container)
603 str = "<div class='DiffBlock'>\n"
604 str += @parts.collect{ |part| part.to_html }.join
605 str += "<div class='clear_float'></div></div>\n"
610 attr_reader :className
613 def initialize(className, container)
614 @className = className
616 container.parts << self
620 str = "<div class='DiffBlockPart %s'>\n" % @className
621 str += @lines.collect{ |line| line.to_html }.join
622 # Don't put white-space after this so adjacent inline-block DiffBlockParts will not wrap.
628 def initialize(lines)
629 lines.length >= 1 or raise "DiffSection.parse only received %d lines" % lines.length
631 matches = START_OF_SECTION_FORMAT.match(lines[0])
632 from, to = [matches[1].to_i, matches[2].to_i] unless matches.nil?
636 diff_block_part = nil
638 for line in lines[1...lines.length]
639 startOfLine = line =~ /^[-\+ ]/ ? 1 : 0
640 text = line[startOfLine...line.length].chomp
643 if (diff_block_part.nil? or diff_block_part.className != 'remove')
644 diff_block = DiffBlock.new(@blocks)
645 diff_block_part = DiffBlockPart.new('remove', diff_block)
648 diff_block_part.lines << CodeLine.new(from, nil, text)
649 from += 1 unless from.nil?
651 if (diff_block_part.nil? or diff_block_part.className != 'add')
652 # Put add lines that immediately follow remove lines into the same DiffBlock.
653 if (diff_block.nil? or diff_block_part.className != 'remove')
654 diff_block = DiffBlock.new(@blocks)
657 diff_block_part = DiffBlockPart.new('add', diff_block)
660 diff_block_part.lines << CodeLine.new(nil, to, text)
661 to += 1 unless to.nil?
663 if (diff_block_part.nil? or diff_block_part.className != 'shared')
664 diff_block = DiffBlock.new(@blocks)
665 diff_block_part = DiffBlockPart.new('shared', diff_block)
668 diff_block_part.lines << CodeLine.new(from, to, text)
669 from += 1 unless from.nil?
670 to += 1 unless to.nil?
674 changes = [ [ [], [] ] ]
676 for block_part in block.parts
677 for line in block_part.lines
678 if (!line.fromLineNumber.nil? and !line.toLineNumber.nil?) then
679 changes << [ [], [] ]
682 changes.last.first << line if line.toLineNumber.nil?
683 changes.last.last << line if line.fromLineNumber.nil?
688 for change in changes
689 next unless change.first.length == change.last.length
690 for i in (0...change.first.length)
691 raw_operations = HTMLDiff::DiffBuilder.new(change.first[i].text, change.last[i].text).operations
694 raw_operations.each_with_index do |operation, j|
695 if operation.action == :equal and j < raw_operations.length - 1
696 length = operation.end_in_new - operation.start_in_new
697 if length < SMALLEST_EQUAL_OPERATION
702 operation.start_in_old -= back
703 operation.start_in_new -= back
705 operations << operation
707 change.first[i].operations = operations
708 change.last[i].operations = operations
712 @blocks.unshift(ContextLine.new(matches[3])) unless matches.nil? || matches[3].empty?
716 str = "<div class='DiffSection'>\n"
717 str += @blocks.collect{ |block| block.to_html }.join
721 def self.parse(lines)
722 linesForSections = lines.inject([[]]) do |sections, line|
723 sections << [] if line =~ /^@@/
724 sections.last << line
728 linesForSections.delete_if { |lines| lines.nil? or lines.empty? }
729 linesForSections.collect { |lines| DiffSection.new(lines) }
734 attr_reader :fromLineNumber
735 attr_reader :toLineNumber
738 def initialize(from, to, text)
739 @fromLineNumber = from
749 lineClasses = ["Line", "LineContainer"]
750 lineClasses << ["add"] unless @toLineNumber.nil? or !@fromLineNumber.nil?
751 lineClasses << ["remove"] unless @fromLineNumber.nil? or !@toLineNumber.nil?
756 markedUpText = self.text_as_html
757 str = "<div class='%s'>\n" % self.classes.join(' ')
758 str += "<span class='from lineNumber'>%s</span><span class='to lineNumber'>%s</span>\n" %
759 [@fromLineNumber.nil? ? ' ' : @fromLineNumber,
760 @toLineNumber.nil? ? ' ' : @toLineNumber] unless @fromLineNumber.nil? and @toLineNumber.nil?
761 str += "<span class='text'>%s</span>\n" % markedUpText
766 class CodeLine < Line
767 attr :operations, true
771 tag = @fromLineNumber.nil? ? "ins" : "del"
772 if @operations.nil? or @operations.empty?
773 return CGI.escapeHTML(@text)
775 @operations.each do |operation|
776 start = @fromLineNumber.nil? ? operation.start_in_new : operation.start_in_old
777 eend = @fromLineNumber.nil? ? operation.end_in_new : operation.end_in_old
778 escaped_text = CGI.escapeHTML(@text[start...eend])
779 if eend - start === 0 or operation.action === :equal
782 html << "<#{tag}>#{escaped_text}</#{tag}>"
789 class ContextLine < Line
790 def initialize(context)
791 super("@", "@", context)