import Foundation /// How a line in the git console is painted. public enum GitLineKind: String, Sendable, Equatable { case command case output case error case hint case staged case unstaged case success } public struct GitConsoleLine: Sendable, Equatable { public var text: String public var kind: GitLineKind public init(text: String, kind: GitLineKind) { self.text = text self.kind = kind } } public enum GitConsoleText { /// The echo of a run, such as `$ git commit -m "fix the bar"`. public static func commandLine(_ arguments: [String]) -> String { (["$ git"] + arguments.map(quoted)).joined(separator: " ") } private static func quoted(_ argument: String) -> String { let needsQuotes = argument.isEmpty || argument.contains { $0.isWhitespace || $0 == "\"" || $0 == "'" } guard needsQuotes else { return argument } return "\"" + argument.replacingOccurrences(of: "\"", with: "\\\"") + "\"" } /// Splits what the user typed into git arguments; a leading `git` is dropped and nil means nothing is left. /// /// Quoting follows the shell: '…' is literal, "…" honours `\"` and `\\`, and an unclosed quote ends at the end. public static func parseInput(_ input: String) -> [String]? { var arguments: [String] = [] var current = "" var hasToken = false var quote: Character? var escaping = false for char in input { if escaping { if quote == "\"" && char != "\"" && char != "\\" { current.append("\\") } current.append(char) escaping = false continue } switch (quote, char) { case ("'", "'"), ("\"", "\""): quote = nil case ("'", _): current.append(char) case (_, "\\"): escaping = true hasToken = true case (nil, "'"), (nil, "\""): quote = char hasToken = true case (nil, _) where char.isWhitespace: if hasToken { arguments.append(current) } current = "" hasToken = false default: current.append(char) hasToken = true } } if escaping { current.append("\\") } if hasToken { arguments.append(current) } if arguments.first == "git" { arguments.removeFirst() } return arguments.isEmpty ? nil : arguments } /// The branch's place against its upstream, such as `1 ahead · 2 behind origin`. public static func syncLabel(ahead: Int, behind: Int, upstream: String?) -> String { guard let upstream else { return "no upstream" } let remote = upstream.split(separator: "/", maxSplits: 1).first.map(String.init) ?? upstream switch (ahead > 0, behind > 0) { case (true, true): return "\(ahead) ahead · \(behind) behind \(remote)" case (false, true): return "\(behind) behind \(remote)" case (true, false): return "\(ahead) ahead of \(remote)" case (false, false): return "in sync with \(remote)" } } } /// Paints the output lines of one git command. Keep one per run: `status` sections carry over between lines. /// /// Git writes progress to stderr, so a stderr line alone is not an error. public struct GitOutputClassifier: Sendable { private enum StatusSection { case staged case unstaged case other } private let subcommand: String? private var section = StatusSection.other public init(arguments: [String]) { subcommand = Self.subcommand(of: arguments) } public mutating func classify(_ line: String, isError: Bool) -> GitLineKind { let trimmed = line.drop { $0 == " " || $0 == "\t" } if trimmed.hasPrefix("hint:") { return .hint } if Self.errorPrefixes.contains(where: { trimmed.hasPrefix($0) }) { return .error } switch subcommand { case "push": if Self.isRefUpdate(trimmed) { return .success } case "status": if let next = Self.sections[String(trimmed)] { section = next return .output } if line.hasPrefix("\t") { switch section { case .staged: return .staged case .unstaged: return .unstaged case .other: break } } default: break } return .output } private static let errorPrefixes = [ "error:", "fatal:", "! [rejected]", "! [remote rejected]", "Aborting", "Please commit your changes", ] /// `a1b2c3d..e4f5a6b main -> main`, a forced `+ a...b`, or `* [new branch] x -> x`. private static func isRefUpdate(_ line: Substring) -> Bool { line.contains(" -> ") && line.wholeMatch(of: /(?:\+\s*)?(?:[0-9a-f]+\.\.\.?[0-9a-f]+|\*\s+\[new [a-z ]+\])\s+.+ -> .+/) != nil } private static let sections: [String: StatusSection] = [ "Changes to be committed:": .staged, "Changes not staged for commit:": .unstaged, "Untracked files:": .unstaged, "Unmerged paths:": .other, ] /// The first argument that is not an option; `-c` and `-C` take a value. private static func subcommand(of arguments: [String]) -> String? { var skipNext = false for argument in arguments { if skipNext { skipNext = false } else if argument == "-c" || argument == "-C" { skipNext = true } else if !argument.hasPrefix("-") { return argument } } return nil } }