HTML diff from I2 - works better than the original

This commit is contained in:
Alexey Verkhovsky 2005-11-14 10:13:18 +00:00
parent 0b1a80a852
commit 8f33b8e549

View file

@ -32,27 +32,101 @@ module Enumerable
end end
end end
class Object
def nil_or_empty?
nil? or empty?
end
end
module Diff module Diff
module Utilities
def explode(sequence)
sequence.is_a?(String) ? sequence.split(//) : sequence
end
def newline?(char)
%W(\n \r).include? char
end
def tab?(char)
"\t" == char
end
# XXX Could be more robust but unrecognized tags cause an infinite loop so
# better to be permissive
def open_tag?(char)
char =~ /\A<[^>]+>/
end
# See comment for open_tag?
def close_tag?(char)
char =~ %r!\A</[^>]+>!
end
def end_of_tag?(char)
char == '>'
end
def start_of_tag?(char)
char == '<'
end
def html2list(x, use_brackets = false)
mode = :char
cur = ''
out = []
explode(x).each do |char|
case mode
when :tag
if end_of_tag? char
cur += use_brackets ? ']' : '>'
out.push cur
cur, mode = '', :char
else
cur += char
end
when :char
if start_of_tag? char
out.push cur
cur = use_brackets ? '[' : '<'
mode = :tag
elsif /\s/.match char
out.push cur + char
cur = ''
else
cur += char
end
end
end
out.push(cur)
out.delete ''
out.map {|elt| newline?(elt) ? elt : elt.chomp}
end
end
class SequenceMatcher class SequenceMatcher
include Utilities
def initialize(a = [''], b = [''], isjunk = nil, byline = false) def initialize(a = [''], b = [''], isjunk = nil, byline = false)
a = (!byline and a.kind_of? String) ? a.split(//) : a a, b = explode(a), explode(b) unless byline
b = (!byline and b.kind_of? String) ? b.split(//) : b @isjunk = isjunk || Proc.new {}
@isjunk = isjunk || proc {} set_sequences a, b
set_seqs a, b
end end
def set_seqs(a, b) def set_sequences(a, b)
set_seq_a a set_sequence_a a
set_seq_b b set_sequence_b b
end end
def set_seq_a(a) def set_sequence_a(a)
@a = a @a = a
@matching_blocks = @opcodes = nil @matching_blocks = @opcodes = nil
end end
def set_seq_b(b) def set_sequence_b(b)
@b = b @b = b
@matching_blocks = @opcodes = nil @matching_blocks = @opcodes = nil
chain_b chain_b
@ -64,24 +138,22 @@ module Diff
pophash = {} pophash = {}
junkdict = {} junkdict = {}
@b.each_with_index do |elt, i| @b.each_with_index do |elt, idx|
if @b2j.has_key? elt if @b2j.has_key? elt
indices = @b2j[elt] indices = @b2j[elt]
if @b.length >= 200 and indices.length * 100 > @b.length if @b.length >= 200 and indices.length * 100 > @b.length
pophash[elt] = 1 pophash[elt] = 1
indices.clear indices.clear
else else
indices.push i indices.push idx
end end
else else
@b2j[elt] = [i] @b2j[elt] = [idx]
end end
end end
pophash.each_key { |elt| @b2j.delete elt } pophash.each_key { |elt| @b2j.delete elt }
junkdict = {}
unless @isjunk.nil? unless @isjunk.nil?
[pophash, @b2j].each do |d| [pophash, @b2j].each do |d|
d.each_key do |elt| d.each_key do |elt|
@ -97,20 +169,16 @@ module Diff
@isbpopular = junkdict.method(:has_key?) @isbpopular = junkdict.method(:has_key?)
end end
def find_longest_match(alo, ahi, blo, bhi) def find_longest_match(a_low, a_high, b_low, b_high)
besti, bestj, bestsize = alo, blo, 0 besti, bestj, bestsize = a_low, b_low, 0
j2len = {} j2len = {}
(alo..ahi).step do |i| (a_low..a_high).step do |i|
newj2len = {} newj2len = {}
(@b2j[@a[i]] || []).each do |j| (@b2j[@a[i]] || []).each do |j|
if j < blo next if j < b_low
next break if j >= b_high
end
if j >= bhi
break
end
k = newj2len[j] = (j2len[j - 1] || 0) + 1 k = newj2len[j] = (j2len[j - 1] || 0) + 1
if k > bestsize if k > bestsize
@ -120,26 +188,21 @@ module Diff
j2len = newj2len j2len = newj2len
end end
while besti > alo and bestj > blo and while besti > a_low and bestj > b_low and not @isbjunk.call(@b[bestj - 1]) and @a[besti - 1] == @b[bestj - 1]
not @isbjunk.call(@b[bestj-1]) and
@a[besti-1] == @b[bestj-1]
besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1 besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1
end end
while besti+bestsize < ahi and bestj+bestsize < bhi and while besti + bestsize < a_high and bestj + bestsize < b_high and
not @isbjunk.call(@b[bestj + bestsize]) and not @isbjunk.call(@b[bestj + bestsize]) and
@a[besti + bestsize] == @b[bestj + bestsize] @a[besti + bestsize] == @b[bestj + bestsize]
bestsize += 1 bestsize += 1
end end
while besti > alo and bestj > blo and while besti > a_low and bestj > b_low and @isbjunk.call(@b[bestj - 1]) and @a[besti - 1] == @b[bestj - 1]
@isbjunk.call(@b[bestj-1]) and
@a[besti-1] == @b[bestj-1]
besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1 besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1
end end
while besti+bestsize < ahi and bestj+bestsize < bhi and while besti + bestsize < a_high and bestj + bestsize < b_high and @isbjunk.call(@b[bestj+bestsize]) and
@isbjunk.call(@b[bestj+bestsize]) and
@a[besti+bestsize] == @b[bestj+bestsize] @a[besti+bestsize] == @b[bestj+bestsize]
bestsize += 1 bestsize += 1
end end
@ -148,32 +211,27 @@ module Diff
end end
def get_matching_blocks def get_matching_blocks
return @matching_blocks unless @matching_blocks.nil? or return @matching_blocks unless @matching_blocks.nil_or_empty?
@matching_blocks.empty?
@matching_blocks = [] @matching_blocks = []
la, lb = @a.length, @b.length size_of_a, size_of_b = @a.size, @b.size
match_block_helper(0, la, 0, lb, @matching_blocks) match_block_helper(0, size_of_a, 0, size_of_b, @matching_blocks)
@matching_blocks.push [la, lb, 0] @matching_blocks.push [size_of_a, size_of_b, 0]
end end
def match_block_helper(alo, ahi, blo, bhi, answer) def match_block_helper(a_low, a_high, b_low, b_high, answer)
i, j, k = x = find_longest_match(alo, ahi, blo, bhi) i, j, k = x = find_longest_match(a_low, a_high, b_low, b_high)
if not k.zero? unless k.zero?
if alo < i and blo < j match_block_helper(a_low, i, b_low, j, answer) if a_low < i and b_low < j
match_block_helper(alo, i, blo, j, answer)
end
answer.push x answer.push x
if i + k < ahi and j + k < bhi if i + k < a_high and j + k < b_high
match_block_helper(i + k, ahi, j + k, bhi, answer) match_block_helper(i + k, a_high, j + k, b_high, answer)
end end
end end
end end
def get_opcodes def get_opcodes
unless @opcodes.nil? or @opcodes.empty? return @opcodes unless @opcodes.nil_or_empty?
return @opcodes
end
i = j = 0 i = j = 0
@opcodes = answer = [] @opcodes = answer = []
@ -187,27 +245,25 @@ module Diff
end end
answer.push [tag, i, ai, j, bj] if tag answer.push [tag, i, ai, j, bj] if tag
i, j = ai + size, bj + size i, j = ai + size, bj + size
answer.push [:equal, ai, i, bj, j] unless size.zero? answer.push [:equal, ai, i, bj, j] unless size.zero?
end end
return answer answer
end end
# XXX: untested # XXX: untested
def get_grouped_opcodes(n = 3) def get_grouped_opcodes(n = 3)
codes = get_opcodes codes = get_opcodes
if codes[0][0] == :equal if codes.first.first == :equal
tag, i1, i2, j1, j2 = codes[0] tag, i1, i2, j1, j2 = codes.first
codes[0] = tag, [i1, i2 - n].max, i2, [j1, j2-n].max, j2 codes[0] = tag, [i1, i2 - n].max, i2, [j1, j2-n].max, j2
end end
if codes[-1][0] == :equal if codes.last.first == :equal
tag, i1, i2, j1, j2 = codes[-1] tag, i1, i2, j1, j2 = codes.last
codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n) codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
end end
nn = n + n nn = n + n
group = [] group = []
codes.each do |tag, i1, i2, j1, j2| codes.each do |tag, i1, i2, j1, j2|
@ -219,20 +275,18 @@ module Diff
group.push [tag, i1, i2, j1 ,j2] group.push [tag, i1, i2, j1 ,j2]
end end
end end
if group and group.length != 1 and group[0][0] == :equal yield group if group and group.size != 1 and group.first.first == :equal
yield group
end
end end
def ratio def ratio
matches = get_matching_blocks.reduce(0) do |sum, triple| matches = get_matching_blocks.reduce(0) do |sum, triple|
sum + triple[-1] sum + triple.last
end end
Diff.calculate_ratio(matches, @a.length + @b.length) Diff.calculate_ratio(matches, @a.size + @b.size)
end end
def quick_ratio def quick_ratio
if @fullbcount.nil? or @fullbcount.empty? if @fullbcount.nil_or_empty?
@fullbcount = {} @fullbcount = {}
@b.each do |elt| @b.each do |elt|
@fullbcount[elt] = (@fullbcount[elt] || 0) + 1 @fullbcount[elt] = (@fullbcount[elt] || 0) + 1
@ -242,203 +296,163 @@ module Diff
avail = {} avail = {}
matches = 0 matches = 0
@a.each do |elt| @a.each do |elt|
if avail.has_key? elt numb = avail.has_key?(elt) ? avail[elt] : (@fullbcount[elt] || 0)
numb = avail[elt]
else
numb = @fullbcount[elt] || 0
end
avail[elt] = numb - 1 avail[elt] = numb - 1
if numb > 0 matches += 1 if numb > 0
matches += 1
end end
end Diff.calculate_ratio matches, @a.size + @b.size
Diff.calculate_ratio matches, @a.length + @b.length
end end
def real_quick_ratio def real_quick_ratio
la, lb = @a.length, @b.length size_of_a, size_of_b = @a.size, @b.size
Diff.calculate_ratio([la, lb].min, la + lb) Diff.calculate_ratio([size_of_a, size_of_b].min, size_of_a + size_of_b)
end end
protected :chain_b, :match_block_helper protected :chain_b, :match_block_helper
end # end class SequenceMatcher end # end class SequenceMatcher
def self.calculate_ratio(matches, length) class << self
def calculate_ratio(matches, length)
return 1.0 if length.zero? return 1.0 if length.zero?
2.0 * matches / length 2.0 * matches / length
end end
# XXX: untested # XXX: untested
def self.get_close_matches(word, possibilities, n=3, cutoff=0.6) def get_close_matches(word, possibilities, n = 3, cutoff = 0.6)
unless n > 0 raise "n must be > 0: #{n}" unless n > 0
raise "n must be > 0: #{n}" raise "cutoff must be in (0.0..1.0): #{cutoff}" unless cutoff.between 0.0..1.0
end
unless 0.0 <= cutoff and cutoff <= 1.0
raise "cutoff must be in (0.0..1.0): #{cutoff}"
end
result = [] result = []
s = SequenceMatcher.new sequence_matcher = Diff::SequenceMatcher.new
s.set_seq_b word sequence_matcher.set_sequence_b word
possibilities.each do |x| possibilities.each do |possibility|
s.set_seq_a x sequence_matcher.set_sequence_a possibility
if s.real_quick_ratio >= cutoff and if sequence_matcher.real_quick_ratio >= cutoff and
s.quick_ratio >= cutoff and sequence_matcher.quick_ratio >= cutoff and
s.ratio >= cutoff sequence_matcher.ratio >= cutoff
result.push [s.ratio, x] result.push [sequence_matcher.ratio, possibility]
end end
end end
unless result.nil? or result.empty? unless result.nil_or_empty?
result.sort result.sort
result.reverse! result.reverse!
result = result[-n..-1] result = result[-n..-1]
end end
result.collect { |score, x| x } result.map {|score, x| x }
end end
def self.count_leading(line, ch) def count_leading(line, ch)
i, n = 0, line.length count, size = 0, line.size
while i < n and line[i].chr == ch count += 1 while count < size and line[count].chr == ch
i += 1 count
end end
i
end end
end end
module HTMLDiff module HTMLDiff
include Diff include Diff
class Builder class Builder
VALID_METHODS = [:replace, :insert, :delete, :equal] VALID_METHODS = [:replace, :insert, :delete, :equal]
def initialize(a, b) def initialize(a, b)
@a = a @a, @b = a, b
@b = b
@content = [] @content = []
end end
def do_op(opcode) def do_op(opcode)
@opcode = opcode @opcode = opcode
op = @opcode[0] op = @opcode.first
VALID_METHODS.include?(op) or raise(NameError, "Invalid opcode #{op}") raise NameError, "Invalid opcode '#{op}'" unless VALID_METHODS.include? op
self.method(op).call send op
end end
def result def result
@content.join('') @content.join
end end
#this methods have to be called via do_op(opcode) so that @opcode is set properly # These methods have to be called via do_op(opcode) so that @opcode is set properly
private private
def replace def replace
delete("diffmod") delete('diffmod')
insert("diffmod") insert('diffmod')
end end
def insert(tagclass="diffins") def insert(tagclass = 'diffins')
op_helper("ins", tagclass, @b[@opcode[3]...@opcode[4]]) op_helper('ins', tagclass, @b[@opcode[3]...@opcode[4]])
end end
def delete(tagclass="diffdel") def delete(tagclass = 'diffdel')
op_helper("del", tagclass, @a[@opcode[1]...@opcode[2]]) op_helper('del', tagclass, @a[@opcode[1]...@opcode[2]])
end end
def equal def equal
@content += @b[@opcode[3]...@opcode[4]] @content += @b[@opcode[3]...@opcode[4]]
end end
# using this as op_helper would be equivalent to the first version of diff.rb by Bill Atkins # Using this as op_helper would be equivalent to the first version of diff.rb by Bill Atkins
def op_helper_simple(tagname, tagclass, to_add) def op_helper_simple(tagname, tagclass, to_add)
@content << "<#{tagname} class=\"#{tagclass}\">" @content << %(<#{tagname} class="#{tagclass}">) << to_add << %(</#{tagname}>)
@content += to_add
@content << "</#{tagname}>"
end end
# this tries to put <p> tags or newline chars before the opening diff tags (<ins> or <del>) # Tries to put <p> tags or newline chars before the opening diff tags (<ins> or <del>)
# or after the ending diff tags # or after the ending diff tags.
# as a result the diff tags should be the "more inside" possible. # As a result the diff tags should be the "most inside" possible.
# this seems to work nice with html containing only paragraphs
# but not sure it works if there are other tags (div, span ... ? ) around
def op_helper(tagname, tagclass, to_add) def op_helper(tagname, tagclass, to_add)
@content << to_add.shift while ( HTMLDiff.is_newline(to_add.first) or predicate_methods = [:tab?, :newline?, :close_tag?, :open_tag?]
HTMLDiff.is_p_close_tag(to_add.first) or content_to_skip = Proc.new do |item|
HTMLDiff.is_p_open_tag(to_add.first) ) predicate_methods.any? {|predicate| HTMLDiff.send(predicate, item)}
@content << "<#{tagname} class=\"#{tagclass}\">" end
@content += to_add
last_tags = [] unless to_add.any? {|element| content_to_skip.call element}
last_tags.unshift(@content.pop) while ( HTMLDiff.is_newline(@content.last) or @content << wrap_text(to_add, tagname, tagclass)
HTMLDiff.is_p_close_tag(@content.last) or else
HTMLDiff.is_p_open_tag(@content.last) ) loop do
last_tags.unshift "</#{tagname}>" @content << to_add and break if to_add.all? {|element| content_to_skip.call element}
@content += last_tags # We are outside of a diff tag
remove_empty_diff(tagname, tagclass) @content << to_add.shift while content_to_skip.call to_add.first
@content << %(<#{tagname} class="#{tagclass}">)
# We are inside a diff tag
@content << to_add.shift until content_to_skip.call to_add.first
@content << %(</#{tagname}>)
end
end
#remove_empty_diff(tagname, tagclass)
end
def wrap_text(text, tagname, tagclass)
%(<#{tagname} class="#{tagclass}">#{text}</#{tagname}>)
end end
def remove_empty_diff(tagname, tagclass) def remove_empty_diff(tagname, tagclass)
if @content[-2] == "<#{tagname} class=\"#{tagclass}\">" and @content[-1] == "</#{tagname}>" then @content = @content[0...-2] if last_elements_empty_diff?(@content, tagname, tagclass)
@content.pop end
@content.pop
def last_elements_empty_diff?(content, tagname, tagclass)
content[-2] == %(<#{tagname} class="#{tagclass}">) and content.last == %(</#{tagname}>)
end end
end end
end class << self
include Diff::Utilities
def self.is_newline(x) def diff(a, b)
(x == "\n") or (x == "\r") or (x == "\t") a, b = html2list(explode(a)), html2list(explode(b))
end
def self.is_p_open_tag(x)
x =~ /\A<(p|li|ul|ol|dir|dt|dl)/
end
def self.is_p_close_tag(x)
x =~ %r!\A</(p|li|ul|ol|dir|dt|dl)!
end
def self.diff(a, b)
a = html2list(a)
b = html2list(b)
out = Builder.new(a, b) out = Builder.new(a, b)
s = SequenceMatcher.new(a, b) sequence_matcher = Diff::SequenceMatcher.new(a, b)
s.get_opcodes.each do |opcode| sequence_matcher.get_opcodes.each {|opcode| out.do_op(opcode)}
out.do_op(opcode)
end
out.result out.result
end end
def self.html2list(x)
mode = :char
cur = ''
out = []
x.split('').each do |c|
if mode == :tag
cur += c
if c == '>'
out.push(cur)
cur = ''
mode = :char
end end
elsif mode == :char end
if c == '<'
out.push cur if __FILE__ == $0
cur = c if ARGV.size == 2
mode = :tag puts HTMLDiff.diff(IO.read(ARGV.pop), IO.read(ARGV.pop))
elsif c =~ /\s/
out.push cur + c
cur = ''
else else
cur += c puts "Usage: html_diff file1 file2"
end end
end end
end
out.push cur
out.find_all { |x| x != '' }
end
end