49 lines
1.8 KiB
Swift
49 lines
1.8 KiB
Swift
import Foundation
|
|
|
|
/// The branches a checkout can pick from: local ones and the ones on "origin".
|
|
public struct GitBranchList: Sendable, Equatable {
|
|
/// Sorted local branch names.
|
|
public var local: [String]
|
|
/// Sorted "origin/x" names; "origin/HEAD" is left out.
|
|
public var remote: [String]
|
|
|
|
public init(local: [String] = [], remote: [String] = []) {
|
|
self.local = local
|
|
self.remote = remote
|
|
}
|
|
|
|
public static let empty = GitBranchList()
|
|
|
|
/// True when `remote` ("origin/x") already has a local branch "x".
|
|
public func isTracked(_ remote: String) -> Bool {
|
|
local.contains(Self.localName(ofRemote: remote))
|
|
}
|
|
|
|
/// The local name a remote branch checks out as: "origin/feature/a" → "feature/a".
|
|
public static func localName(ofRemote remote: String) -> String {
|
|
guard let slash = remote.firstIndex(of: "/") else { return remote }
|
|
return String(remote[remote.index(after: slash)...])
|
|
}
|
|
}
|
|
|
|
public enum GitBranchParsing {
|
|
public static let arguments = ["for-each-ref", "--format=%(refname)", "refs/heads", "refs/remotes/origin"]
|
|
|
|
/// Reads one full ref name per line, as `arguments` prints them.
|
|
public static func parse(_ raw: String) -> GitBranchList {
|
|
var list = GitBranchList()
|
|
for line in raw.split(whereSeparator: \.isNewline) {
|
|
let ref = line.trimmingCharacters(in: .whitespaces)
|
|
if ref.hasPrefix("refs/heads/") {
|
|
list.local.append(String(ref.dropFirst("refs/heads/".count)))
|
|
} else if ref.hasPrefix("refs/remotes/origin/") {
|
|
let name = String(ref.dropFirst("refs/remotes/".count))
|
|
if name != "origin/HEAD" { list.remote.append(name) }
|
|
}
|
|
}
|
|
list.local.sort()
|
|
list.remote.sort()
|
|
return list
|
|
}
|
|
}
|