Repository Public License
1import Foundation23/// A line-level diff of two texts (longest common subsequence), used by `browser.compare` and the compare helper.4public struct TextDiff: Sendable, Hashable {5 public var added: [String]6 public var removed: [String]7 public var unchangedCount: Int8 /// True when an input had more units than `maxUnits` and only the beginning was compared.9 public var wasTruncated: Bool1011 public static let maxUnits = 1_5001213 /// Share of units common to both sides, 0…1 (1 when both are empty).14 public var similarity: Double {15 let total = unchangedCount * 2 + added.count + removed.count16 return total == 0 ? 1 : Double(unchangedCount * 2) / Double(total)17 }1819 public var isIdentical: Bool { added.isEmpty && removed.isEmpty && !wasTruncated }2021 public init(old: String, new: String) {22 let left = Self.units(old), right = Self.units(new)23 wasTruncated = left.count > Self.maxUnits || right.count > Self.maxUnits24 let a = Array(left.prefix(Self.maxUnits)), b = Array(right.prefix(Self.maxUnits))25 // Classic LCS table over line keys; 1 500 × 1 500 cells at most.26 let keysA = a.map(Self.key), keysB = b.map(Self.key)27 var table = [[Int32]](repeating: [Int32](repeating: 0, count: b.count + 1), count: a.count + 1)28 if !a.isEmpty, !b.isEmpty {29 for i in stride(from: a.count - 1, through: 0, by: -1) {30 for j in stride(from: b.count - 1, through: 0, by: -1) {31 table[i][j] = keysA[i] == keysB[j] ? table[i + 1][j + 1] + 1 : max(table[i + 1][j], table[i][j + 1])32 }33 }34 }35 var added: [String] = [], removed: [String] = [], unchanged = 036 var i = 0, j = 037 while i < a.count, j < b.count {38 if keysA[i] == keysB[j] { unchanged += 1; i += 1; j += 1 }39 else if table[i + 1][j] >= table[i][j + 1] { removed.append(a[i]); i += 1 }40 else { added.append(b[j]); j += 1 }41 }42 removed.append(contentsOf: a[i...]); added.append(contentsOf: b[j...])43 self.added = added; self.removed = removed; self.unchangedCount = unchanged44 }4546 /// Non-empty lines; a text of very few long lines is split into sentences instead so that a diff says something.47 static func units(_ text: String) -> [String] {48 let lines = text.split(whereSeparator: { $0.isNewline }).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }49 if lines.count >= 4 || text.count < 400 { return lines }50 return AnswerVerifier.split(text).map(\.body)51 }5253 private static func key(_ line: String) -> String {54 line.lowercased().split(whereSeparator: { $0.isWhitespace }).joined(separator: " ")55 }5657 /// A bounded, readable summary: counts, then the first removed and added lines.58 public func summary(leftLabel: String, rightLabel: String, maxCharacters: Int) -> String {59 var lines = ["Compared \(leftLabel) (left) with \(rightLabel) (right)."]60 if isIdentical {61 lines.append("No difference: \(unchangedCount) lines are the same.")62 return lines.joined(separator: "\n")63 }64 lines.append("\(unchangedCount) lines in common, \(removed.count) only on the left, \(added.count) only on the right; similarity \(Int((similarity * 100).rounded())) %.")65 if wasTruncated { lines.append("Only the first \(Self.maxUnits) lines of each side were compared.") }66 let perSide = max(200, (maxCharacters - 300) / 2)67 func block(_ title: String, _ prefix: String, _ items: [String]) {68 guard !items.isEmpty else { return }69 lines.append(title)70 var used = 0, shown = 071 for item in items {72 let line = "\(prefix) \(AgentText.singleLine(item, limit: 240))"73 if used + line.count > perSide { break }74 lines.append(line); used += line.count + 1; shown += 175 }76 if shown < items.count { lines.append("… and \(items.count - shown) more.") }77 }78 block("Only on the left:", "-", removed)79 block("Only on the right:", "+", added)80 return AgentText.truncate(lines.joined(separator: "\n"), to: maxCharacters)81 }82}83