import Foundation public struct StatusEntry: Sendable, Equatable { /// The index column of the porcelain XY code (" " when clean). public var index: Character /// The working-tree column of the porcelain XY code. public var working: Character /// The destination path for renames and copies. public var path: String /// The source path of a rename or copy; nil otherwise. public var originalPath: String? public init(index: Character, working: Character, path: String, originalPath: String? = nil) { self.index = index self.working = working self.path = path self.originalPath = originalPath } /// True when the index column records a rename, whose source is gone from the index. public var isStagedRename: Bool { index == "R" && originalPath != nil } } public struct ParsedStatus: Sendable, Equatable { public var branch: String public var ahead: Int public var canPush: Bool public var behind: Int public var upstream: String? public var entries: [StatusEntry] public init(branch: String, ahead: Int, canPush: Bool, behind: Int = 0, upstream: String? = nil, entries: [StatusEntry]) { self.branch = branch self.ahead = ahead self.canPush = canPush self.behind = behind self.upstream = upstream self.entries = entries } } /// One row a porcelain entry turns into. public struct GitRowSpec: Sendable, Equatable { public var status: GitStatus public var staged: Bool public init(status: GitStatus, staged: Bool) { self.status = status self.staged = staged } } public enum Porcelain { /// The arguments `GitService.load` passes to git; `-z` keeps paths unquoted. public static let statusArguments = ["status", "--porcelain", "-b", "--untracked-files=all", "-z"] /// Parses `git status --porcelain -b -z`: NUL-separated, the `## ` header first. /// /// For a rename or copy (R or C in either column) the next NUL field is the source /// path, not an entry of its own. A missing header leaves the branch at "HEAD". public static func parseStatus(_ raw: String) -> ParsedStatus { let parts = raw.split(separator: "\0", omittingEmptySubsequences: false) var result = ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []) var sourceFollows = false for part in parts { if sourceFollows { sourceFollows = false result.entries[result.entries.count - 1].originalPath = String(part) continue } if part.isEmpty { continue } if part.hasPrefix("## ") { let header = String(part.dropFirst(3)) result.branch = parseBranch(header: header) (result.ahead, result.canPush) = parseAhead(header: header) result.behind = parseBehind(header: header) result.upstream = parseUpstream(header: header) continue } let chars = Array(part.prefix(2)) let index = chars.first ?? " " let working = chars.count > 1 ? chars[1] : " " let path = String(part.dropFirst(3)) if index == "R" || index == "C" || working == "R" || working == "C" { sourceFollows = true } result.entries.append(StatusEntry(index: index, working: working, path: path)) } return result } /// The display branch of a header such as `main...origin/main [ahead 1]`, /// `No commits yet on main` (→ "main") or `HEAD (no branch)` (→ "HEAD"). public static func parseBranch(header: String) -> String { let noCommits = "No commits yet on " if header.hasPrefix(noCommits) { return header.dropFirst(noCommits.count).trimmingCharacters(in: .whitespaces) } if header.hasPrefix("HEAD ") { return "HEAD" } let head = header.range(of: "...").map { header[..<$0.lowerBound] } ?? Substring(header) let name = head.split(separator: " ", omittingEmptySubsequences: false).first.map(String.init) ?? "" let trimmed = name.trimmingCharacters(in: .whitespaces) return trimmed.isEmpty ? "HEAD" : trimmed } /// Push state from a header. `[ahead N]` → (N, true); no `...` upstream → (0, true), /// because a first push still sends every commit; "No commits yet" or detached → (0, false). public static func parseAhead(header: String) -> (ahead: Int, canPush: Bool) { if header.hasPrefix("No commits yet on ") || header.hasPrefix("HEAD ") { return (0, false) } if let match = header.firstMatch(of: /\[[^\]]*\bahead (\d+)/), let count = Int(match.1) { return (count, true) } return (0, !header.contains("...")) } /// The `[behind N]` count of a header; 0 without one. public static func parseBehind(header: String) -> Int { guard let match = header.firstMatch(of: /\[[^\]]*\bbehind (\d+)/) else { return 0 } return Int(match.1) ?? 0 } /// The tracked branch after `...` in a header (`main...origin/main [ahead 1]` → "origin/main"); nil without one. public static func parseUpstream(header: String) -> String? { if header.hasPrefix("HEAD ") { return nil } guard let range = header.range(of: "...") else { return nil } let name = header[range.upperBound...].split(separator: " ").first.map(String.init) ?? "" return name.isEmpty ? nil : name } /// Maps one porcelain column letter to the letter the row shows. public static func status(for code: Character) -> GitStatus { switch code { case "A", "C", "?": .added case "D": .deleted case "R": .renamed default: .modified } } /// A merge conflict. Neither half can be staged on its own, so it stays one unstaged `U` row. public static func isConflict(index: Character, working: Character) -> Bool { index == "U" || working == "U" || (index == "A" && working == "A") || (index == "D" && working == "D") } /// Splits an XY pair into rows: "MM" is a staged row plus an unstaged row, never one folded row. public static func classify(index: Character, working: Character) -> [GitRowSpec] { if isConflict(index: index, working: working) { return [GitRowSpec(status: .unmerged, staged: false)] } var rows: [GitRowSpec] = [] if index != " " && index != "?" { rows.append(GitRowSpec(status: status(for: index), staged: true)) } if working != " " { rows.append(GitRowSpec(status: status(for: working), staged: false)) } return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows } /// True when a failed `git push` only needs `-u origin `. public static func needsUpstream(stderr: String) -> Bool { stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil } }