1 -- LuaDiffer: A simple Lua diff library
3 -- This file returns a function that can be called on two strings to return a table
4 -- containing the details of the difference between them. Usage:
5 -- >> local diff = require("diff")
6 -- >> diff("hello\nworld", "hello\nWORLD\n!!!")
7 -- {{old="hello", old_first=1, old_last=1, new="hello\n", new_first=1, new_last=1},
8 -- {old="world", old_first=2, old_last=2, new="WORLD\n!!!", new_first=2, new_last=3}}
9 -- The returned diff table also has a diff:print() method on it that can be used to print
10 -- the diff in a human-readable form. See below for the print options.
12 -- This implementation uses the Hunt-McIlroy algorithm, and is inspired by Jason Orendorff's
13 -- lovely python implementation at: http://pynash.org/2013/02/26/diff-in-50-lines/
15 -- Copyright 2017 Bruce Hill
17 -- Permission is hereby granted, free of charge, to any person obtaining a copy of
18 -- this software and associated documentation files (the "Software"), to deal in
19 -- the Software without restriction, including without limitation the rights to
20 -- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
21 -- of the Software, and to permit persons to whom the Software is furnished to do
22 -- so, subject to the following conditions:
24 -- The above copyright notice and this permission notice shall be included in all
25 -- copies or substantial portions of the Software.
27 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28 -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29 -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30 -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31 -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32 -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35 local diff_mt = {__index={}}
38 local function color(n) return string.char(27)..("[%dm"):format(n) end
39 local COLORS = {green=color(32), red=color(31), bright=color(1), underscore=color(4), reset=color(0)}
41 -- Return a new diff as if it were a diff of strings, rather than tables.
42 diff_mt.__index.stringify = function(d, sep)
43 if #d > 0 and type(d[1].old) == 'string' then return d end
45 local stringified = {}
46 for i,chunk in ipairs(d) do
48 old=table.concat(chunk.old,sep), old_first=chunk.old_first, old_last=chunk.old_last,
49 new=table.concat(chunk.new,sep), new_first=chunk.new_first, new_last=chunk.new_last,
52 return setmetatable(stringified, diff_mt)
55 -- With a diff, you can call diff:print{...} to print it out. The options available are:
56 -- color = (true/false), true by default, whether or not to print with colors.
57 -- context = <number>, how many lines of context to print around the diff, (default: infinite)
58 -- sep = <string>, the separator used for context (default: "\n")
59 -- numbers = (true/false), whether or not to print the (line) numbers where the chunks
60 -- came from in the input (default: false)
61 diff_mt.__index.print = function(d, options)
62 options = options or {}
63 if #d > 0 and type(d[1].old) == 'table' then
64 d = d:stringify(options.sep)
66 local colors = (options.color ~= false) and COLORS or setmetatable({}, {__index=function() return "" end})
67 local numbers = options.numbers or false
68 local context_pattern = nil
69 options.context = options.context or math.huge
70 if options.context ~= 0 and options.context ~= math.huge then
71 local sep = options.sep or "\n"
72 local lines = ("[^"..sep.."]*"..sep):rep(options.context)
73 context_pattern = ("^("..lines..").*"..sep.."("..lines..")$")
75 for i,chunk in ipairs(d) do
76 if chunk.old == chunk.new then
78 local same = chunk.old
79 if context_pattern then
80 local before, after = same:match(context_pattern)
81 if before and after then
82 -- "\b" is used as a hack to make sure the ellipsis is unindented
83 if i == 1 then same = "\b\b…\n"..after
84 elseif i == #d then same = before.."\n\b\b…"
85 else same = before.."\b\b…\n"..after end
88 if not (options and options.context == 0) then
89 io.write((same:gsub("([^\n]*)\n?", " %1\n")))
93 if #chunk.old > 0 then
95 print(colors.underscore..colors.bright..colors.red..
96 ("Old #%d-%d:"):format(chunk.old_first, chunk.old_last)..colors.reset)
98 io.write(colors.red..(chunk.old:gsub("([^\n]*)\n?", "- %1\n"))..colors.reset)
100 if #chunk.new > 0 then
102 print(colors.underscore..colors.bright..colors.green..
103 ("New #%d-%d:"):format(chunk.new_first, chunk.new_last)..colors.reset)
105 io.write(colors.green..(chunk.new:gsub("([^\n]*)\n?", "+ %1\n"))..colors.reset)
111 -- Take two strings or tables, and return a table representing a chunk-by-chunk diff of the two.
112 -- By default, strings are broken up by lines, but the optional third parameter "sep" lets
113 -- you provide a different separator to break on.
114 -- The return value is a list of chunks that have .old, .new corresponding to the old and
115 -- new versions. For identical chunks, .old == .new.
116 local function diff(old, new, sep)
117 local insert, concat = table.insert, table.concat
119 if type(old) == 'string' and type(new) == 'string' then
120 -- Split into a table using sep (default: newline)
123 for c in old:gmatch("[^"..sep.."]*"..sep.."?") do insert(A, c) end
124 for c in new:gmatch("[^"..sep.."]*"..sep.."?") do insert(B, c) end
125 slice = function(X,start,stop) return concat(X,"",start,stop) end
126 elseif type(old) == 'table' and type(new) == 'table' then
128 slice = function(X,start,stop)
130 for i=start,stop do s[#s+1] = X[i] end
134 error("Two different types passed to diff: "..type(old).." and "..type(new))
137 -- Find the longest common subsequence between A[a_min..a_max] and B[b_min..b_max] (inclusive),
138 -- and return (the starting position in a), (the starting position in b), (the length)
139 local longest_common_subsequence = function(a_min,a_max, b_min,b_max)
140 local longest = {a=a_min, b=b_min, length=0}
142 for a = a_min, a_max do
144 for b = b_min, b_max do
146 local new_run_len = 1 + (runs[b-1] or 0)
147 new_runs[b] = new_run_len
148 if new_run_len > longest.length then
149 longest.a = a - new_run_len + 1
150 longest.b = b - new_run_len + 1
151 longest.length = new_run_len
160 -- Find *all* the common subsequences between A[a_min..a_max] and B[b_min..b_max] (inclusive)
161 -- and put them into the common_subsequences table.
162 local common_subsequences = {}
163 local find_common_subsequences
164 find_common_subsequences = function(a_min,a_max, b_min,b_max)
165 -- Take a greedy approach and pull out the longest subsequences first
166 local lcs = longest_common_subsequence(a_min,a_max, b_min,b_max)
167 if lcs.length == 0 then return end
168 find_common_subsequences(a_min, lcs.a - 1, b_min, lcs.b - 1)
169 insert(common_subsequences, lcs)
170 find_common_subsequences(lcs.a + lcs.length, a_max, lcs.b + lcs.length, b_max)
172 find_common_subsequences(1,#A, 1,#B)
174 -- For convenience in iteration (this catches matching chunks at the end):
175 insert(common_subsequences, {a=#A+1, b=#B+1, length=0})
176 local chunks = setmetatable({}, diff_mt)
178 for _,subseq in ipairs(common_subsequences) do
179 if subseq.a > a or subseq.b > b then
181 old=slice(A, a, subseq.a-1), old_first=a, old_last=subseq.a-1,
182 new=slice(B, b, subseq.b-1), new_first=b, new_last=subseq.b-1})
184 if subseq.length > 0 then
185 -- Ensure that the *same* table is used for .old and .new so equality checks
186 -- suffice and you don't need to do element-wise comparisons.
187 local same = slice(A, subseq.a, subseq.a+subseq.length-1)
189 old=same, old_first=subseq.a, old_last=subseq.a+subseq.length-1,
190 new=same, new_first=subseq.b, new_last=subseq.b+subseq.length-1})
192 a = subseq.a + subseq.length
193 b = subseq.b + subseq.length