Katalon利用java-diff-utils库写一个Groovy脚本,实现自动化比较两个文件夹下的文件,并将比较结果以文件为单位输出成HTML。当文件在两个文件夹中都存在但内容不同时,将两个文件中的差异数据都出力到HTML中,并将有差异的字段高亮显示出来;当文件只在一个文件夹中存在时,将这个信息输出到HTML中
时间: 2024-03-04 19:49:03 浏览: 84
可以使用java-diff-utils库来实现这个脚本,以下是一个示例代码:
```groovy
@Grab('com.googlecode.java-diff-utils:diffutils:1.3.0')
import difflib.*
import org.apache.commons.io.FileUtils
def compareFolders(folder1, folder2, outputHtml) {
def report = new StringBuilder()
report << "<html><head><title>Folder Comparison Report</title></head><body>"
report << "<h1>Folder Comparison Report</h1>"
def files1 = FileUtils.listFiles(folder1, null, true).toList()
def files2 = FileUtils.listFiles(folder2, null, true).toList()
def commonFiles = files1.intersect(files2)
def uniqueFiles1 = files1.minus(commonFiles)
def uniqueFiles2 = files2.minus(commonFiles)
report << "<h2>Common Files</h2>"
commonFiles.each { file ->
def relativePath = file.relativeTo(folder1).path
def file1Content = FileUtils.readFileToString(file)
def file2 = new File(folder2, relativePath)
def file2Content = FileUtils.readFileToString(file2)
if (file1Content != file2Content) {
report << "<h3>$relativePath</h3>"
report << "<table>"
report << "<tr><th>Field</th><th>File 1</th><th>File 2</th></tr>"
def diff = DiffUtils.diff(file1Content.tokenize('\n'), file2Content.tokenize('\n'))
def patch = diff.generateUnifiedDiff(relativePath, relativePath, file1Content.tokenize('\n'), diff, 0)
patch.each { line ->
if (line.startsWith("@@")) {
report << "<tr><td colspan='3'><pre>$line</pre></td></tr>"
} else if (line.startsWith("+")) {
report << "<tr><td>+</td><td></td><td>${highlightAddition(line.substring(1))}</td></tr>"
} else if (line.startsWith("-")) {
report << "<tr><td>-</td><td>${highlightDeletion(line.substring(1))}</td><td></td></tr>"
} else {
report << "<tr><td></td><td>$line</td><td>$line</td></tr>"
}
}
report << "</table>"
}
}
report << "<h2>Unique Files</h2>"
report << "<h3>Only in Folder 1:</h3>"
uniqueFiles1.each { file ->
report << "<p>${file.relativeTo(folder1)}</p>"
}
report << "<h3>Only in Folder 2:</h3>"
uniqueFiles2.each { file ->
report << "<p>${file.relativeTo(folder2)}</p>"
}
report << "</body></html>"
FileUtils.writeStringToFile(outputHtml, report.toString(), 'UTF-8')
}
def highlightAddition(str) {
"<span style='background-color: lightgreen'>$str</span>"
}
def highlightDeletion(str) {
"<span style='background-color: pink'>$str</span>"
}
// Example usage:
compareFolders(new File('folder1'), new File('folder2'), new File('report.html'))
```
这个脚本同样首先获取两个文件夹中的文件列表,并分别找出共同的文件和独立的文件。对于共同的文件,它比较每个文件的内容,如果有差异则将差异数据输出到HTML中。这次它使用java-diff-utils库来比较文件内容,将差异数据转换成Unified Diff格式,并使用表格将差异数据输出到HTML中。对于新增的内容,它使用`highlightAddition`函数将其高亮显示;对于删除的内容,它使用`highlightDeletion`函数将其高亮显示。对于独立的文件,它只需要将文件名输出到HTML中即可。
阅读全文