Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
50 kB · 1444 lines
Swift
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445import Clibgit2import Clibgit2.sysimport Foundationimport SourceControlClientimport 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..<git_status_list_entrycount(statusList.rawValue) { guard let entryPointer = git_status_byindex(statusList.rawValue, index) else { continue } let entry = entryPointer.pointee let delta = entry.index_to_workdir ?? entry.head_to_index guard let pathPointer = delta?.pointee.new_file.path ?? delta?.pointee.old_file.path else { continue } entries.append( StatusEntry( path: RepositoryPath(rawValue: String(cString: pathPointer)), kind: entry.status.entryKind ) ) } } return entries } }
func stage(_ request: StageRequest) throws { try withOpenRepository { repository in var indexPointer: OpaquePointer? try check(git_repository_index(&indexPointer, repository.rawValue)) let index = try OwnedGitIndex(indexPointer)
try index.withBorrowed { index in for path in request.paths { try path.rawValue.withCString { pathPointer in let fileURL = self.repository.url.appending(path: path.rawValue) if FileManager.default.fileExists( atPath: fileURL.path(percentEncoded: false) ) { try check(git_index_add_bypath(index.rawValue, pathPointer)) } else { try check(git_index_remove_bypath(index.rawValue, pathPointer)) } } } try check(git_index_write(index.rawValue)) } } }
func commit(_ request: CommitRequest) throws -> 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<git_signature>? 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<CChar>?] = [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<T: ~Copyable>( _ 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<T: ~Copyable>( 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<T: ~Copyable>( _ 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<T: ~Copyable>( _ 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<T: ~Copyable>( _ 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<T: ~Copyable>( _ 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<T: ~Copyable>( _ operation: (UnsafePointer<git_oid>) 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<T: ~Copyable>( _ 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<T: ~Copyable>( _ 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<T: ~Copyable>( _ 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<T: ~Copyable>( _ 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<git_signature>
init(_ rawValue: UnsafeMutablePointer<git_signature>?) 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<T: ~Copyable>( _ operation: (borrowing BorrowedGitSignature) throws -> T ) rethrows -> T { try operation(BorrowedGitSignature(self)) }}
private struct BorrowedGitSignature: ~Copyable, ~Escapable { fileprivate let rawValue: UnsafeMutablePointer<git_signature>
@_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<T: ~Copyable>( _ 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<T>( _ parentCommit: borrowing OwnedGitCommit?, _ operation: (inout UnsafeMutableBufferPointer<OpaquePointer?>) 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<T>( _ 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<GitRemoteCallbacksPayload> .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<GitRemoteCallbacksPayload> .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<GitRemoteCallbacksPayload> .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<GitRemoteCallbacksPayload> .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<GitRemoteCallbacksPayload> .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<T>(_ body: (UnsafePointer<CChar>?) 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) } }}