SPB Git

Repository Public

GitModels.swift 7.0 KB 151 lines swift

1import Foundation23public struct GitStatusEntry: Sendable, Hashable, Identifiable {4    public enum Kind: String, Sendable { case staged, unstaged, both, untracked, ignored, conflicted, renamed }5    public var id: String { path }6    public let path: String7    public let originalPath: String?8    public let kind: Kind9    /// Two-letter XY code from porcelain v2 (e.g. "M.", ".M", "MM", "A.", "??", "UU").10    public let code: String1112    public init(path: String, originalPath: String? = nil, kind: Kind, code: String) {13        self.path = path; self.originalPath = originalPath; self.kind = kind; self.code = code14    }15}1617public struct GitStatus: Sendable, Hashable {18    public var branch: String?19    public var upstream: String?20    public var ahead = 021    public var behind = 022    public var headSHA: String?23    public var isDetached = false24    public var entries: [GitStatusEntry] = []2526    public init() {}2728    public var isClean: Bool { entries.allSatisfy { $0.kind == .ignored } }29    public var hasConflicts: Bool { entries.contains { $0.kind == .conflicted } }30    public var stagedCount: Int { entries.filter { $0.kind == .staged || $0.kind == .both || $0.kind == .renamed }.count }31    public var unstagedCount: Int { entries.filter { $0.kind == .unstaged || $0.kind == .both }.count }32    public var untrackedCount: Int { entries.filter { $0.kind == .untracked }.count }33}3435public struct GitCommit: Sendable, Hashable, Identifiable {36    public var id: String { sha }37    public let sha: String38    public let author: String39    public let date: Date40    public let subject: String41    public var shortSHA: String { String(sha.prefix(8)) }4243    public init(sha: String, author: String, date: Date, subject: String) {44        self.sha = sha; self.author = author; self.date = date; self.subject = subject45    }46}4748public struct GitWorktree: Sendable, Hashable, Identifiable {49    public var id: String { path }50    public let path: String51    public let head: String?52    public let branch: String?53    public let isBare: Bool54    public let isDetached: Bool55    public let isLocked: Bool56    public let isPrunable: Bool5758    public init(path: String, head: String?, branch: String?, isBare: Bool = false, isDetached: Bool = false, isLocked: Bool = false, isPrunable: Bool = false) {59        self.path = path; self.head = head; self.branch = branch; self.isBare = isBare; self.isDetached = isDetached; self.isLocked = isLocked; self.isPrunable = isPrunable60    }6162    public var branchName: String? { branch.map { $0.replacingOccurrences(of: "refs/heads/", with: "") } }63}6465public enum GitParsers {66    /// `git status --porcelain=v2 --branch -z`67    public static func parseStatus(_ output: String) -> GitStatus {68        var status = GitStatus()69        let records = output.split(separator: "\0", omittingEmptySubsequences: true).map(String.init)70        var i = 071        while i < records.count {72            let line = records[i]73            i += 174            if line.hasPrefix("# branch.oid ") { let v = String(line.dropFirst(13)); status.headSHA = v == "(initial)" ? nil : v; continue }75            if line.hasPrefix("# branch.head ") { let v = String(line.dropFirst(14)); status.isDetached = v == "(detached)"; status.branch = status.isDetached ? nil : v; continue }76            if line.hasPrefix("# branch.upstream ") { status.upstream = String(line.dropFirst(18)); continue }77            if line.hasPrefix("# branch.ab ") {78                let parts = line.dropFirst(12).split(separator: " ")79                status.ahead = Int(parts.first?.dropFirst() ?? "") ?? 080                status.behind = Int(parts.last?.dropFirst() ?? "") ?? 081                continue82            }83            if line.hasPrefix("#") { continue }84            let fields = line.split(separator: " ", omittingEmptySubsequences: false).map(String.init)85            guard let type = fields.first else { continue }86            switch type {87            case "1" where fields.count >= 9:88                let xy = fields[1]89                let path = fields[8...].joined(separator: " ")90                status.entries.append(GitStatusEntry(path: path, kind: kind(for: xy), code: xy))91            case "2" where fields.count >= 10:92                let xy = fields[1]93                let path = fields[9...].joined(separator: " ")94                let original = i < records.count ? records[i] : nil95                i += 196                status.entries.append(GitStatusEntry(path: path, originalPath: original, kind: .renamed, code: xy))97            case "u" where fields.count >= 11:98                let xy = fields[1]99                status.entries.append(GitStatusEntry(path: fields[10...].joined(separator: " "), kind: .conflicted, code: xy))100            case "?":101                status.entries.append(GitStatusEntry(path: String(line.dropFirst(2)), kind: .untracked, code: "??"))102            case "!":103                status.entries.append(GitStatusEntry(path: String(line.dropFirst(2)), kind: .ignored, code: "!!"))104            default: break105            }106        }107        return status108    }109110    static func kind(for xy: String) -> GitStatusEntry.Kind {111        let chars = Array(xy)112        guard chars.count == 2 else { return .unstaged }113        let staged = chars[0] != "."114        let unstaged = chars[1] != "."115        if staged && unstaged { return .both }116        if staged { return .staged }117        return .unstaged118    }119120    /// `git log --format=%H%x1f%an%x1f%at%x1f%s -n N`121    public static func parseLog(_ output: String) -> [GitCommit] {122        output.split(whereSeparator: \.isNewline).compactMap { line in123            let f = line.split(separator: "\u{1f}", omittingEmptySubsequences: false).map(String.init)124            guard f.count >= 4, let t = TimeInterval(f[2]) else { return nil }125            return GitCommit(sha: f[0], author: f[1], date: Date(timeIntervalSince1970: t), subject: f[3])126        }127    }128129    /// `git worktree list --porcelain`130    public static func parseWorktrees(_ output: String) -> [GitWorktree] {131        var result: [GitWorktree] = []132        var path: String?, head: String?, branch: String?, bare = false, detached = false, locked = false, prunable = false133        func flush() {134            if let p = path { result.append(GitWorktree(path: p, head: head, branch: branch, isBare: bare, isDetached: detached, isLocked: locked, isPrunable: prunable)) }135            path = nil; head = nil; branch = nil; bare = false; detached = false; locked = false; prunable = false136        }137        for line in output.components(separatedBy: "\n") {138            if line.isEmpty { flush(); continue }139            if line.hasPrefix("worktree ") { flush(); path = String(line.dropFirst(9)) }140            else if line.hasPrefix("HEAD ") { head = String(line.dropFirst(5)) }141            else if line.hasPrefix("branch ") { branch = String(line.dropFirst(7)) }142            else if line == "bare" { bare = true }143            else if line == "detached" { detached = true }144            else if line.hasPrefix("locked") { locked = true }145            else if line.hasPrefix("prunable") { prunable = true }146        }147        flush()148        return result149    }150}151
Files main
Menu

Theme