Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Diff
- -- By KillaVanilla
- local args = {...}
- local function get_diff(f1, f2)
- -- Do trimming:
- local start = 1
- local f1_end = #f1
- local f2_end = #f2
- while (start <= #f1) and (start <= #f2) do
- if not (f1[start] == f2[start]) then
- start = start-1
- break
- else
- start = start+1
- end
- end
- while (f1_end >= start) and (f2_end >= start) do
- if not (f1[f1_end] == f2[f2_end]) then
- f1_end = f1_end+1
- f2_end = f2_end+1
- break
- else
- f1_end = f1_end-1
- f2_end = f2_end-1
- end
- end
- local c = {}
- for i=0, #f1 do
- c[i] = {}
- c[i][0] = 0
- end
- for i=0, #f2 do
- c[0][i] = 0
- end
- for i=1, #f1 do
- for j=1, #f2 do
- if f1[i] == f2[j] then
- c[i][j] = c[i-1][j-1]+1
- else
- c[i][j] = math.max(c[i][j-1], c[i-1][j])
- end
- end
- end
- local d = {}
- local function recurser(i, j)
- if (i>0) and (j>0) and (f1[i] == f2[j]) then
- recurser(i-1, j-1)
- table.insert(d, {0, f1[i]})
- --print(" "..f1[i])
- elseif (j>0) and ((i==0) or (c[i][j-1] >= c[i-1][j])) then
- recurser(i, j-1)
- table.insert(d, {1, f2[j], i, j})
- --print(j..">"..f2[j])
- elseif (i>0) and ((j==0) or (c[i][j-1] < c[i-1][j])) then
- recurser(i-1, j)
- table.insert(d, {2, f1[i], i, j})
- --print(i.."<"..f1[i])
- end
- end
- recurser(#f1, #f2)
- return d
- end
- if #args < 3 then
- print("diff - Get differences between files")
- print(string.rep("=", term.getSize()))
- print("USAGE: diff <file1> <file2> <output file>")
- else
- assert(fs.exists(args[1]), args[1].." does not exist!")
- assert(fs.exists(args[2]), args[2].." does not exist!")
- local lines_1 = {}
- local lines_2 = {}
- local last_pause = os.clock()
- local f1 = fs.open(args[1], "r")
- while true do
- local line = f1.readLine()
- if line then
- table.insert(lines_1, line)
- else
- break
- end
- if (os.clock() - last_pause) >= 2.8 then
- os.queueEvent("")
- os.pullEvent("")
- last_pause = os.clock()
- end
- end
- f1.close()
- local f2 = fs.open(args[2], "r")
- while true do
- local line = f2.readLine()
- if line then
- table.insert(lines_2, line)
- else
- break
- end
- if (os.clock() - last_pause) >= 2.8 then
- os.queueEvent("")
- os.pullEvent("")
- last_pause = os.clock()
- end
- end
- f2.close()
- local diff = get_diff(lines_1, lines_2)
- local f3 = fs.open(args[3], "w")
- for i=1, #diff do
- if diff[i][1] == 1 then
- f3.writeLine(diff[i][4]..">"..diff[i][2])
- elseif diff[i][1] == 2 then
- f3.writeLine(diff[i][4].."<"..diff[i][2])
- end
- end
- --f3.writeLine(textutils.serialize(diff))
- f3.close()
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement