SPB Git

Repository Public MIT

LineDiff.swift 4.5 KB 107 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassRegistry/LineDiff.swift8// Module           : SPGlassRegistry9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243/// A small unified diff for showing how a local file differs from its registry version.44public enum LineDiff {45    /// Returns a unified diff of `old` → `new`, or an empty string when they are equal.46    public static func unified(old: String, new: String, oldLabel: String, newLabel: String, context: Int = 3) -> String {47        let a = lines(old), b = lines(new)48        if a == b { return "" }49        let difference = b.difference(from: a)50        var removed = Set<Int>(), inserted = Set<Int>()51        for change in difference {52            switch change {53            case .remove(let offset, _, _): removed.insert(offset)54            case .insert(let offset, _, _): inserted.insert(offset)55            }56        }5758        // Walk both files to build one edit script: (" ", "-", "+") with the line numbers of each side.59        struct Row { let tag: Character; let text: String; let oldLine: Int; let newLine: Int }60        var rows: [Row] = []61        var i = 0, j = 062        while i < a.count || j < b.count {63            if i < a.count, removed.contains(i) {64                rows.append(Row(tag: "-", text: a[i], oldLine: i + 1, newLine: j + 1)); i += 165            } else if j < b.count, inserted.contains(j) {66                rows.append(Row(tag: "+", text: b[j], oldLine: i + 1, newLine: j + 1)); j += 167            } else if i < a.count, j < b.count {68                rows.append(Row(tag: " ", text: a[i], oldLine: i + 1, newLine: j + 1)); i += 1; j += 169            } else {70                break71            }72        }7374        let changed = rows.indices.filter { rows[$0].tag != " " }75        guard let first = changed.first else { return "" }76        var hunks: [ClosedRange<Int>] = []77        var start = max(first - context, 0), end = min(first + context, rows.count - 1)78        for index in changed.dropFirst() {79            if index - context <= end + 1 {80                end = min(index + context, rows.count - 1)81            } else {82                hunks.append(start...end)83                start = max(index - context, 0); end = min(index + context, rows.count - 1)84            }85        }86        hunks.append(start...end)8788        var output = "--- \(oldLabel)\n+++ \(newLabel)\n"89        for hunk in hunks {90            let slice = rows[hunk]91            let oldCount = slice.filter { $0.tag != "+" }.count, newCount = slice.filter { $0.tag != "-" }.count92            let oldStart = slice.first?.oldLine ?? 1, newStart = slice.first?.newLine ?? 193            output += "@@ -\(oldCount == 0 ? oldStart - 1 : oldStart),\(oldCount) +\(newCount == 0 ? newStart - 1 : newStart),\(newCount) @@\n"94            for row in slice {95                output += "\(row.tag)\(row.text)\n"96            }97        }98        return output99    }100101    private static func lines(_ text: String) -> [String] {102        var result = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")103        if result.last == "" { result.removeLast() }104        return result105    }106}107
Files main
Menu

Theme