Skip to content

Commit dec5090

Browse files
committed
Initial attempt at Myers’ diff algorithm
1 parent ba36f04 commit dec5090

File tree

1 file changed

+33
-39
lines changed

1 file changed

+33
-39
lines changed

demo/xtra/DIFF.LUA

Lines changed: 33 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,49 +4,43 @@ local function open(filename)
44
return f
55
end
66

7-
local function blocks(f1, f2)
8-
local bs, b = 4096, {}
9-
repeat
10-
local l, r, lines, data = f1:read(bs), f2:read(bs), {}, nil
11-
if l then _, lines.l = string.gsub(l,"\n", "\n") end
12-
if r then _, lines.r = string.gsub(r,"\n", "\n") end
13-
if l ~= r then data = { l = l, r = r } end
14-
if lines.l or lines.r then
15-
table.insert(b, { data = data, lines = lines })
7+
local function diff_u(fn1,fn2)
8+
local f1, f2, pre, post, x, y, l1, l2 = open(fn1), open(fn2), {}, 0, 0, 0
9+
local function flush_pre()
10+
for _, v in ipairs(pre) do print(" " .. v) end
11+
pre = {}
12+
end
13+
local function diagonal()
14+
if #pre >= 3 then table.remove(pre, 1) end
15+
if #pre <= 0 and post > 0 then
16+
print(" " .. l2) post = post - 1
17+
else
18+
table.insert(pre, l2)
1619
end
17-
until not l and not r
18-
return b
19-
end
20-
21-
local function lines(str, prev)
22-
local l, last = {}
23-
24-
for line, newline in str:gmatch("([^\n]*)(\n?)") do
25-
if newline ~= "\n" then last = line else table.insert(l, line) end
20+
x = x + 1 y = y + 1
21+
l1, l2 = f1:read("*l"), f2:read("*l")
2622
end
23+
local function right()
24+
flush_pre()
25+
post = 3
26+
print("-" .. l1)
27+
l2 = f2:read("*l")
28+
end
29+
local function down()
30+
flush_pre()
31+
post = 3
32+
print("+" .. l2)
33+
l1 = f1:read("*l")
34+
end
35+
repeat
36+
if l1 == l2 then diagonal()
37+
elseif not l2 then right()
38+
elseif not l1 then down()
39+
else right() down()
40+
end
2741

28-
if prev and #l > 0 then l[1] = prev .. l[1] end
29-
return l, last
30-
end
31-
32-
local function diff_u(fn1,fn2)
33-
local f1, f2 = open(fn1), open(fn2)
34-
local diff_b, dl, dr, tl, tr = blocks(f1, f2)
42+
until not l1 and not l2
3543
f1:close() f2:close()
36-
37-
if diff_b then
38-
for _, v in ipairs(diff_b) do
39-
dl, tl = lines(v.data.l, tl)
40-
dr, tr = lines(v.data.r, tr)
41-
local max = #dl > #dr and #dl or #dr
42-
43-
for k = 1, max do
44-
if dl[k] ~= dr[k] then
45-
print("-"..dl[k].."\n+"..dr[k].."\n")
46-
end
47-
end
48-
end
49-
end
5044
end
5145

5246
if #arg < 2 then return end

0 commit comments

Comments
 (0)