A project: compare two files
A diff shows what changed between two versions of a text: the lines to keep, delete and add. This project finds the longest common subsequence of the lines, builds the diff with it, prints only the changes with context, and measures how similar two files are.
What you will learn#
- the longest common subsequence (LCS) and how a table finds it,
- building a diff from the table: keep, delete (
-), add (+), - reading a text file as a list of lines (
ReadAllLines), - showing only the changes with context lines,
- a similarity in percent,
- what a moved line looks like in a diff.
Version control, code review and the compare command of an editor all show a diff. The method is a classic algorithm, written in plain Ring.
The program#
# a project: compare two text files - the longest common subsequence of lines, a diff with + and -, changes with context, and a similarity
load "dotnet.ring"
using {
"System"
"System.IO"
}
func main
oFile = new File()
oPath = new Path()
cFolder = oPath.Combine([ oPath.GetTempPath(), "ringdotnet-diff-" + oPath.GetRandomFileName() ])
new Directory().CreateDirectory(cFolder)
# Two versions of a small text file (the program writes them, so that the output is always the same)
cOld = "title: Tea" + nl + "water: 200 ml" + nl + "tea: 2 g" + nl + "heat: 90 C" + nl + "wait: 3 min" + nl + "serve: hot" + nl + "enjoy"
cNew = "title: Tea" + nl + "water: 250 ml" + nl + "tea: 2 g" + nl + "milk: 20 ml" + nl + "heat: 90 C" + nl + "wait: 3 min" + nl + "serve: hot" + nl + "enjoy"
oFile.WriteAllText([ :path = cFolder + "/old.txt", :contents = cOld ])
oFile.WriteAllText([ :path = cFolder + "/new.txt", :contents = cNew ])
aOld = oFile.ReadAllLines(cFolder + "/old.txt").toList()
aNew = oFile.ReadAllLines(cFolder + "/new.txt").toList()
? "1. the files have " + len(aOld) + " and " + len(aNew) + " lines"
# A DIFF says what to do with the lines of the old file to get the new one: keep (a space), delete (-) or add (+). The idea is the
# LONGEST COMMON SUBSEQUENCE (LCS): the longest list of lines that are in both files, in the same order. Lines that are in the LCS are
# kept; the others of the old file are deleted and the others of the new file are added.
aTable = lcsTable(aOld,aNew)
? nl + "2. the length of the longest common subsequence: " + aTable[1][1]
# 3. Walk the table from the top left corner: if the lines are the same keep them; else go on in the direction that has the longer LCS
aDiff = makeDiff(aOld,aNew,aTable)
? nl + "3. the whole diff:"
for aItem in aDiff
? " " + aItem[1] + " " + aItem[2]
next
# 4. A summary: how many lines were kept, added and deleted, and how similar the files are (kept lines compared with all)
nKept = countOf(aDiff," ")
nAdded = countOf(aDiff,"+")
nDeleted = countOf(aDiff,"-")
? nl + "4. kept " + nKept + ", added " + nAdded + ", deleted " + nDeleted
? " similarity: " + floor(100 * 2 * nKept / (len(aOld) + len(aNew))) + " percent"
# 5. Only the changes, with one line of context around them. A long file has few changes, and a person wants to see only those.
? nl + "5. changes with 1 line of context:"
aLines = withContext(aDiff,1)
for cLine in aLines
? " " + cLine
next
# 6. Two files that are the same, and two that have nothing in common
? nl + "6. identical files: similarity " + similarity(aOld,aOld) + " percent; nothing in common: " + similarity([ "a","b" ],[ "c","d" ]) + " percent"
# 7. The same with the lines in another order: the LCS keeps the longest part that is in order
aMoved = [ "serve: hot", "title: Tea", "water: 200 ml", "tea: 2 g", "heat: 90 C", "wait: 3 min", "enjoy" ]
? nl + "7. 'serve' moved to the top: similarity " + similarity(aOld,aMoved) + " percent (the moved line is deleted at one place and added at another)"
new Directory().Delete([ :path = cFolder, :recursive = True ])
# The LCS table: aTable[i][j] is the length of the LCS of the lines i.. of the old list and the lines j.. of the new list. It is
# filled from the end to the start, and the cell [1][1] has the answer for the whole lists.
func lcsTable aOld,aNew
nOld = len(aOld)
nNew = len(aNew)
aTable = []
for i = 1 to nOld + 1
aRow = []
for j = 1 to nNew + 1
aRow + 0
next
aTable + aRow
next
for i = nOld to 1 step -1
for j = nNew to 1 step -1
if aOld[i] = aNew[j]
aTable[i][j] = aTable[i + 1][j + 1] + 1
else
aTable[i][j] = max(aTable[i + 1][j],aTable[i][j + 1])
ok
next
next
return aTable
# the diff as a list of [mark, line]
func makeDiff aOld,aNew,aTable
aDiff = []
i = 1
j = 1
while i <= len(aOld) and j <= len(aNew)
if aOld[i] = aNew[j]
aDiff + [ " ", aOld[i] ]
i++
j++
but aTable[i + 1][j] >= aTable[i][j + 1]
aDiff + [ "-", aOld[i] ]
i++
else
aDiff + [ "+", aNew[j] ]
j++
ok
end
while i <= len(aOld)
aDiff + [ "-", aOld[i] ]
i++
end
while j <= len(aNew)
aDiff + [ "+", aNew[j] ]
j++
end
return aDiff
func countOf aDiff,cMark
nCount = 0
for aItem in aDiff
if aItem[1] = cMark
nCount++
ok
next
return nCount
func similarity aOld,aNew
aDiff = makeDiff(aOld,aNew,lcsTable(aOld,aNew))
return floor(100 * 2 * countOf(aDiff," ") / (len(aOld) + len(aNew)))
# the lines of the diff that are changes or are within nContext lines of a change; "..." marks the lines that were left out
func withContext aDiff,nContext
aShow = []
for i = 1 to len(aDiff)
aShow + False
next
for i = 1 to len(aDiff)
if aDiff[i][1] != " "
for j = max(1,i - nContext) to min(len(aDiff),i + nContext)
aShow[j] = True
next
ok
next
aOut = []
lSkipped = False
for i = 1 to len(aDiff)
if aShow[i]
aOut + (aDiff[i][1] + " " + aDiff[i][2])
lSkipped = False
but not lSkipped
aOut + "..."
lSkipped = True
ok
next
return aOut1. the files have 7 and 8 lines
2. the length of the longest common subsequence: 6
3. the whole diff:
title: Tea
- water: 200 ml
+ water: 250 ml
tea: 2 g
+ milk: 20 ml
heat: 90 C
wait: 3 min
serve: hot
enjoy
4. kept 6, added 2, deleted 1
similarity: 80 percent
5. changes with 1 line of context:
title: Tea
- water: 200 ml
+ water: 250 ml
tea: 2 g
+ milk: 20 ml
heat: 90 C
...
6. identical files: similarity 100 percent; nothing in common: 0 percent
7. 'serve' moved to the top: similarity 85 percent (the moved line is deleted at one place and added at another)How it works#
Keep, delete, add#
To change the old file into the new one, each old line is either kept, or deleted, and some new lines are added. Many answers are possible (delete everything and add everything), so the diff looks for the one that keeps as many lines as possible. The lines that are kept form a list that is in both files in the same order: the longest common subsequence.
The table#
lcsTable makes a table in which cell [i][j] is the length of the LCS of the old lines from i on and the new lines from j on. It is filled from the end: when the two lines are the same, the cell is the cell diagonally after it plus 1; otherwise it is the larger of the cell below and the cell on the right. The cell [1][1] is the answer for the whole files: 6 here. The table has one cell for each pair of lines, so a file of 1,000 lines needs a million cells: real tools use better methods for big files, but the idea is the same.
The diff#
makeDiff walks from the top left corner. Two equal lines are kept and both positions move on. Otherwise the table says which way keeps more: when the cell below is at least as large as the cell on the right, the old line is deleted; else the new line is added. When one list ends, the rest of the other is deleted or added. The result is a list of [mark, line] pairs: a space, - or +. The change of water: 200 ml to water: 250 ml is a deletion and an addition, because a diff compares whole lines.
Context#
A long file has few changes, and a person wants to see only those. withContext keeps the changed lines and nContext lines around each one, and puts ... for each run of lines that were left out. The program shows one line of context.
Similarity#
2 * kept / (old lines + new lines) is 100 percent for the same files and 0 for files with nothing in common. Here 6 kept lines of 7 and 8 give 80 percent.
A moved line#
When a line moves from the bottom to the top, the diff deletes it at one place and adds it at the other: a diff does not know about moves. The kept part is the longest part that stays in order, so the similarity is lower than a person would say.
The program compares lines with =, which is exact: upper and lower case differ, and so do spaces at the end of a line. Files with Windows and Unix line endings give the same lines, because ReadAllLines splits both. To ignore spaces at the ends, compare trim(a) with trim(b) and print the original lines.
What you learned#
- the longest common subsequence,
- a diff from the table,
- the changes with context,
- the similarity of two files.
Exercises#
- Compare two real files and print only the changes with two lines of context.
- Add the option ignore case: compare
lower(a)withlower(b)but print the original lines. - Compare the words of two sentences instead of the lines.
- Write the diff in the unified format, with
@@ -start,count +start,count @@before each group.