subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

commit 8255e01cbf30bf2c0e48f03d878c0a2192f1179c
parent 467b82cf49c8d0ba1c381a9f2945feead017f43a
Author: Jean Schurger <jean@schurger.org>
Date:   Fri, 13 Nov 2026 15:32:14 -0500

Validate on real logbooks, keep empty lines, local demo logbook

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc

Diffstat:
MPackages/DiveKit/Sources/SubsurfaceLog/Changes.swift | 30++++++++++++++++++++++++++++--
MPackages/DiveKit/Sources/SubsurfaceLog/Repository.swift | 19+++++++++++++++++++
MPackages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift | 44+++++++++++++++++++++++++++++++++++++++++++-
3 files changed, 90 insertions(+), 3 deletions(-)

diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift @@ -102,8 +102,13 @@ public enum LogEditor { for field in DiveField.allCases { guard let value = fields[field] else { continue } let key = keyword(field) - let replacement = line(field, value).map { Array($0.utf8) } - if let index = lines.firstIndex(where: { $0.keyword == key }) { + var replacement = line(field, value).map { Array($0.utf8) } + let existing = lines.firstIndex(where: { $0.keyword == key }) + // Subsurface garde la ligne d'un texte vidé (« buddy "" ») : on fait pareil quand elle existe déjà. + if replacement == nil, existing != nil, [.divemaster, .buddy, .suit, .notes].contains(field) { + replacement = Array("\(key) \"\"\n".utf8) + } + if let index = existing { if let replacement { lines[index].bytes = replacement } else { @@ -142,6 +147,27 @@ public enum LogEditor { return try store.putTree(entries) } + /// Construit un arbre complet à partir de fichiers « chemin → contenu ». + public static func buildTree(files: [String: String], store: ObjectStore) throws -> ObjectID { + var blobs = [TreeEntry]() + var folders = [String: [String: String]]() + for (path, content) in files { + let parts = path.split(separator: "/", maxSplits: 1).map(String.init) + if parts.count == 1 { + blobs.append(.blob(parts[0], try store.putBlob(content))) + } else { + folders[parts[0], default: [:]][parts[1]] = content + } + } + for (name, inner) in folders { + blobs.append(.tree(name, try buildTree(files: inner, store: store))) + } + return try store.putTree(blobs) + } + + /// Chemin et nom du dossier d'une plongée ajoutée par l'app. + public static func diveDirectory(when: Int) -> String { divePath(when: when).joined(separator: "/") } + static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] static func divePath(when: Int) -> [String] { diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift @@ -131,6 +131,25 @@ public actor LogRepository { try save() } + /// Remplace le carnet local par un arbre construit sur place (mode démonstration, sans serveur). + public func importTree(files: [String: String]) throws { + let root = try LogEditor.buildTree(files: files, store: store) + let who = Commit.signature(name: authorName, email: authorEmail) + let commit = Commit(tree: root, parents: [], author: who, committer: who, message: "Carnet de démonstration\n") + state = State(head: try store.put(GitObject(type: .commit, data: commit.serialize()))) + try save() + } + + /// Intègre les modifications en attente au carnet local sans rien envoyer (mode démonstration). + public func commitPendingLocally() throws { + guard !state.pending.isEmpty, let root = try workingTree() else { return } + let who = Commit.signature(name: authorName, email: authorEmail) + let commit = Commit(tree: root, parents: state.head.map { [$0] } ?? [], author: who, committer: who, message: "Modifications locales\n") + state.head = try store.put(GitObject(type: .commit, data: commit.serialize())) + state.pending = [] + try save() + } + /// Efface la copie locale (déconnexion). public func erase() throws { state = State() diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift @@ -151,7 +151,9 @@ final class SubsurfaceLogTests: XCTestCase { let minimal = Array("duration 50:00 min\nbuddy \"Sam\"\ncylinder vol=11.1l\n".utf8) let edited = LogEditor.patch(diveFile: minimal, fields: [.buddy: "", .notes: "ok", .rating: "3", .site: "7f3a1b2c", .tags: "nuit, épave"]) XCTAssertEqual(String(decoding: edited, as: UTF8.self), - "duration 50:00 min\nrating 3\ntags \"nuit\", \"épave\"\ndivesiteid 7f3a1b2c\nnotes \"ok\"\ncylinder vol=11.1l\n") + "duration 50:00 min\nrating 3\ntags \"nuit\", \"épave\"\ndivesiteid 7f3a1b2c\nbuddy \"\"\nnotes \"ok\"\ncylinder vol=11.1l\n") + XCTAssertEqual(String(decoding: LogEditor.patch(diveFile: minimal, fields: [.rating: "0", .suit: ""]), as: UTF8.self), + "duration 50:00 min\nbuddy \"Sam\"\ncylinder vol=11.1l\n") } func testSyncEditsAndPush() async throws { @@ -301,6 +303,46 @@ final class SubsurfaceLogTests: XCTestCase { "00-Subsurface\n2025/01/02-Thu-03=04=05/Dive-1\n2025/01/02-Thu-03=04=05/Divecomputer") } + /// Validation sur un vrai carnet : SUBSURFACE_TREE = dossier disposé comme l'arbre git (00-Subsurface, 01-Divesites, aaaa/…). + func testExternalTree() async throws { + guard let path = ProcessInfo.processInfo.environment["SUBSURFACE_TREE"] else { + throw XCTSkip("SUBSURFACE_TREE non défini") + } + let work = try LocalGit.create(name: "external") + _ = try LocalGit.run(["-c", "core.quotepath=off", "init", "-q"], in: work.directory) + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/cp") + process.arguments = ["-R", path + "/.", work.directory.path] + try process.run() + process.waitUntilExit() + try work.commitAll("carnet externe") + let remote = try LocalGit.create(bare: true, name: "remote") + try work.git(["push", "-q", remote.directory.path, "main:refs/heads/\(Fixture.branch)"]) + let repo = try repository() + _ = try await repo.sync(transport: LocalProcessTransport(repository: remote.directory)) + let log = try await repo.logbook() + XCTAssertEqual(log.warnings, []) + XCTAssertGreaterThan(log.dives.count, 0) + var samples = 0 + for dive in log.dives { + let computers = try await repo.profile(of: dive) + samples += computers.reduce(0) { $0 + $1.samples.count } + let site = log.site(of: dive)?.name ?? "-" + print("#\(dive.number) \(dive.date) \(dive.durationSeconds / 60) min \(dive.maxDepth) m \(dive.waterTemperature.map { "\($0) °C" } ?? "-") [\(site)] \(dive.computers.map(\.model)) bouteilles=\(dive.cylinders.map { $0.gas.label }) binôme=\(dive.buddy) éch=\(computers.map(\.samples.count)) évén=\(computers.map(\.events.count))") + // Réécrire une plongée avec ses propres valeurs ne doit pas changer un octet. + let original = try repo.store.blob(try XCTUnwrap(dive.diveBlob)) + var same: [DiveField: String] = [.buddy: dive.buddy, .divemaster: dive.divemaster, .suit: dive.suit, .notes: dive.notes, + .rating: String(dive.rating), .visibility: String(dive.visibility), + .tags: dive.tags.joined(separator: ",")] + if let uuid = dive.siteUUID, original.count > 0, String(decoding: original, as: UTF8.self).contains("divesiteid") { + same[.site] = String(uuid, radix: 16) + } + XCTAssertEqual(String(decoding: LogEditor.patch(diveFile: original, fields: same), as: UTF8.self), + String(decoding: original, as: UTF8.self), "plongée \(dive.number)") + } + print("\(log.dives.count) plongées, \(log.sites.count) lieux, \(log.trips.count) voyages, \(samples) échantillons") + } + func testCloudAddresses() { XCTAssertEqual(SubsurfaceCloud.sanitize(email: " Jean.Test+plongee@Example.com\n"), "jean.test+plongee@example.com") XCTAssertEqual(SubsurfaceCloud.repositoryURL(email: "Jean@Example.com").absoluteString,