File: AlgorithmDiff.rb

package info (click to toggle)
tj3 3.8.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,048 kB
  • sloc: ruby: 36,481; javascript: 1,113; sh: 19; makefile: 17
file content (311 lines) | stat: -rw-r--r-- 7,189 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env ruby -w
# encoding: UTF-8
#
# = AlgorithmDiff.rb -- The TaskJuggler III Project Management Software
#
# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
#               by Chris Schlaeger <cs@taskjuggler.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#

# This class is an implementation of the classic UNIX diff functionality. It's
# based on an original implementation by Lars Christensen, which based his
# version on the Perl Algorithm::Diff implementation. This is largely a
# from-scratch implementation that tries to have a less intrusive and more
# user-friendly interface. But some code fragments are very similar to the
# original and are copyright (C) 2001 Lars Christensen.
class Diff

  # A Hunk stores all information about a contiguous change of the destination
  # list. It stores the inserted and deleted values as well as their positions
  # in the A and B list.
  class Hunk

    attr_reader :insertValues, :deleteValues
    attr_accessor :aIdx, :bIdx

    # Create a new Hunk. _aIdx_ is the index in the A list. _bIdx_ is the
    # index in the B list.
    def initialize(aIdx, bIdx)
      @aIdx = aIdx
      # A list of values to be deleted from the A list starting at aIdx.
      @deleteValues = []

      @bIdx = bIdx
      # A list of values to be inserted into the B list at bIdx.
      @insertValues = []
    end

    # Has the Hunk any values to insert?
    def insert?
      !@insertValues.empty?
    end

    # Has the Hunk any values to be deleted?
    def delete?
      !@deleteValues.empty?
    end

    def to_s
      str = ''
      showSeparator = false
      if insert? && delete?
        str << "#{aRange}c#{bRange}\n"
        showSeparator = true
      elsif insert?
        str << "#{aIdx}a#{bRange}\n"
      else
        str << "#{aRange}d#{bIdx}\n"
      end

      @deleteValues.each { |value| str << "< #{value}\n" }
      str << "---\n" if showSeparator
      @insertValues.each { |value| str << "> #{value}\n" }

      str
    end

    def inspect
      puts to_s
    end

    private

    def aRange
      range(@aIdx + 1, @aIdx + @deleteValues.length)
    end

    def bRange
      range(@bIdx + 1, @bIdx + @insertValues.length)
    end

    def range(startIdx, endIdx)
      if (startIdx == endIdx)
        "#{startIdx}"
      else
        "#{startIdx},#{endIdx}"
      end
    end

  end

  # Create a new Diff between the _a_ list and _b_ list.
  def initialize(a, b)
    @hunks = []
    diff(a, b)
  end

  # Modify the _values_ list according to the stored diff information.
  def patch(values)
    res = values.dup
    @hunks.each do |hunk|
      if hunk.delete?
        res.slice!(hunk.bIdx, hunk.deleteValues.length)
      end
      if hunk.insert?
        res.insert(hunk.bIdx, *hunk.insertValues)
      end
    end
    res
  end

  def editScript
    script = []
    @hunks.each do |hunk|
      if hunk.delete?
        script << "#{hunk.aIdx + 1}d#{hunk.deleteValues.length}"
      end
      if hunk.insert?
        script << "#{hunk.bIdx + 1}i#{hunk.insertValues.join(',')}"
      end
    end

    script
  end

  # Return the diff list as standard UNIX diff output.
  def to_s
    str = ''
    @hunks.each { |hunk| str << hunk.to_s }
    str
  end

  def inspect
    puts to_s
  end

  private

  def diff(a, b)
    indexTranslationTable = computeIndexTranslations(a, b)

    ai = bi = 0
    tableLength = indexTranslationTable.length
    while ai < tableLength do
      # Check if value from index ai should be included in B.
      destIndex = indexTranslationTable[ai]
      if destIndex
        # Yes, it needs to go to position destIndex. All values from bi to
        # newIndex - 1 are new values in B, not in A.
        while bi < destIndex
          insertElement(ai, bi, b[bi])
          bi += 1
        end
        bi += 1
      else
        # No, it's not in B. Put it onto the deletion list.
        deleteElement(ai, bi, a[ai])
      end
      ai += 1
    end

    # The remainder of the A list has to be deleted.
    while ai < a.length
      deleteElement(ai, bi, a[ai])
      ai += 1
    end
    # The remainder of the B list are new values.
    while bi < b.length
      insertElement(ai, bi, b[bi])
      bi += 1
    end
  end

  def computeIndexTranslations(a, b)
    aEndIdx = a.length - 1
    bEndIdx = b.length - 1
    startIdx = 0
    indexTranslationTable = []

    while (startIdx < aEndIdx && startIdx < bEndIdx &&
           a[startIdx] == b[startIdx])
      indexTranslationTable[startIdx] = startIdx
      startIdx += 1
    end

    while (aEndIdx >= startIdx && bEndIdx >= startIdx &&
           a[aEndIdx] == b[bEndIdx])
      indexTranslationTable[aEndIdx] = bEndIdx
      aEndIdx -= 1
      bEndIdx -= 1
    end

    return indexTranslationTable if startIdx >= aEndIdx && startIdx >= bEndIdx

    links = []
    thresholds = []
    bHashesToIndicies = reverseHash(b, startIdx, bEndIdx)

    startIdx.upto(aEndIdx) do |ai|
      aValue = a[ai]
      next unless bHashesToIndicies.has_key? aValue

      k = nil
      bHashesToIndicies[aValue].each do |bi|
        if k && (thresholds[k] > bi) && (thresholds[k - 1] < bi)
          thresholds[k] = bi
        else
          k = replaceNextLarger(thresholds, bi, k)
        end
        links[k] = [ k == 0 ? nil : links[k - 1], ai, bi ] if k
      end
    end

    if !thresholds.empty?
      link = links[thresholds.length - 1]
      while link
        indexTranslationTable[link[1]] = link[2]
        link = link[0]
      end
    end

    return indexTranslationTable
  end

  def reverseHash(values, startIdx, endIdx)
    hash = {}
    startIdx.upto(endIdx) do |i|
      element = values[i]
      if hash.has_key?(element)
        hash[element].insert(0, i)
      else
        hash[element] = [ i ]
      end
    end

    hash
  end

  def replaceNextLarger(ary, value, high = nil)
    high ||= ary.length
    if ary.empty? || value > ary[-1]
      ary.push value
      return high
    end
    low = 0
    while low < high
      index = (high + low) / 2
      found = ary[index]
      return nil if value == found

      if value > found
        low = index + 1
      else
        high = index
      end
    end

    ary[low] = value

    low
  end

  def deleteElement(aIdx, bIdx, value)
    if @hunks.empty? ||
       @hunks.last.aIdx + @hunks.last.deleteValues.length != aIdx
      @hunks << (hunk = Hunk.new(aIdx, bIdx))
    else
      hunk = @hunks.last
    end
    hunk.deleteValues << value
  end

  def insertElement(aIdx, bIdx, value)
    if @hunks.empty? ||
       @hunks.last.bIdx + @hunks.last.insertValues.length != bIdx
      @hunks << (hunk = Hunk.new(aIdx, bIdx))
    else
      hunk = @hunks.last
    end
    hunk.insertValues << value
  end

end

module Diffable

  def diff(b)
    Diff.new(self, b)
  end

  def patch(diff)
    diff.patch(self)
  end

end

module DiffableString

  def diff(b)
    split("\n").extend(Diffable).diff(b.split("\n"))
  end

  def patch(hunks)
    split("\n").extend(Diffable).patch(hunks).join("\n") + "\n"
  end

end