commit 4d98e148e156962139b2d0d500d53af4068bdfc7
parent 21da5c665aacf87710db8ef3c930fae2ffe1cd74
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 15:24:51 -0500
GitLite: pure-Swift git client (objects, packfiles, smart HTTP, push), tested against real git
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
11 files changed, 1146 insertions(+), 0 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,6 @@
+*.xcodeproj
+build/
+.build/
+.swiftpm/
+fastlane/report.xml
+App/Info.plist
diff --git a/Makefile b/Makefile
@@ -0,0 +1,22 @@
+# Le code vit ici (hotrats) ; Swift et Xcode tournent sur chunga.
+CHUNGA ?= chunga
+REMOTE ?= src/perso/open-surfclam
+DEST ?= platform=iOS Simulator,name=iPhone 17 Pro
+
+.PHONY: sync test-kit project build test
+
+sync:
+ rsync -a --delete --exclude .git --exclude .claude --exclude '*.xcodeproj' --exclude build --exclude .build ./ $(CHUNGA):$(REMOTE)/
+
+# Paquet Swift seul (git + format Subsurface), sans interface. FILTER=NomDuTest pour un seul test.
+test-kit: sync
+ ssh $(CHUNGA) 'cd $(REMOTE)/Packages/DiveKit && swift test $(if $(FILTER),--filter $(FILTER)) 2>&1'
+
+project: sync
+ ssh $(CHUNGA) 'cd $(REMOTE) && xcodegen -q'
+
+build: project
+ ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme OpenSurfclam -destination "$(DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO build'
+
+test: project
+ ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme OpenSurfclam -destination "$(DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO test'
diff --git a/Packages/DiveKit/Package.swift b/Packages/DiveKit/Package.swift
@@ -0,0 +1,21 @@
+// swift-tools-version: 5.9
+import PackageDescription
+
+let package = Package(
+ name: "DiveKit",
+ platforms: [.iOS(.v17), .macOS(.v14)],
+ products: [
+ .library(name: "GitLite", targets: ["GitLite"]),
+ .library(name: "SubsurfaceLog", targets: ["SubsurfaceLog"]),
+ ],
+ targets: [
+ // Client git minimal en Swift pur : objets, paquets, protocole « smart HTTP ».
+ .target(name: "GitLite", linkerSettings: [.linkedLibrary("z")]),
+ // Format de carnet de Subsurface (stockage git) : lecture, modification, synchronisation.
+ .target(name: "SubsurfaceLog", dependencies: ["GitLite"]),
+ // Outils de test : pilote le vrai git en ligne de commande (macOS seulement).
+ .target(name: "GitTestSupport", dependencies: ["GitLite"]),
+ .testTarget(name: "GitLiteTests", dependencies: ["GitLite", "GitTestSupport"]),
+ .testTarget(name: "SubsurfaceLogTests", dependencies: ["SubsurfaceLog", "GitLite", "GitTestSupport"]),
+ ]
+)
diff --git a/Packages/DiveKit/Sources/GitLite/Client.swift b/Packages/DiveKit/Sources/GitLite/Client.swift
@@ -0,0 +1,261 @@
+import Foundation
+
+// MARK: - pkt-line
+
+enum PktLine {
+ static let flush: [UInt8] = Array("0000".utf8)
+
+ static func encode(_ payload: [UInt8]) -> [UInt8] {
+ Array(String(format: "%04x", payload.count + 4).utf8) + payload
+ }
+
+ static func encode(_ text: String) -> [UInt8] { encode(Array(text.utf8)) }
+
+ /// Découpe un flux en paquets ; `nil` = paquet de vidage (0000).
+ static func decode(_ data: [UInt8]) throws -> [[UInt8]?] {
+ var out = [[UInt8]?]()
+ var pos = 0
+ while pos + 4 <= data.count {
+ guard let length = Int(String(decoding: data[pos..<(pos + 4)], as: UTF8.self), radix: 16) else {
+ throw GitError.malformed("pkt-line : longueur")
+ }
+ if length < 4 {
+ out.append(nil)
+ pos += 4
+ continue
+ }
+ guard pos + length <= data.count else { throw GitError.malformed("pkt-line tronqué") }
+ out.append(Array(data[(pos + 4)..<(pos + length)]))
+ pos += length
+ }
+ return out
+ }
+}
+
+// MARK: - Transport
+
+public enum GitService: String, Sendable {
+ case uploadPack = "git-upload-pack"
+ case receivePack = "git-receive-pack"
+}
+
+/// Transport sans état, calqué sur le protocole « smart HTTP » de git.
+public protocol GitTransport: Sendable {
+ func advertisement(_ service: GitService) async throws -> [UInt8]
+ func rpc(_ service: GitService, body: [UInt8]) async throws -> [UInt8]
+}
+
+public struct HTTPTransport: GitTransport {
+ public let baseURL: URL
+ public let username: String
+ public let password: String
+ public let userAgent: String
+ public let session: URLSession
+
+ public init(baseURL: URL, username: String, password: String, userAgent: String = "git/2.0 (open-surfclam)", session: URLSession? = nil) {
+ self.baseURL = baseURL
+ self.username = username
+ self.password = password
+ self.userAgent = userAgent
+ if let session {
+ self.session = session
+ } else {
+ let config = URLSessionConfiguration.ephemeral
+ config.timeoutIntervalForRequest = 60
+ config.timeoutIntervalForResource = 600
+ config.httpCookieStorage = nil
+ config.urlCredentialStorage = nil
+ self.session = URLSession(configuration: config)
+ }
+ }
+
+ private func request(_ url: URL) -> URLRequest {
+ var request = URLRequest(url: url)
+ let token = Data("\(username):\(password)".utf8).base64EncodedString()
+ request.setValue("Basic \(token)", forHTTPHeaderField: "Authorization")
+ request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
+ request.cachePolicy = .reloadIgnoringLocalCacheData
+ return request
+ }
+
+ private func perform(_ request: URLRequest) async throws -> [UInt8] {
+ let data: Data
+ let response: URLResponse
+ do {
+ (data, response) = try await session.data(for: request)
+ } catch {
+ throw GitError.network(error.localizedDescription)
+ }
+ guard let http = response as? HTTPURLResponse else { throw GitError.network("réponse inattendue") }
+ switch http.statusCode {
+ case 200: return Array(data)
+ case 401, 403: throw GitError.unauthorized
+ case 404: throw GitError.notFound
+ default: throw GitError.http(http.statusCode)
+ }
+ }
+
+ public func advertisement(_ service: GitService) async throws -> [UInt8] {
+ var components = URLComponents(url: baseURL.appendingPathComponent("info/refs"), resolvingAgainstBaseURL: false)!
+ components.queryItems = [URLQueryItem(name: "service", value: service.rawValue)]
+ return try await perform(request(components.url!))
+ }
+
+ public func rpc(_ service: GitService, body: [UInt8]) async throws -> [UInt8] {
+ var request = request(baseURL.appendingPathComponent(service.rawValue))
+ request.httpMethod = "POST"
+ request.setValue("application/x-\(service.rawValue)-request", forHTTPHeaderField: "Content-Type")
+ request.setValue("application/x-\(service.rawValue)-result", forHTTPHeaderField: "Accept")
+ request.httpBody = Data(body)
+ return try await perform(request)
+ }
+}
+
+// MARK: - Client
+
+public struct RemoteRefs: Sendable {
+ public var refs: [String: ObjectID] = [:]
+ public var capabilities: Set<String> = []
+
+ public func branch(_ name: String) -> ObjectID? { refs["refs/heads/\(name)"] }
+}
+
+public struct GitClient: Sendable {
+ public let transport: GitTransport
+ public let store: ObjectStore
+ public var agent = "open-surfclam/0.1"
+
+ public init(transport: GitTransport, store: ObjectStore) {
+ self.transport = transport
+ self.store = store
+ }
+
+ public func refs(_ service: GitService = .uploadPack) async throws -> RemoteRefs {
+ let packets = try PktLine.decode(try await transport.advertisement(service))
+ var result = RemoteRefs()
+ var first = true
+ for packet in packets {
+ guard var line = packet else { continue }
+ if line.starts(with: Array("# service=".utf8)) { continue }
+ if line.last == 0x0a { line.removeLast() }
+ if first {
+ first = false
+ if let nul = line.firstIndex(of: 0) {
+ let caps = String(decoding: line[(nul + 1)...], as: UTF8.self)
+ result.capabilities = Set(caps.split(separator: " ").map(String.init))
+ line = Array(line[..<nul])
+ }
+ }
+ let text = String(decoding: line, as: UTF8.self)
+ if text.hasPrefix("ERR ") { throw GitError.remote(String(text.dropFirst(4))) }
+ guard text.count > 41, let id = ObjectID(hex: text.prefix(40)) else { continue }
+ let name = String(text.dropFirst(41))
+ if name == "capabilities^{}" || name.hasSuffix("^{}") || id.isZero { continue }
+ result.refs[name] = id
+ }
+ return result
+ }
+
+ /// Récupère `want` et ce qui en dépend. `have` = commits déjà connus, `shallow` = commits locaux sans parents,
+ /// `depth` = profondeur d'historique demandée. Rend les commits que le serveur a laissés sans parents.
+ @discardableResult
+ public func fetch(want: ObjectID, have: [ObjectID] = [], shallow: [ObjectID] = [], depth: Int? = nil,
+ capabilities: Set<String>) async throws -> [ObjectID] {
+ var caps = ["agent=\(agent)"]
+ for wanted in ["side-band-64k", "ofs-delta", "no-progress"] where capabilities.contains(wanted) {
+ caps.append(wanted)
+ }
+ let useDepth = depth != nil && capabilities.contains("shallow")
+ var body = PktLine.encode("want \(want.hex) \(caps.joined(separator: " "))\n")
+ if useDepth {
+ for id in shallow { body += PktLine.encode("shallow \(id.hex)\n") }
+ body += PktLine.encode("deepen \(depth!)\n")
+ }
+ body += PktLine.flush
+ for id in have { body += PktLine.encode("have \(id.hex)\n") }
+ body += PktLine.encode("done\n")
+
+ let response = try await transport.rpc(.uploadPack, body: body)
+ let sideband = caps.contains("side-band-64k")
+ var newShallow = [ObjectID]()
+ var pack = [UInt8]()
+ var inPack = false
+
+ if sideband {
+ for packet in try PktLine.decode(response) {
+ guard let payload = packet, let first = payload.first else { continue }
+ if !inPack, first > 3 {
+ let text = String(decoding: payload, as: UTF8.self)
+ if text.hasPrefix("shallow "), let id = ObjectID(hex: text.dropFirst(8).prefix(40)) {
+ newShallow.append(id)
+ } else if text.hasPrefix("ERR ") {
+ throw GitError.remote(String(text.dropFirst(4)))
+ }
+ continue
+ }
+ inPack = true
+ switch first {
+ case 1: pack.append(contentsOf: payload.dropFirst())
+ case 3: throw GitError.remote(String(decoding: payload.dropFirst(), as: UTF8.self))
+ default: break
+ }
+ }
+ } else {
+ // Sans bande latérale : quelques paquets texte, puis le paquet d'objets brut.
+ var pos = 0
+ while pos + 4 <= response.count, !(response[pos] == 0x50 && response[pos + 1] == 0x41) {
+ guard let length = Int(String(decoding: response[pos..<(pos + 4)], as: UTF8.self), radix: 16) else { break }
+ if length >= 4, pos + length <= response.count {
+ let text = String(decoding: response[(pos + 4)..<(pos + length)], as: UTF8.self)
+ if text.hasPrefix("shallow "), let id = ObjectID(hex: text.dropFirst(8).prefix(40)) { newShallow.append(id) }
+ if text.hasPrefix("ERR ") { throw GitError.remote(String(text.dropFirst(4))) }
+ }
+ pos += max(length, 4)
+ }
+ pack = Array(response[min(pos, response.count)...])
+ }
+
+ guard !pack.isEmpty else { throw GitError.malformed("réponse sans paquet d'objets") }
+ let store = self.store
+ let objects = try Pack.parse(pack, external: { store.get($0) })
+ for object in objects { _ = try store.put(object) }
+ guard store.contains(want) else { throw GitError.missingObject(want.hex) }
+ return newShallow
+ }
+
+ /// Envoie des objets et déplace une référence de `old` (nil = création) vers `new`.
+ public func push(ref: String, old: ObjectID?, new: ObjectID, objects: [GitObject]) async throws {
+ var body = PktLine.encode(Array("\((old ?? .zero).hex) \(new.hex) \(ref)".utf8) + [0] + Array("report-status agent=\(agent)\n".utf8))
+ body += PktLine.flush
+ body += Pack.write(objects)
+ let response = try await transport.rpc(.receivePack, body: body)
+ var unpackOK = false
+ var refOK = false
+ for packet in try PktLine.decode(response) {
+ guard var payload = packet else { continue }
+ // Certains serveurs enveloppent le rapport dans la bande 1.
+ if payload.first == 1 {
+ let inner = (try? PktLine.decode(Array(payload.dropFirst()))) ?? []
+ for case let line? in inner { try check(line, ref: ref, unpackOK: &unpackOK, refOK: &refOK) }
+ continue
+ }
+ if payload.first == 2 { continue }
+ if payload.first == 3 { payload.removeFirst(); throw GitError.remote(String(decoding: payload, as: UTF8.self)) }
+ try check(payload, ref: ref, unpackOK: &unpackOK, refOK: &refOK)
+ }
+ guard unpackOK, refOK else { throw GitError.pushRejected("réponse incomplète du serveur") }
+ }
+
+ private func check(_ line: [UInt8], ref: String, unpackOK: inout Bool, refOK: inout Bool) throws {
+ let text = String(decoding: line, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+ if text == "unpack ok" {
+ unpackOK = true
+ } else if text.hasPrefix("unpack ") {
+ throw GitError.pushRejected(String(text.dropFirst(7)))
+ } else if text == "ok \(ref)" {
+ refOK = true
+ } else if text.hasPrefix("ng ") {
+ throw GitError.pushRejected(String(text.dropFirst(3)))
+ }
+ }
+}
diff --git a/Packages/DiveKit/Sources/GitLite/Objects.swift b/Packages/DiveKit/Sources/GitLite/Objects.swift
@@ -0,0 +1,225 @@
+import CryptoKit
+import Foundation
+
+public enum GitError: Error, Equatable, CustomStringConvertible {
+ case malformed(String)
+ case missingObject(String)
+ case unauthorized
+ case notFound
+ case http(Int)
+ case network(String)
+ case remote(String)
+ case pushRejected(String)
+
+ public var description: String {
+ switch self {
+ case .malformed(let what): return "données git invalides : \(what)"
+ case .missingObject(let id): return "objet git manquant : \(id)"
+ case .unauthorized: return "identifiants refusés"
+ case .notFound: return "dépôt introuvable"
+ case .http(let code): return "erreur HTTP \(code)"
+ case .network(let what): return "réseau : \(what)"
+ case .remote(let what): return "serveur : \(what)"
+ case .pushRejected(let why): return "envoi refusé : \(why)"
+ }
+ }
+}
+
+/// Identifiant d'objet git (SHA-1, 20 octets).
+public struct ObjectID: Hashable, Sendable, CustomStringConvertible, Codable {
+ public let bytes: [UInt8]
+
+ public init?(bytes: [UInt8]) {
+ guard bytes.count == 20 else { return nil }
+ self.bytes = bytes
+ }
+
+ public init?<S: StringProtocol>(hex: S) {
+ let chars = Array(hex.utf8)
+ guard chars.count == 40 else { return nil }
+ var out = [UInt8]()
+ out.reserveCapacity(20)
+ for i in stride(from: 0, to: 40, by: 2) {
+ guard let hi = Self.nibble(chars[i]), let lo = Self.nibble(chars[i + 1]) else { return nil }
+ out.append(hi << 4 | lo)
+ }
+ self.bytes = out
+ }
+
+ private static func nibble(_ c: UInt8) -> UInt8? {
+ switch c {
+ case 48...57: return c - 48
+ case 97...102: return c - 87
+ case 65...70: return c - 55
+ default: return nil
+ }
+ }
+
+ public var hex: String {
+ let digits = Array("0123456789abcdef".utf8)
+ var out = [UInt8]()
+ out.reserveCapacity(40)
+ for b in bytes {
+ out.append(digits[Int(b >> 4)])
+ out.append(digits[Int(b & 15)])
+ }
+ return String(decoding: out, as: UTF8.self)
+ }
+
+ public var description: String { hex }
+
+ public var isZero: Bool { bytes.allSatisfy { $0 == 0 } }
+ public static let zero = ObjectID(bytes: [UInt8](repeating: 0, count: 20))!
+
+ public init(from decoder: Decoder) throws {
+ let text = try decoder.singleValueContainer().decode(String.self)
+ guard let id = ObjectID(hex: text) else {
+ throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "identifiant git invalide"))
+ }
+ self = id
+ }
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ try container.encode(hex)
+ }
+}
+
+public enum ObjectType: UInt8, Sendable {
+ case commit = 1, tree = 2, blob = 3, tag = 4
+
+ public var name: String {
+ switch self {
+ case .commit: return "commit"
+ case .tree: return "tree"
+ case .blob: return "blob"
+ case .tag: return "tag"
+ }
+ }
+}
+
+public struct GitObject: Sendable, Equatable {
+ public let type: ObjectType
+ public let data: [UInt8]
+
+ public init(type: ObjectType, data: [UInt8]) {
+ self.type = type
+ self.data = data
+ }
+
+ public var id: ObjectID {
+ var hasher = Insecure.SHA1()
+ hasher.update(data: Array("\(type.name) \(data.count)\u{0}".utf8))
+ hasher.update(data: data)
+ return ObjectID(bytes: Array(hasher.finalize()))!
+ }
+}
+
+func sha1(_ bytes: [UInt8]) -> [UInt8] {
+ Array(Insecure.SHA1.hash(data: bytes))
+}
+
+// MARK: - Arbres
+
+public struct TreeEntry: Sendable, Equatable {
+ public var mode: String
+ public var name: String
+ public var id: ObjectID
+
+ public init(mode: String, name: String, id: ObjectID) {
+ self.mode = mode
+ self.name = name
+ self.id = id
+ }
+
+ public var isTree: Bool { mode == "40000" || mode == "040000" }
+
+ public static func tree(_ name: String, _ id: ObjectID) -> TreeEntry { .init(mode: "40000", name: name, id: id) }
+ public static func blob(_ name: String, _ id: ObjectID) -> TreeEntry { .init(mode: "100644", name: name, id: id) }
+}
+
+public enum Tree {
+ public static func parse(_ data: [UInt8]) throws -> [TreeEntry] {
+ var entries = [TreeEntry]()
+ var i = 0
+ while i < data.count {
+ guard let space = data[i...].firstIndex(of: 0x20) else { throw GitError.malformed("arbre : mode") }
+ guard let nul = data[space...].firstIndex(of: 0) else { throw GitError.malformed("arbre : nom") }
+ guard nul + 21 <= data.count else { throw GitError.malformed("arbre : identifiant") }
+ let mode = String(decoding: data[i..<space], as: UTF8.self)
+ let name = String(decoding: data[(space + 1)..<nul], as: UTF8.self)
+ let id = ObjectID(bytes: Array(data[(nul + 1)..<(nul + 21)]))!
+ entries.append(TreeEntry(mode: mode, name: name, id: id))
+ i = nul + 21
+ }
+ return entries
+ }
+
+ /// Sérialise un arbre dans l'ordre exigé par git (les dossiers se comparent comme « nom/ »).
+ public static func serialize(_ entries: [TreeEntry]) -> [UInt8] {
+ func key(_ e: TreeEntry) -> [UInt8] { Array(e.name.utf8) + (e.isTree ? [0x2f] : []) }
+ let sorted = entries.sorted { key($0).lexicographicallyPrecedes(key($1)) }
+ var out = [UInt8]()
+ for e in sorted {
+ out.append(contentsOf: Array((e.mode == "040000" ? "40000" : e.mode).utf8))
+ out.append(0x20)
+ out.append(contentsOf: Array(e.name.utf8))
+ out.append(0)
+ out.append(contentsOf: e.id.bytes)
+ }
+ return out
+ }
+}
+
+// MARK: - Commits
+
+public struct Commit: Sendable, Equatable {
+ public var tree: ObjectID
+ public var parents: [ObjectID]
+ public var author: String
+ public var committer: String
+ public var message: String
+
+ public init(tree: ObjectID, parents: [ObjectID], author: String, committer: String, message: String) {
+ self.tree = tree
+ self.parents = parents
+ self.author = author
+ self.committer = committer
+ self.message = message
+ }
+
+ public static func parse(_ data: [UInt8]) throws -> Commit {
+ let text = String(decoding: data, as: UTF8.self)
+ let parts = text.components(separatedBy: "\n\n")
+ let header = parts.first ?? ""
+ let message = parts.dropFirst().joined(separator: "\n\n")
+ var tree: ObjectID?
+ var parents = [ObjectID]()
+ var author = "", committer = ""
+ for line in header.split(separator: "\n") {
+ if line.hasPrefix("tree ") {
+ tree = ObjectID(hex: line.dropFirst(5))
+ } else if line.hasPrefix("parent ") {
+ if let p = ObjectID(hex: line.dropFirst(7)) { parents.append(p) }
+ } else if line.hasPrefix("author ") {
+ author = String(line.dropFirst(7))
+ } else if line.hasPrefix("committer ") {
+ committer = String(line.dropFirst(10))
+ }
+ }
+ guard let tree else { throw GitError.malformed("commit sans arbre") }
+ return Commit(tree: tree, parents: parents, author: author, committer: committer, message: message)
+ }
+
+ public func serialize() -> [UInt8] {
+ var text = "tree \(tree.hex)\n"
+ for p in parents { text += "parent \(p.hex)\n" }
+ text += "author \(author)\ncommitter \(committer)\n\n\(message)"
+ return Array(text.utf8)
+ }
+
+ /// « Nom <courriel> secondes +0000 »
+ public static func signature(name: String, email: String, date: Date = Date()) -> String {
+ "\(name) <\(email)> \(Int(date.timeIntervalSince1970)) +0000"
+ }
+}
diff --git a/Packages/DiveKit/Sources/GitLite/Pack.swift b/Packages/DiveKit/Sources/GitLite/Pack.swift
@@ -0,0 +1,246 @@
+import Foundation
+import zlib
+
+enum Zlib {
+ /// Décompresse un flux zlib qui commence à `offset` ; rend les données et le nombre d'octets lus.
+ static func inflate(_ input: [UInt8], from offset: Int, expectedSize: Int) throws -> (data: [UInt8], consumed: Int) {
+ var stream = z_stream()
+ guard inflateInit_(&stream, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else {
+ throw GitError.malformed("zlib : initialisation")
+ }
+ defer { inflateEnd(&stream) }
+ var output = [UInt8](repeating: 0, count: max(expectedSize, 1))
+ let available = input.count - offset
+ guard available > 0 else { throw GitError.malformed("zlib : flux vide") }
+ var status: Int32 = Z_OK
+ var produced = 0
+ try input.withUnsafeBufferPointer { inPtr in
+ try output.withUnsafeMutableBufferPointer { outPtr in
+ stream.next_in = UnsafeMutablePointer(mutating: inPtr.baseAddress! + offset)
+ stream.avail_in = UInt32(min(available, Int(UInt32.max)))
+ stream.next_out = outPtr.baseAddress!
+ stream.avail_out = UInt32(outPtr.count)
+ status = zlib.inflate(&stream, Z_FINISH)
+ produced = outPtr.count - Int(stream.avail_out)
+ if status != Z_STREAM_END {
+ throw GitError.malformed("zlib : flux invalide (\(status))")
+ }
+ }
+ }
+ guard produced == expectedSize else { throw GitError.malformed("zlib : taille inattendue") }
+ let consumed = min(available, Int(UInt32.max)) - Int(stream.avail_in)
+ if output.count != expectedSize { output.removeLast(output.count - expectedSize) }
+ return (output, consumed)
+ }
+
+ static func deflate(_ input: [UInt8]) -> [UInt8] {
+ var bound = compressBound(UInt(input.count))
+ var output = [UInt8](repeating: 0, count: Int(bound))
+ let status = input.withUnsafeBufferPointer { inPtr -> Int32 in
+ // compress2 exige un pointeur non nul même pour une entrée vide.
+ var dummy: UInt8 = 0
+ return withUnsafePointer(to: &dummy) { dummyPtr in
+ compress2(&output, &bound, inPtr.baseAddress ?? dummyPtr, UInt(input.count), Z_DEFAULT_COMPRESSION)
+ }
+ }
+ precondition(status == Z_OK, "zlib : compression impossible")
+ output.removeLast(output.count - Int(bound))
+ return output
+ }
+}
+
+/// Lecture et écriture des paquets d'objets (« packfiles », version 2).
+public enum Pack {
+ private struct Entry {
+ var type: UInt8 // 1…4 objet, 6 ofs-delta, 7 ref-delta
+ var data: [UInt8] // contenu, ou instructions de delta
+ var baseOffset: Int = 0
+ var baseID: ObjectID?
+ }
+
+ /// Décode un paquet ; `external` fournit les bases absentes du paquet (paquets « minces »).
+ public static func parse(_ pack: [UInt8], external: (ObjectID) -> GitObject? = { _ in nil }) throws -> [GitObject] {
+ guard pack.count >= 32, pack[0] == 0x50, pack[1] == 0x41, pack[2] == 0x43, pack[3] == 0x4b else {
+ throw GitError.malformed("paquet : en-tête")
+ }
+ let version = be32(pack, 4)
+ guard version == 2 || version == 3 else { throw GitError.malformed("paquet : version \(version)") }
+ let count = Int(be32(pack, 8))
+ guard sha1(Array(pack[0..<(pack.count - 20)])) == Array(pack[(pack.count - 20)...]) else {
+ throw GitError.malformed("paquet : somme de contrôle")
+ }
+
+ var entries = [Int: Entry]()
+ var order = [Int]()
+ order.reserveCapacity(count)
+ var pos = 12
+ let end = pack.count - 20
+ for _ in 0..<count {
+ guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ let start = pos
+ var byte = pack[pos]; pos += 1
+ let type = (byte >> 4) & 7
+ var size = Int(byte & 15)
+ var shift = 4
+ while byte & 0x80 != 0 {
+ guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ byte = pack[pos]; pos += 1
+ size |= Int(byte & 0x7f) << shift
+ shift += 7
+ }
+ var entry = Entry(type: type, data: [])
+ switch type {
+ case 1, 2, 3, 4:
+ break
+ case 6:
+ guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ byte = pack[pos]; pos += 1
+ var offset = Int(byte & 0x7f)
+ while byte & 0x80 != 0 {
+ guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ byte = pack[pos]; pos += 1
+ offset = ((offset + 1) << 7) | Int(byte & 0x7f)
+ }
+ entry.baseOffset = start - offset
+ case 7:
+ guard pos + 20 <= end else { throw GitError.malformed("paquet tronqué") }
+ entry.baseID = ObjectID(bytes: Array(pack[pos..<(pos + 20)]))
+ pos += 20
+ default:
+ throw GitError.malformed("paquet : type \(type)")
+ }
+ let (data, consumed) = try Zlib.inflate(pack, from: pos, expectedSize: size)
+ entry.data = data
+ pos += consumed
+ entries[start] = entry
+ order.append(start)
+ }
+
+ var resolved = [Int: GitObject]()
+ var byID = [ObjectID: GitObject]()
+
+ // Objets entiers d'abord : ils servent de base aux deltas par identifiant.
+ for offset in order {
+ let e = entries[offset]!
+ if let type = ObjectType(rawValue: e.type) {
+ let object = GitObject(type: type, data: e.data)
+ resolved[offset] = object
+ byID[object.id] = object
+ }
+ }
+
+ func resolve(_ offset: Int, depth: Int) throws -> GitObject {
+ if let done = resolved[offset] { return done }
+ guard depth < 4096, let e = entries[offset] else { throw GitError.malformed("paquet : chaîne de deltas") }
+ let base: GitObject
+ if e.type == 6 {
+ base = try resolve(e.baseOffset, depth: depth + 1)
+ } else {
+ guard let id = e.baseID else { throw GitError.malformed("paquet : delta sans base") }
+ if let found = byID[id] {
+ base = found
+ } else if let found = external(id) {
+ base = found
+ } else {
+ throw GitError.missingObject(id.hex)
+ }
+ }
+ let object = GitObject(type: base.type, data: try applyDelta(base: base.data, delta: e.data))
+ resolved[offset] = object
+ byID[object.id] = object
+ return object
+ }
+
+ // Les deltas par identifiant peuvent pointer vers un delta pas encore résolu : plusieurs passes.
+ var pending = order.filter { resolved[$0] == nil }
+ while !pending.isEmpty {
+ var next = [Int]()
+ var firstError: Error?
+ for offset in pending {
+ do {
+ _ = try resolve(offset, depth: 0)
+ } catch let error as GitError {
+ if case .missingObject = error {
+ next.append(offset)
+ firstError = firstError ?? error
+ } else {
+ throw error
+ }
+ }
+ }
+ if next.count == pending.count { throw firstError ?? GitError.malformed("paquet : deltas") }
+ pending = next
+ }
+ return order.compactMap { resolved[$0] }
+ }
+
+ static func applyDelta(base: [UInt8], delta: [UInt8]) throws -> [UInt8] {
+ var pos = 0
+ func varint() throws -> Int {
+ var value = 0, shift = 0
+ while true {
+ guard pos < delta.count else { throw GitError.malformed("delta tronqué") }
+ let b = delta[pos]; pos += 1
+ value |= Int(b & 0x7f) << shift
+ shift += 7
+ if b & 0x80 == 0 { return value }
+ }
+ }
+ let baseSize = try varint()
+ guard baseSize == base.count else { throw GitError.malformed("delta : taille de la base") }
+ let resultSize = try varint()
+ var out = [UInt8]()
+ out.reserveCapacity(resultSize)
+ while pos < delta.count {
+ let op = delta[pos]; pos += 1
+ if op & 0x80 != 0 {
+ var offset = 0, size = 0
+ for i in 0..<4 where op & (1 << UInt8(i)) != 0 {
+ guard pos < delta.count else { throw GitError.malformed("delta tronqué") }
+ offset |= Int(delta[pos]) << (8 * i); pos += 1
+ }
+ for i in 0..<3 where op & (0x10 << UInt8(i)) != 0 {
+ guard pos < delta.count else { throw GitError.malformed("delta tronqué") }
+ size |= Int(delta[pos]) << (8 * i); pos += 1
+ }
+ if size == 0 { size = 0x10000 }
+ guard offset + size <= base.count else { throw GitError.malformed("delta : copie hors limites") }
+ out.append(contentsOf: base[offset..<(offset + size)])
+ } else if op != 0 {
+ let size = Int(op)
+ guard pos + size <= delta.count else { throw GitError.malformed("delta tronqué") }
+ out.append(contentsOf: delta[pos..<(pos + size)])
+ pos += size
+ } else {
+ throw GitError.malformed("delta : instruction nulle")
+ }
+ }
+ guard out.count == resultSize else { throw GitError.malformed("delta : taille du résultat") }
+ return out
+ }
+
+ /// Écrit un paquet d'objets entiers (sans delta).
+ public static func write(_ objects: [GitObject]) -> [UInt8] {
+ var out: [UInt8] = [0x50, 0x41, 0x43, 0x4b, 0, 0, 0, 2]
+ let n = UInt32(objects.count)
+ out.append(contentsOf: [UInt8(n >> 24), UInt8((n >> 16) & 255), UInt8((n >> 8) & 255), UInt8(n & 255)])
+ for object in objects {
+ var size = object.data.count
+ var byte = (object.type.rawValue << 4) | UInt8(size & 15)
+ size >>= 4
+ while size > 0 {
+ out.append(byte | 0x80)
+ byte = UInt8(size & 0x7f)
+ size >>= 7
+ }
+ out.append(byte)
+ out.append(contentsOf: Zlib.deflate(object.data))
+ }
+ out.append(contentsOf: sha1(out))
+ return out
+ }
+
+ private static func be32(_ b: [UInt8], _ i: Int) -> UInt32 {
+ UInt32(b[i]) << 24 | UInt32(b[i + 1]) << 16 | UInt32(b[i + 2]) << 8 | UInt32(b[i + 3])
+ }
+}
diff --git a/Packages/DiveKit/Sources/GitLite/Store.swift b/Packages/DiveKit/Sources/GitLite/Store.swift
@@ -0,0 +1,126 @@
+import Foundation
+
+/// Magasin d'objets git. Les implémentations sont sûres entre fils d'exécution.
+public protocol ObjectStore: AnyObject, Sendable {
+ func get(_ id: ObjectID) -> GitObject?
+ func put(_ object: GitObject) throws -> ObjectID
+ func contains(_ id: ObjectID) -> Bool
+}
+
+public extension ObjectStore {
+ func require(_ id: ObjectID) throws -> GitObject {
+ guard let object = get(id) else { throw GitError.missingObject(id.hex) }
+ return object
+ }
+
+ func tree(_ id: ObjectID) throws -> [TreeEntry] {
+ let object = try require(id)
+ guard object.type == .tree else { throw GitError.malformed("\(id.hex) n'est pas un arbre") }
+ return try Tree.parse(object.data)
+ }
+
+ func commit(_ id: ObjectID) throws -> Commit {
+ let object = try require(id)
+ guard object.type == .commit else { throw GitError.malformed("\(id.hex) n'est pas un commit") }
+ return try Commit.parse(object.data)
+ }
+
+ func blob(_ id: ObjectID) throws -> [UInt8] {
+ let object = try require(id)
+ guard object.type == .blob else { throw GitError.malformed("\(id.hex) n'est pas un fichier") }
+ return object.data
+ }
+
+ @discardableResult
+ func putBlob(_ text: String) throws -> ObjectID {
+ try put(GitObject(type: .blob, data: Array(text.utf8)))
+ }
+
+ @discardableResult
+ func putTree(_ entries: [TreeEntry]) throws -> ObjectID {
+ try put(GitObject(type: .tree, data: Tree.serialize(entries)))
+ }
+}
+
+public final class MemoryObjectStore: ObjectStore, @unchecked Sendable {
+ private var objects = [ObjectID: GitObject]()
+ private let lock = NSLock()
+
+ public init() {}
+
+ public func get(_ id: ObjectID) -> GitObject? {
+ lock.lock(); defer { lock.unlock() }
+ return objects[id]
+ }
+
+ public func put(_ object: GitObject) throws -> ObjectID {
+ let id = object.id
+ lock.lock(); defer { lock.unlock() }
+ objects[id] = object
+ return id
+ }
+
+ public func contains(_ id: ObjectID) -> Bool {
+ lock.lock(); defer { lock.unlock() }
+ return objects[id] != nil
+ }
+
+ public var count: Int {
+ lock.lock(); defer { lock.unlock() }
+ return objects.count
+ }
+}
+
+/// Magasin sur disque : un fichier par objet (`ab/cdef…`), premier octet = type, le reste = contenu.
+public final class FileObjectStore: ObjectStore, @unchecked Sendable {
+ public let directory: URL
+ private var cache = [ObjectID: GitObject]()
+ private let lock = NSLock()
+ private let cacheLimit: Int
+
+ public init(directory: URL, cacheLimit: Int = 4096) throws {
+ self.directory = directory
+ self.cacheLimit = cacheLimit
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ }
+
+ private func url(_ id: ObjectID) -> URL {
+ let hex = id.hex
+ return directory.appendingPathComponent(String(hex.prefix(2))).appendingPathComponent(String(hex.dropFirst(2)))
+ }
+
+ public func get(_ id: ObjectID) -> GitObject? {
+ lock.lock(); defer { lock.unlock() }
+ if let hit = cache[id] { return hit }
+ guard let data = try? Data(contentsOf: url(id)), let first = data.first, let type = ObjectType(rawValue: first) else {
+ return nil
+ }
+ let object = GitObject(type: type, data: Array(data.dropFirst()))
+ remember(id, object)
+ return object
+ }
+
+ public func put(_ object: GitObject) throws -> ObjectID {
+ let id = object.id
+ lock.lock(); defer { lock.unlock() }
+ let target = url(id)
+ if !FileManager.default.fileExists(atPath: target.path) {
+ try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
+ var data = Data([object.type.rawValue])
+ data.append(contentsOf: object.data)
+ try data.write(to: target, options: .atomic)
+ }
+ remember(id, object)
+ return id
+ }
+
+ public func contains(_ id: ObjectID) -> Bool {
+ lock.lock(); defer { lock.unlock() }
+ return cache[id] != nil || FileManager.default.fileExists(atPath: url(id).path)
+ }
+
+ private func remember(_ id: ObjectID, _ object: GitObject) {
+ if cache.count >= cacheLimit { cache.removeAll(keepingCapacity: true) }
+ cache[id] = object
+ }
+}
diff --git a/Packages/DiveKit/Sources/GitTestSupport/LocalGit.swift b/Packages/DiveKit/Sources/GitTestSupport/LocalGit.swift
@@ -0,0 +1,101 @@
+#if os(macOS)
+import Foundation
+import GitLite
+
+/// Dépôt git local piloté par la commande `git`, pour confronter GitLite au vrai git.
+public struct LocalGit: Sendable {
+ public let directory: URL
+
+ public init(directory: URL) {
+ self.directory = directory
+ }
+
+ public static func temporaryDirectory(_ name: String = "repo") throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("divekit-\(UUID().uuidString)").appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ public static func create(bare: Bool = false, name: String = "repo") throws -> LocalGit {
+ let repo = LocalGit(directory: try temporaryDirectory(name))
+ try repo.git(["init", "-q", "-b", "main"] + (bare ? ["--bare"] : []))
+ try repo.git(["config", "user.name", "Test"])
+ try repo.git(["config", "user.email", "test@example.com"])
+ try repo.git(["config", "uploadpack.allowAnySHA1InWant", "true"])
+ return repo
+ }
+
+ @discardableResult
+ public func git(_ arguments: [String], input: [UInt8]? = nil) throws -> [UInt8] {
+ try Self.run(arguments, in: directory, input: input)
+ }
+
+ public func text(_ arguments: [String]) throws -> String {
+ String(decoding: try git(arguments), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ public func write(_ path: String, _ content: String) throws {
+ let url = directory.appendingPathComponent(path)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(content.utf8).write(to: url)
+ }
+
+ @discardableResult
+ public func commitAll(_ message: String) throws -> ObjectID {
+ try git(["add", "-A"])
+ try git(["commit", "-q", "--allow-empty", "-m", message])
+ return ObjectID(hex: try text(["rev-parse", "HEAD"]))!
+ }
+
+ public static func run(_ arguments: [String], in directory: URL, input: [UInt8]? = nil) throws -> [UInt8] {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
+ process.arguments = ["git"] + arguments
+ process.currentDirectoryURL = directory
+ let stdout = Pipe(), stderr = Pipe(), stdin = Pipe()
+ process.standardOutput = stdout
+ process.standardError = stderr
+ process.standardInput = stdin
+ try process.run()
+ let writer = Thread {
+ if let input { stdin.fileHandleForWriting.write(Data(input)) }
+ try? stdin.fileHandleForWriting.close()
+ }
+ writer.start()
+ var errorData = Data()
+ let errorReader = Thread { errorData = stderr.fileHandleForReading.readDataToEndOfFile() }
+ errorReader.start()
+ let output = stdout.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ while !errorReader.isFinished { usleep(1000) }
+ guard process.terminationStatus == 0 else {
+ throw GitError.remote("git \(arguments.joined(separator: " ")) : \(String(decoding: errorData, as: UTF8.self))")
+ }
+ return Array(output)
+ }
+}
+
+/// Transport qui parle au vrai `git upload-pack` / `git receive-pack` en mode sans état, comme le ferait un serveur HTTP.
+public struct LocalProcessTransport: GitTransport {
+ public let repository: URL
+
+ public init(repository: URL) {
+ self.repository = repository
+ }
+
+ private func command(_ service: GitService) -> String {
+ service == .uploadPack ? "upload-pack" : "receive-pack"
+ }
+
+ public func advertisement(_ service: GitService) async throws -> [UInt8] {
+ let refs = try LocalGit.run([command(service), "--stateless-rpc", "--advertise-refs", repository.path], in: repository)
+ let header = "# service=\(service.rawValue)\n"
+ return Array(String(format: "%04x", header.utf8.count + 4).utf8) + Array(header.utf8) + Array("0000".utf8) + refs
+ }
+
+ public func rpc(_ service: GitService, body: [UInt8]) async throws -> [UInt8] {
+ try LocalGit.run([command(service), "--stateless-rpc", repository.path], in: repository, input: body)
+ }
+}
+#endif
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Placeholder.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Placeholder.swift
@@ -0,0 +1 @@
+import GitLite
diff --git a/Packages/DiveKit/Tests/GitLiteTests/GitLiteTests.swift b/Packages/DiveKit/Tests/GitLiteTests/GitLiteTests.swift
@@ -0,0 +1,135 @@
+import XCTest
+@testable import GitLite
+import GitTestSupport
+
+final class GitLiteTests: XCTestCase {
+ func testObjectIDs() throws {
+ // « git hash-object » d'un fichier vide et de "hello\n"
+ XCTAssertEqual(GitObject(type: .blob, data: []).id.hex, "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391")
+ XCTAssertEqual(GitObject(type: .blob, data: Array("hello\n".utf8)).id.hex, "ce013625030ba8dba906f756967f9e9ca394464a")
+ XCTAssertEqual(ObjectID(hex: "ce013625030ba8dba906f756967f9e9ca394464a")?.hex, "ce013625030ba8dba906f756967f9e9ca394464a")
+ XCTAssertNil(ObjectID(hex: "xyz"))
+ }
+
+ func testPackRoundTrip() throws {
+ let objects = [
+ GitObject(type: .blob, data: []),
+ GitObject(type: .blob, data: Array(repeating: 65, count: 100_000)),
+ GitObject(type: .blob, data: (0..<5000).map { UInt8(truncatingIfNeeded: $0 &* 31) }),
+ ]
+ let parsed = try Pack.parse(Pack.write(objects))
+ XCTAssertEqual(parsed, objects)
+ }
+
+ func testCorruptPackIsRejected() throws {
+ var pack = Pack.write([GitObject(type: .blob, data: Array("abc".utf8))])
+ pack[14] ^= 0xff
+ XCTAssertThrowsError(try Pack.parse(pack))
+ }
+
+ func testTreeOrderMatchesGit() throws {
+ let repo = try LocalGit.create()
+ try repo.write("a.txt", "1")
+ try repo.write("a/x", "2")
+ try repo.write("a-b", "3")
+ try repo.write("a0", "4")
+ try repo.write("Z", "5")
+ try repo.commitAll("ordre")
+ let raw = try repo.git(["cat-file", "tree", "HEAD^{tree}"])
+ let entries = try Tree.parse(raw)
+ XCTAssertEqual(entries.map(\.name), ["Z", "a-b", "a.txt", "a", "a0"])
+ XCTAssertEqual(Tree.serialize(entries.shuffled()), raw)
+ }
+
+ /// Dépôt avec historique et deltas, relu en entier par notre client.
+ func testFetchMatchesRealGit() async throws {
+ let repo = try LocalGit.create()
+ var body = (0..<400).map { "ligne \($0) du profil de plongée\n" }.joined()
+ for i in 0..<12 {
+ body += "ajout \(i)\n"
+ try repo.write("2024/05/plongee-\(i % 3)/Divecomputer", body)
+ try repo.write("00-Subsurface", "version 3\nrev \(i)\n")
+ try repo.commitAll("commit \(i)")
+ }
+ try repo.git(["gc", "-q", "--aggressive"])
+ let head = ObjectID(hex: try repo.text(["rev-parse", "HEAD"]))!
+
+ let store = MemoryObjectStore()
+ let client = GitClient(transport: LocalProcessTransport(repository: repo.directory), store: store)
+ let remote = try await client.refs()
+ XCTAssertEqual(remote.branch("main"), head)
+ try await client.fetch(want: head, capabilities: remote.capabilities)
+
+ // Tous les objets du dépôt sont là et identiques.
+ let listing = try repo.text(["rev-list", "--objects", "--all"])
+ var checked = 0
+ for line in listing.split(separator: "\n") {
+ let id = ObjectID(hex: line.prefix(40))!
+ let object = try XCTUnwrap(store.get(id), "objet absent : \(line)")
+ let type = try repo.text(["cat-file", "-t", id.hex])
+ XCTAssertEqual(object.type.name, type)
+ XCTAssertEqual(object.data, try repo.git(["cat-file", type, id.hex]))
+ checked += 1
+ }
+ XCTAssertGreaterThan(checked, 40)
+ let commit = try store.commit(head)
+ XCTAssertEqual(commit.parents.count, 1)
+ XCTAssertEqual(commit.message, "commit 11\n")
+ }
+
+ func testShallowThenIncrementalFetch() async throws {
+ let repo = try LocalGit.create()
+ try repo.write("a", "un\n")
+ try repo.commitAll("un")
+ try repo.write("b", "deux\n")
+ let second = try repo.commitAll("deux")
+
+ let store = MemoryObjectStore()
+ let client = GitClient(transport: LocalProcessTransport(repository: repo.directory), store: store)
+ var remote = try await client.refs()
+ let shallow = try await client.fetch(want: second, depth: 1, capabilities: remote.capabilities)
+ XCTAssertEqual(shallow, [second])
+ XCTAssertEqual(store.count, 4) // 1 commit, 1 arbre, 2 fichiers : pas d'historique
+
+ try repo.write("c", "trois\n")
+ let third = try repo.commitAll("trois")
+ remote = try await client.refs()
+ let again = try await client.fetch(want: third, have: [second], shallow: shallow, depth: 1, capabilities: remote.capabilities)
+ XCTAssertEqual(again, [third])
+ XCTAssertEqual(store.count, 7) // + 1 commit, 1 arbre, 1 fichier seulement
+ XCTAssertEqual(try store.tree(try store.commit(third).tree).map(\.name), ["a", "b", "c"])
+ }
+
+ func testPushCreatesAndUpdatesBranch() async throws {
+ let repo = try LocalGit.create(bare: true)
+ let store = MemoryObjectStore()
+ let client = GitClient(transport: LocalProcessTransport(repository: repo.directory), store: store)
+
+ let blob = GitObject(type: .blob, data: Array("version 3\n".utf8))
+ let tree = GitObject(type: .tree, data: Tree.serialize([.blob("00-Subsurface", blob.id)]))
+ let who = Commit.signature(name: "Test", email: "test@example.com", date: Date(timeIntervalSince1970: 1_700_000_000))
+ let first = GitObject(type: .commit, data: Commit(tree: tree.id, parents: [], author: who, committer: who, message: "premier\n").serialize())
+ try await client.push(ref: "refs/heads/jean@example.com", old: nil, new: first.id, objects: [blob, tree, first])
+ XCTAssertEqual(try repo.text(["rev-parse", "refs/heads/jean@example.com"]), first.id.hex)
+ XCTAssertEqual(try repo.text(["show", "jean@example.com:00-Subsurface"]), "version 3")
+ try repo.git(["fsck", "--strict"])
+
+ let blob2 = GitObject(type: .blob, data: Array("notes\n".utf8))
+ let sub = GitObject(type: .tree, data: Tree.serialize([.blob("Dive-1", blob2.id)]))
+ let tree2 = GitObject(type: .tree, data: Tree.serialize([.blob("00-Subsurface", blob.id), .tree("2024", sub.id)]))
+ let second = GitObject(type: .commit, data: Commit(tree: tree2.id, parents: [first.id], author: who, committer: who, message: "second\n").serialize())
+ try await client.push(ref: "refs/heads/jean@example.com", old: first.id, new: second.id, objects: [blob2, sub, tree2, second])
+ XCTAssertEqual(try repo.text(["log", "--format=%s", "jean@example.com"]), "second\npremier")
+ try repo.git(["fsck", "--strict"])
+
+ // Une mise à jour à partir d'un état périmé est refusée.
+ let third = GitObject(type: .commit, data: Commit(tree: tree.id, parents: [first.id], author: who, committer: who, message: "périmé\n").serialize())
+ do {
+ try await client.push(ref: "refs/heads/jean@example.com", old: first.id, new: third.id, objects: [third])
+ XCTFail("l'envoi aurait dû être refusé")
+ } catch let error as GitError {
+ guard case .pushRejected = error else { return XCTFail("\(error)") }
+ }
+ XCTAssertEqual(try repo.text(["rev-parse", "refs/heads/jean@example.com"]), second.id.hex)
+ }
+}
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/PlaceholderTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/PlaceholderTests.swift
@@ -0,0 +1,2 @@
+import XCTest
+final class PlaceholderTests: XCTestCase {}