import Clibgit2 import Clibgit2.sys import Foundation import SourceControlClient import Tagged public enum LibGit2SourceControlClient { public static var live: SourceControlClient { LibGit2Runtime.shared.initialize() let repositories = GitRepositoryActorRegistry() return SourceControlClient( clone: { request in try await repositories.repository(at: request.destinationURL) .clone(request) .clientRepository }, open: { url in try await repositories.repository(at: url) .open() .clientRepository }, fetch: { request in try await repositories.repository(for: request.repository).fetch( remote: request.remote, credentials: request.credentials ) }, checkout: { request in try await repositories.repository(for: request.repository).checkout(ref: request.ref) }, resolveRevision: { request in try await repositories.repository(for: request.repository).resolveRevision(ref: request.ref) }, createBranch: { request in try await repositories.repository(for: request.repository).createBranch( name: request.name, startPoint: request.startPoint, checkout: request.checkout ) }, status: { repository in try await repositories.repository(for: repository).status() }, stage: { request in try await repositories.repository(for: request.repository).stage(paths: request.paths) }, commit: { request in try await repositories.repository(for: request.repository).commit( message: request.message, author: request.author ) }, formatPatch: { request in try await repositories.repository(for: request.repository).formatPatch( commit: request.commit ) }, push: { request in try await repositories.repository(for: request.repository).push( remote: request.remote, localBranch: request.localBranch, remoteBranch: request.remoteBranch, credentials: request.credentials ) } ) } } private actor GitRepositoryActorRegistry { private var repositories: [URL: GitRepositoryActor] = [:] func repository(for repository: Repository) -> GitRepositoryActor { self.repository(at: repository.url) } func repository(at url: URL) -> GitRepositoryActor { let url = url.standardizedFileURL if let repository = repositories[url] { return repository } let repository = GitRepositoryActor(url: url) repositories[url] = repository return repository } } private actor GitRepositoryActor { private var repository: GitRepository init(url: URL) { self.repository = GitRepository(url: url) } func open() throws -> GitRepository { repository = try GitRepository.open(at: repository.url) return repository } func clone(_ request: CloneRequest) throws -> GitRepository { repository = try GitRepository.clone(request) return repository } func fetch( remote: RemoteName, credentials: Credentials? ) throws { try repository.fetch(remote: remote, credentials: credentials) } func checkout(ref: RefName) throws { try repository.checkout(ref: ref) } func resolveRevision(ref: RefName) throws -> CommitID { try repository.resolveRevision(ref: ref) } func createBranch( name: BranchName, startPoint: RefName, checkout: Bool ) throws -> Branch { try repository.createBranch(name: name, startPoint: startPoint, checkout: checkout) } func status() throws -> [StatusEntry] { try repository.status() } func stage(paths: [RepositoryPath]) throws { try repository.stage(paths: paths) } func commit( message: CommitMessage, author: Author ) throws -> Commit { try repository.commit(message: message, author: author) } func formatPatch(commit: CommitID) throws -> Data { try repository.formatPatch(commit: commit) } func push( remote: RemoteName, localBranch: BranchName, remoteBranch: BranchName, credentials: Credentials? ) throws { try repository.push( remote: remote, localBranch: localBranch, remoteBranch: remoteBranch, credentials: credentials ) } } private final class LibGit2Runtime: @unchecked Sendable { static let shared = LibGit2Runtime() private let lock = NSLock() private var isInitialized = false func initialize() { lock.lock() defer { lock.unlock() } guard !isInitialized else { return } git_libgit2_init() isInitialized = true } } public struct GitRepository: Equatable, Sendable { public var url: URL public init(url: URL) { self.url = url.standardizedFileURL } public init(_ repository: Repository) { self.init(url: repository.url) } public static func open(at url: URL) throws -> Self { try Self(LibGit2Repository.open(url)) } public static func clone(_ request: CloneRequest) throws -> Self { try Self(LibGit2Repository.clone(request)) } public static func clone( remote: Remote, to destinationURL: URL, checkout: RefName? = nil, depth: Int? = nil, credentials: Credentials? = nil ) throws -> Self { try clone( CloneRequest( remote: remote, destinationURL: destinationURL, checkout: checkout, depth: depth, credentials: credentials ) ) } public var clientRepository: Repository { Repository(url: url) } public func fetch( remote: RemoteName = RemoteName(rawValue: "origin"), credentials: Credentials? = nil ) throws { try LibGit2Repository(clientRepository).fetch( FetchRequest( repository: clientRepository, remote: remote, credentials: credentials ) ) } public func checkout(ref: RefName) throws { try LibGit2Repository(clientRepository).checkout( CheckoutRequest(repository: clientRepository, ref: ref) ) } public func resolveRevision(ref: RefName = "HEAD") throws -> CommitID { try LibGit2Repository(clientRepository).resolveRevision( ResolveRevisionRequest(repository: clientRepository, ref: ref) ) } public func createBranch( name: BranchName, startPoint: RefName = RefName(rawValue: "HEAD"), checkout: Bool = true ) throws -> Branch { try LibGit2Repository(clientRepository).createBranch( CreateBranchRequest( repository: clientRepository, name: name, startPoint: startPoint, checkout: checkout ) ) } public func status() throws -> [StatusEntry] { try LibGit2Repository(clientRepository).status() } public func stage(paths: [RepositoryPath]) throws { try LibGit2Repository(clientRepository).stage( StageRequest(repository: clientRepository, paths: paths) ) } public func commit( message: CommitMessage, author: Author ) throws -> Commit { try LibGit2Repository(clientRepository).commit( CommitRequest( repository: clientRepository, message: message, author: author ) ) } public func formatPatch(commit: CommitID) throws -> Data { try LibGit2Repository(clientRepository).formatPatch( FormatPatchRequest(repository: clientRepository, commit: commit) ) } public func push( remote: RemoteName = RemoteName(rawValue: "origin"), localBranch: BranchName, remoteBranch: BranchName, credentials: Credentials? = nil ) throws { try LibGit2Repository(clientRepository).push( PushRequest( repository: clientRepository, remote: remote, localBranch: localBranch, remoteBranch: remoteBranch, credentials: credentials ) ) } } private struct LibGit2Repository { var repository: Repository init(_ repository: Repository) { self.repository = repository } static func open(_ url: URL) throws -> Repository { try withGitRepository(at: url) { _ in Repository(url: url) } } static func clone(_ request: CloneRequest) throws -> Repository { try Task.checkCancellation() var cloneOptions = git_clone_options() try check(git_clone_options_init(&cloneOptions, UInt32(GIT_CLONE_OPTIONS_VERSION))) let remoteCallbacksPayload = GitRemoteCallbacksPayload(credentials: request.credentials) configureRemoteCallbacks( &cloneOptions.fetch_opts.callbacks, payload: remoteCallbacksPayload ) if let depth = request.depth { cloneOptions.fetch_opts.depth = Int32(depth) } let checkoutBranch = request.checkout?.rawValue return try withExtendedLifetime(remoteCallbacksPayload) { try checkoutBranch.withOptionalCString { checkoutBranchPointer in cloneOptions.checkout_branch = checkoutBranchPointer return try request.remote.url.rawValue.withCString { remoteURL in try request.destinationURL.path(percentEncoded: false).withCString { destinationPath in var repositoryPointer: OpaquePointer? try checkRemote( git_clone(&repositoryPointer, remoteURL, destinationPath, &cloneOptions), payload: remoteCallbacksPayload ) try Task.checkCancellation() let repository = try OwnedGitRepository(repositoryPointer) return repository.withBorrowed { _ in Repository(url: request.destinationURL) } } } } } } func fetch(_ request: FetchRequest) throws { try Task.checkCancellation() try withOpenRepository { repository in var remotePointer: OpaquePointer? try request.remote.rawValue.withCString { remoteName in try check(git_remote_lookup(&remotePointer, repository.rawValue, remoteName)) } let remote = try OwnedGitRemote(remotePointer) var fetchOptions = git_fetch_options() try check(git_fetch_options_init(&fetchOptions, UInt32(GIT_FETCH_OPTIONS_VERSION))) let remoteCallbacksPayload = GitRemoteCallbacksPayload(credentials: request.credentials) configureRemoteCallbacks( &fetchOptions.callbacks, payload: remoteCallbacksPayload ) try withExtendedLifetime(remoteCallbacksPayload) { try remote.withBorrowed { remote in try checkRemote( git_remote_fetch(remote.rawValue, nil, &fetchOptions, nil), payload: remoteCallbacksPayload ) try Task.checkCancellation() } } } } func checkout(_ request: CheckoutRequest) throws { try withOpenRepository { repository in var objectPointer: OpaquePointer? var referencePointer: OpaquePointer? try request.ref.rawValue.withCString { refName in try check(git_revparse_ext(&objectPointer, &referencePointer, repository.rawValue, refName)) } let revspec = try OwnedGitRevspec(object: objectPointer, reference: referencePointer) var checkoutOptions = git_checkout_options() try check(git_checkout_options_init(&checkoutOptions, UInt32(GIT_CHECKOUT_OPTIONS_VERSION))) checkoutOptions.checkout_strategy = UInt32(GIT_CHECKOUT_FORCE.rawValue) try revspec.withBorrowed { revspec in try check(git_checkout_tree(repository.rawValue, revspec.object, &checkoutOptions)) if let reference = revspec.reference, git_reference_is_branch(reference) == 1, let referenceName = git_reference_name(reference) { try check(git_repository_set_head(repository.rawValue, referenceName)) } else if let oidPointer = git_object_id(revspec.object) { try check(git_repository_set_head_detached(repository.rawValue, oidPointer)) } } } } func resolveRevision(_ request: ResolveRevisionRequest) throws -> CommitID { try withOpenRepository { repository in var objectPointer: OpaquePointer? try request.ref.rawValue.withCString { refName in try check(git_revparse_single(&objectPointer, repository.rawValue, refName)) } let object = try OwnedGitObject(objectPointer) return try object.withBorrowed { object in var commitPointer: OpaquePointer? try check(git_object_peel(&commitPointer, object.rawValue, GIT_OBJECT_COMMIT)) let commit = try OwnedGitObject(commitPointer) return try commit.withBorrowed { commit in try commit.withOID { CommitID(rawValue: $0.pointee.hexString) } } } } } func createBranch(_ request: CreateBranchRequest) throws -> Branch { try withOpenRepository { repository in var objectPointer: OpaquePointer? try request.startPoint.rawValue.withCString { startPoint in try check(git_revparse_single(&objectPointer, repository.rawValue, startPoint)) } let object = try OwnedGitObject(objectPointer) let branchReference = try object.withBorrowed { object in try object.withOID { oidPointer in var commitPointer: OpaquePointer? try check(git_commit_lookup(&commitPointer, repository.rawValue, oidPointer)) let commit = try OwnedGitCommit(commitPointer) return try commit.withBorrowed { commit in var branchReferencePointer: OpaquePointer? try request.name.rawValue.withCString { branchName in try check(git_branch_create(&branchReferencePointer, repository.rawValue, branchName, commit.rawValue, 0)) } return try OwnedGitReference(branchReferencePointer) } } } _ = branchReference if request.checkout { try checkout(CheckoutRequest(repository: self.repository, ref: RefName(rawValue: request.name.rawValue))) } return Branch(name: request.name) } } func status() throws -> [StatusEntry] { try withOpenRepository { repository in var options = git_status_options() try check(git_status_options_init(&options, UInt32(GIT_STATUS_OPTIONS_VERSION))) options.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR options.flags = UInt32(GIT_STATUS_OPT_INCLUDE_UNTRACKED.rawValue | GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX.rawValue) var statusListPointer: OpaquePointer? try check(git_status_list_new(&statusListPointer, repository.rawValue, &options)) let statusList = try OwnedGitStatusList(statusListPointer) var entries: [StatusEntry] = [] statusList.withBorrowed { statusList in for index in 0.. Commit { try withOpenRepository { repository in var indexPointer: OpaquePointer? try check(git_repository_index(&indexPointer, repository.rawValue)) let index = try OwnedGitIndex(indexPointer) var treeID = git_oid() try index.withBorrowed { index in try check(git_index_write_tree(&treeID, index.rawValue)) } var treePointer: OpaquePointer? try check(git_tree_lookup(&treePointer, repository.rawValue, &treeID)) let tree = try OwnedGitTree(treePointer) var signaturePointer: UnsafeMutablePointer? try request.author.name.rawValue.withCString { name in try request.author.email.rawValue.withCString { email in try check(git_signature_now(&signaturePointer, name, email)) } } let signature = try OwnedGitSignature(signaturePointer) var headReferencePointer: OpaquePointer? var parentCommitPointer: OpaquePointer? if git_repository_head(&headReferencePointer, repository.rawValue) == 0 { let headReference = try OwnedGitReference(headReferencePointer) var parentObjectPointer: OpaquePointer? if git_reference_peel(&parentObjectPointer, headReference.rawValue, GIT_OBJECT_COMMIT) == 0, let parentOID = git_object_id(parentObjectPointer) { try check(git_commit_lookup(&parentCommitPointer, repository.rawValue, parentOID)) } if let parentObjectPointer { let parentObject = try OwnedGitObject(parentObjectPointer) _ = parentObject } } let parentCommit = try parentCommitPointer.map(OwnedGitCommit.init) var commitID = git_oid() try tree.withBorrowed { tree in try signature.withBorrowed { signature in try request.message.rawValue.withCString { message in try withParentPointers(parentCommit) { parentBuffer in try check( git_commit_create( &commitID, repository.rawValue, "HEAD", signature.rawValue, signature.rawValue, nil, message, tree.rawValue, parentBuffer.count, parentBuffer.baseAddress ) ) } } } } return Commit(id: CommitID(rawValue: commitID.hexString)) } } func formatPatch(_ request: FormatPatchRequest) throws -> Data { try withOpenRepository { repository in let commit = try lookupCommit(request.commit, in: repository) let parentCommit = try firstParentCommit(of: commit, in: repository) let oldTree: OwnedGitTree? switch parentCommit { case let .some(parentCommit): oldTree = try tree(for: parentCommit) case .none: oldTree = nil } let newTree = try tree(for: commit) var options = git_diff_options() try check(git_diff_options_init(&options, UInt32(GIT_DIFF_OPTIONS_VERSION))) options.flags = UInt32(GIT_DIFF_SHOW_BINARY.rawValue) var diffPointer: OpaquePointer? try withTreePointers(oldTree, newTree) { oldTreePointer, newTreePointer in try check( git_diff_tree_to_tree( &diffPointer, repository.rawValue, oldTreePointer, newTreePointer, &options ) ) } let diff = try OwnedGitDiff(diffPointer) var buffer = git_buf() try diff.withBorrowed { diff in try check(git_diff_to_buf(&buffer, diff.rawValue, GIT_DIFF_FORMAT_PATCH)) } defer { git_buf_dispose(&buffer) } guard let pointer = buffer.ptr else { return Data() } return Data(bytes: pointer, count: buffer.size) } } func push(_ request: PushRequest) throws { try Task.checkCancellation() try withOpenRepository { repository in var remotePointer: OpaquePointer? try request.remote.rawValue.withCString { remoteName in try check(git_remote_lookup(&remotePointer, repository.rawValue, remoteName)) } let remote = try OwnedGitRemote(remotePointer) var pushOptions = git_push_options() try check(git_push_options_init(&pushOptions, UInt32(GIT_PUSH_OPTIONS_VERSION))) let remoteCallbacksPayload = GitRemoteCallbacksPayload(credentials: request.credentials) configureRemoteCallbacks( &pushOptions.callbacks, payload: remoteCallbacksPayload, capturesPushDiagnostics: true ) let refspec = "refs/heads/\(request.localBranch.rawValue):refs/heads/\(request.remoteBranch.rawValue)" try withExtendedLifetime(remoteCallbacksPayload) { try remote.withBorrowed { remote in try refspec.withCString { refspecPointer in var refspecs: [UnsafeMutablePointer?] = [UnsafeMutablePointer(mutating: refspecPointer)] try refspecs.withUnsafeMutableBufferPointer { buffer in var strarray = git_strarray(strings: buffer.baseAddress, count: buffer.count) try checkRemotePush( git_remote_push(remote.rawValue, &strarray, &pushOptions), payload: remoteCallbacksPayload ) try Task.checkCancellation() } } } } } } private func withOpenRepository( _ operation: (borrowing BorrowedGitRepository) throws -> T ) throws -> T { try Self.withGitRepository(at: repository.url, operation) } private func lookupCommit( _ commitID: CommitID, in repository: borrowing BorrowedGitRepository ) throws -> OwnedGitCommit { var oid = git_oid() try commitID.rawValue.withCString { commitID in try check(git_oid_fromstr(&oid, commitID)) } var commitPointer: OpaquePointer? try withUnsafePointer(to: &oid) { oid in try check(git_commit_lookup(&commitPointer, repository.rawValue, oid)) } return try OwnedGitCommit(commitPointer) } private func firstParentCommit( of commit: borrowing OwnedGitCommit, in repository: borrowing BorrowedGitRepository ) throws -> OwnedGitCommit? { try commit.withBorrowed { commit in guard git_commit_parentcount(commit.rawValue) > 0 else { return nil } var parentPointer: OpaquePointer? try check(git_commit_parent(&parentPointer, commit.rawValue, 0)) return try OwnedGitCommit(parentPointer) } } private func tree(for commit: borrowing OwnedGitCommit) throws -> OwnedGitTree { try commit.withBorrowed { commit in var treePointer: OpaquePointer? try check(git_commit_tree(&treePointer, commit.rawValue)) return try OwnedGitTree(treePointer) } } private static func withGitRepository( at url: URL, _ operation: (borrowing BorrowedGitRepository) throws -> T ) throws -> T { var repositoryPointer: OpaquePointer? try url.path(percentEncoded: false).withCString { path in try check(git_repository_open(&repositoryPointer, path)) } let repository = try OwnedGitRepository(repositoryPointer) return try repository.withBorrowed(operation) } } private struct OwnedGitRepository: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a repository handle.") } self.rawValue = rawValue } deinit { git_repository_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitRepository) throws -> T ) rethrows -> T { try operation(BorrowedGitRepository(self)) } } private struct BorrowedGitRepository: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow repository) init(_ repository: borrowing OwnedGitRepository) { self.rawValue = repository.rawValue } } private struct OwnedGitRemote: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a remote handle.") } self.rawValue = rawValue } deinit { git_remote_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitRemote) throws -> T ) rethrows -> T { try operation(BorrowedGitRemote(self)) } } private struct BorrowedGitRemote: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow remote) init(_ remote: borrowing OwnedGitRemote) { self.rawValue = remote.rawValue } } private struct OwnedGitRevspec: ~Copyable { fileprivate let object: OpaquePointer fileprivate let reference: OpaquePointer? init(object: OpaquePointer?, reference: OpaquePointer?) throws { guard let object else { git_reference_free(reference) throw SourceControlError.operationFailed("libgit2 did not return an object handle.") } self.object = object self.reference = reference } deinit { git_reference_free(reference) git_object_free(object) } func withBorrowed( _ operation: (borrowing BorrowedGitRevspec) throws -> T ) rethrows -> T { try operation(BorrowedGitRevspec(self)) } } private struct BorrowedGitRevspec: ~Copyable, ~Escapable { fileprivate let object: OpaquePointer fileprivate let reference: OpaquePointer? @_lifetime(borrow revspec) init(_ revspec: borrowing OwnedGitRevspec) { self.object = revspec.object self.reference = revspec.reference } } private struct OwnedGitObject: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return an object handle.") } self.rawValue = rawValue } deinit { git_object_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitObject) throws -> T ) rethrows -> T { try operation(BorrowedGitObject(self)) } } private struct BorrowedGitObject: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow object) init(_ object: borrowing OwnedGitObject) { self.rawValue = object.rawValue } func withOID( _ operation: (UnsafePointer) throws -> T ) throws -> T { guard let oid = git_object_id(rawValue) else { throw SourceControlError.operationFailed("Could not resolve object ID.") } return try operation(oid) } } private struct OwnedGitCommit: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a commit handle.") } self.rawValue = rawValue } deinit { git_commit_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitCommit) throws -> T ) rethrows -> T { try operation(BorrowedGitCommit(self)) } } private struct BorrowedGitCommit: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow commit) init(_ commit: borrowing OwnedGitCommit) { self.rawValue = commit.rawValue } } private struct OwnedGitReference: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a reference handle.") } self.rawValue = rawValue } deinit { git_reference_free(rawValue) } } private struct OwnedGitIndex: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return an index handle.") } self.rawValue = rawValue } deinit { git_index_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitIndex) throws -> T ) rethrows -> T { try operation(BorrowedGitIndex(self)) } } private struct BorrowedGitIndex: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow index) init(_ index: borrowing OwnedGitIndex) { self.rawValue = index.rawValue } } private struct OwnedGitTree: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a tree handle.") } self.rawValue = rawValue } deinit { git_tree_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitTree) throws -> T ) rethrows -> T { try operation(BorrowedGitTree(self)) } } private struct BorrowedGitTree: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow tree) init(_ tree: borrowing OwnedGitTree) { self.rawValue = tree.rawValue } } private struct OwnedGitDiff: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a diff handle.") } self.rawValue = rawValue } deinit { git_diff_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitDiff) throws -> T ) rethrows -> T { try operation(BorrowedGitDiff(self)) } } private struct BorrowedGitDiff: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow diff) init(_ diff: borrowing OwnedGitDiff) { self.rawValue = diff.rawValue } } private struct OwnedGitSignature: ~Copyable { fileprivate let rawValue: UnsafeMutablePointer init(_ rawValue: UnsafeMutablePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a signature handle.") } self.rawValue = rawValue } deinit { git_signature_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitSignature) throws -> T ) rethrows -> T { try operation(BorrowedGitSignature(self)) } } private struct BorrowedGitSignature: ~Copyable, ~Escapable { fileprivate let rawValue: UnsafeMutablePointer @_lifetime(borrow signature) init(_ signature: borrowing OwnedGitSignature) { self.rawValue = signature.rawValue } } private struct OwnedGitStatusList: ~Copyable { fileprivate let rawValue: OpaquePointer init(_ rawValue: OpaquePointer?) throws { guard let rawValue else { throw SourceControlError.operationFailed("libgit2 did not return a status list handle.") } self.rawValue = rawValue } deinit { git_status_list_free(rawValue) } func withBorrowed( _ operation: (borrowing BorrowedGitStatusList) throws -> T ) rethrows -> T { try operation(BorrowedGitStatusList(self)) } } private struct BorrowedGitStatusList: ~Copyable, ~Escapable { fileprivate let rawValue: OpaquePointer @_lifetime(borrow statusList) init(_ statusList: borrowing OwnedGitStatusList) { self.rawValue = statusList.rawValue } } private func withParentPointers( _ parentCommit: borrowing OwnedGitCommit?, _ operation: (inout UnsafeMutableBufferPointer) throws -> T ) rethrows -> T { switch parentCommit { case let .some(parentCommit): var parents: [OpaquePointer?] = [parentCommit.rawValue] return try parents.withUnsafeMutableBufferPointer(operation) case .none: var parents: [OpaquePointer?] = [] return try parents.withUnsafeMutableBufferPointer(operation) } } private func withTreePointers( _ oldTree: borrowing OwnedGitTree?, _ newTree: borrowing OwnedGitTree, _ operation: (OpaquePointer?, OpaquePointer) throws -> T ) rethrows -> T { switch oldTree { case let .some(oldTree): return try oldTree.withBorrowed { oldTree in try newTree.withBorrowed { newTree in try operation(oldTree.rawValue, newTree.rawValue) } } case .none: return try newTree.withBorrowed { newTree in try operation(nil, newTree.rawValue) } } } private func check(_ result: Int32) throws { guard result >= 0 else { throw SourceControlError.operationFailed(lastGitError(defaultCode: result)) } } private func checkRemote( _ result: Int32, payload: GitRemoteCallbacksPayload ) throws { if result == GIT_EUSER.rawValue, payload.isCancelled { throw CancellationError() } guard result >= 0 else { throw SourceControlError.remoteOperationFailed( sourceControlRemoteFailure( message: lastGitError(defaultCode: result) ) ) } } func checkRemotePush( _ result: Int32, payload: GitRemoteCallbacksPayload ) throws { if result == GIT_EUSER.rawValue, payload.isCancelled { throw CancellationError() } let fallbackMessage = result < 0 ? lastGitError(defaultCode: result) : nil guard let message = payload.pushFailureMessage(fallback: fallbackMessage) else { return } throw SourceControlError.remoteOperationFailed( sourceControlRemoteFailure(message: message) ) } func sourceControlRemoteFailure(message: String) -> SourceControlRemoteFailure { let kind: SourceControlRemoteFailure.Kind if message.localizedCaseInsensitiveContains("timed out") { kind = .timedOut } else if message.localizedCaseInsensitiveContains("failed to start ssh session") || message.localizedCaseInsensitiveContains("failed to connect") || message.localizedCaseInsensitiveContains("could not connect") || message.localizedCaseInsensitiveContains("connection refused") || message.localizedCaseInsensitiveContains("connection reset") { kind = .connection } else if message.localizedCaseInsensitiveContains("authenticate") || message.localizedCaseInsensitiveContains("authentication") || message.localizedCaseInsensitiveContains("credential") || message.localizedCaseInsensitiveContains("permission denied") { kind = .authentication } else { kind = .unknown } return SourceControlRemoteFailure(kind: kind, message: message) } private func lastGitError(defaultCode: Int32) -> String { guard let errorPointer = git_error_last(), let message = errorPointer.pointee.message else { return "libgit2 operation failed with code \(defaultCode)." } return String(cString: message) } final class GitRemoteCallbacksPayload: @unchecked Sendable { let credentials: Credentials? private let lock = NSLock() private var pushRejections: [String] = [] private var sidebandMessages: [String] = [] init(credentials: Credentials?) { self.credentials = credentials } var isCancelled: Bool { Task.isCancelled } func recordPushRejection(refname: String, status: String) { lock.lock() defer { lock.unlock() } pushRejections.append("Remote rejected \(refname): \(status)") } func recordSidebandMessage(_ message: String) { let lines = message .split(whereSeparator: \.isNewline) .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } guard !lines.isEmpty else { return } lock.lock() defer { lock.unlock() } sidebandMessages.append(contentsOf: lines) } func pushFailureMessage(fallback: String?) -> String? { lock.lock() defer { lock.unlock() } guard !pushRejections.isEmpty || fallback != nil else { return nil } var messages = sidebandMessages + pushRejections if let fallback, !messages.contains(fallback) { messages.append(fallback) } return messages.joined(separator: "\n") } } private func configureRemoteCallbacks( _ callbacks: inout git_remote_callbacks, payload: GitRemoteCallbacksPayload, capturesPushDiagnostics: Bool = false ) { callbacks.credentials = gitCredentialAcquireCallback callbacks.transfer_progress = gitTransferProgressCallback if capturesPushDiagnostics { callbacks.sideband_progress = gitSidebandProgressCallback callbacks.push_update_reference = gitPushUpdateReferenceCallback } switch payload.credentials?.hostKeyPolicy { case .defaultValidation, .none: break case .pinnedSHA256, .acceptForTesting: callbacks.certificate_check = gitCertificateCheckCallback } callbacks.payload = Unmanaged.passUnretained(payload).toOpaque() } let gitSidebandProgressCallback: git_transport_message_cb = { message, length, payload in guard let payload else { return 0 } let payloadValue = Unmanaged .fromOpaque(payload) .takeUnretainedValue() guard !payloadValue.isCancelled else { return GIT_EUSER.rawValue } guard let message, length > 0 else { return 0 } payloadValue.recordSidebandMessage( String( decoding: UnsafeRawBufferPointer(start: message, count: Int(length)), as: UTF8.self ) ) return 0 } let gitPushUpdateReferenceCallback: git_push_update_reference_cb = { refname, status, payload in guard let payload else { return 0 } let payloadValue = Unmanaged .fromOpaque(payload) .takeUnretainedValue() guard !payloadValue.isCancelled else { return GIT_EUSER.rawValue } guard let refname, let status else { return 0 } payloadValue.recordPushRejection( refname: String(cString: refname), status: String(cString: status) ) return 0 } private let gitCredentialAcquireCallback: git_credential_acquire_cb = { out, _, usernameFromURL, allowedTypes, payload in guard let out else { return Int32(GIT_ERROR.rawValue) } guard let payload else { return Int32(GIT_PASSTHROUGH.rawValue) } let payloadValue = Unmanaged .fromOpaque(payload) .takeUnretainedValue() guard !payloadValue.isCancelled else { return GIT_EUSER.rawValue } let username = payloadValue.credentials?.ssh.username.rawValue ?? usernameFromURL.map { String(cString: $0) } ?? "git" switch payloadValue.credentials?.ssh.source ?? .agent { case .agent: if credentialAllowed(allowedTypes, GIT_CREDENTIAL_SSH_KEY) { return username.withCString { usernamePointer in git_credential_ssh_key_from_agent(out, usernamePointer) } } case let .memory(publicKey, privateKey, passphrase): if credentialAllowed(allowedTypes, GIT_CREDENTIAL_SSH_MEMORY) { let publicKey = publicKey?.rawValue let passphrase = passphrase?.rawValue return username.withCString { usernamePointer in publicKey.withOptionalCString { publicKeyPointer in privateKey.rawValue.withCString { privateKeyPointer in passphrase.withOptionalCString { passphrasePointer in git_credential_ssh_key_memory_new( out, usernamePointer, publicKeyPointer, privateKeyPointer, passphrasePointer ) } } } } } if !credentialAllowed(allowedTypes, GIT_CREDENTIAL_USERNAME) { return gitError( "The remote did not accept in-memory SSH key credentials.", code: GIT_EAUTH, errorClass: GIT_ERROR_SSH ) } } if credentialAllowed(allowedTypes, GIT_CREDENTIAL_USERNAME) { return username.withCString { usernamePointer in git_credential_username_new(out, usernamePointer) } } return Int32(GIT_PASSTHROUGH.rawValue) } private let gitTransferProgressCallback: git_indexer_progress_cb = { _, payload in guard let payload else { return 0 } let payloadValue = Unmanaged .fromOpaque(payload) .takeUnretainedValue() return payloadValue.isCancelled ? GIT_EUSER.rawValue : 0 } private let gitCertificateCheckCallback: git_transport_certificate_check_cb = { cert, _, _, payload in guard let payload else { return Int32(GIT_PASSTHROUGH.rawValue) } let payloadValue = Unmanaged .fromOpaque(payload) .takeUnretainedValue() guard !payloadValue.isCancelled else { return GIT_EUSER.rawValue } switch payloadValue.credentials?.hostKeyPolicy { case .defaultValidation, .none: return Int32(GIT_PASSTHROUGH.rawValue) case .acceptForTesting: return 0 case let .pinnedSHA256(expectedFingerprint): guard let cert, cert.pointee.cert_type == GIT_CERT_HOSTKEY_LIBSSH2 else { return gitError( "The remote did not provide an SSH host key certificate.", code: GIT_ECERTIFICATE, errorClass: GIT_ERROR_SSH ) } let hostKey = UnsafeRawPointer(cert) .assumingMemoryBound(to: git_cert_hostkey.self) .pointee guard hostKey.type.rawValue & GIT_CERT_SSH_SHA256.rawValue != 0 else { return gitError( "The remote SSH host key did not include a SHA-256 fingerprint.", code: GIT_ECERTIFICATE, errorClass: GIT_ERROR_SSH ) } let actualFingerprint = withUnsafeBytes(of: hostKey.hash_sha256) { bytes in Data(bytes).base64EncodedString().trimmingBase64Padding } guard actualFingerprint == expectedFingerprint.normalizedSHA256Fingerprint else { return gitError( "The remote SSH host key did not match the pinned SHA-256 fingerprint.", code: GIT_ECERTIFICATE, errorClass: GIT_ERROR_SSH ) } return 0 } } private func credentialAllowed( _ allowedTypes: UInt32, _ type: git_credential_t ) -> Bool { allowedTypes & type.rawValue != 0 } private func gitError( _ message: String, code: git_error_code, errorClass: git_error_t ) -> Int32 { _ = message.withCString { messagePointer in git_error_set_str(Int32(errorClass.rawValue), messagePointer) } return Int32(code.rawValue) } private extension HostKeySHA256 { var normalizedSHA256Fingerprint: String { rawValue .trimmingCharacters(in: .whitespacesAndNewlines) .removingPrefix("SHA256:") .trimmingBase64Padding } } private extension String { func removingPrefix(_ prefix: String) -> String { hasPrefix(prefix) ? String(dropFirst(prefix.count)) : self } var trimmingBase64Padding: String { trimmingCharacters(in: CharacterSet(charactersIn: "=")) } } private extension Optional where Wrapped == String { func withOptionalCString(_ body: (UnsafePointer?) throws -> T) rethrows -> T { switch self { case let .some(value): return try value.withCString(body) case .none: return try body(nil) } } } private extension git_status_t { var entryKind: StatusEntry.Kind { if rawValue & GIT_STATUS_CONFLICTED.rawValue != 0 { return .conflicted } if rawValue & GIT_STATUS_WT_NEW.rawValue != 0 { return .untracked } if rawValue & GIT_STATUS_INDEX_NEW.rawValue != 0 { return .added } if rawValue & GIT_STATUS_WT_DELETED.rawValue != 0 || rawValue & GIT_STATUS_INDEX_DELETED.rawValue != 0 { return .deleted } if rawValue & GIT_STATUS_WT_RENAMED.rawValue != 0 || rawValue & GIT_STATUS_INDEX_RENAMED.rawValue != 0 { return .renamed } if rawValue & GIT_STATUS_WT_MODIFIED.rawValue != 0 || rawValue & GIT_STATUS_INDEX_MODIFIED.rawValue != 0 { return .modified } return .modified } } private extension git_oid { var hexString: String { var oid = self return withUnsafePointer(to: &oid) { oidPointer in var buffer = [CChar](repeating: 0, count: 41) git_oid_tostr(&buffer, buffer.count, oidPointer) return String(decoding: buffer.prefix(40).map(UInt8.init(bitPattern:)), as: UTF8.self) } } }