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

main.swift (13634B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 import GitLite
      4 import SubsurfaceLog
      5 
      6 // Verification tool, outside the app: the same code as on the iPhone, against the real Subsurface cloud.
      7 //   CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli list
      8 //   CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli import export.zip
      9 // The password is only ever passed through the environment, never as an argument.
     10 
     11 func fail(_ message: String) -> Never {
     12     FileHandle.standardError.write(Data((message + "\n").utf8))
     13     exit(1)
     14 }
     15 
     16 let arguments = CommandLine.arguments.dropFirst()
     17 let environment = ProcessInfo.processInfo.environment
     18 // "inspect" never touches the network: it shows what a file contains.
     19 if arguments.first == "inspect", let path = arguments.dropFirst().first {
     20     do {
     21         let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path))))
     22         print("\(dives.count) dives in the file")
     23         for dive in dives {
     24             let c = NaiveTime.components(dive.when)
     25             let date = String(format: "%04d-%02d-%02d %02d:%02d:%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
     26             let pressures = dive.samples.compactMap(\.pressure1)
     27             print("  \(date)  \(String(format: "%5.1f", dive.maxDepth)) m  \(String(format: "%3d", dive.durationSeconds / 60)) min  \(dive.model)  \(dive.gases.map(\.label).joined(separator: "+"))  \(dive.decoModel ?? "")  \(Int(pressures.first ?? 0))→\(Int(pressures.last ?? 0)) bar  samples=\(dive.samples.count)  site=\(dive.site.isEmpty ? "-" : dive.site)  buddy=\(dive.buddy.isEmpty ? "-" : dive.buddy)  notes=\(dive.notes.count)")
     28         }
     29         exit(0)
     30     } catch {
     31         fail("failed: \(error)")
     32     }
     33 }
     34 
     35 guard let command = arguments.first, let email = environment["CLOUD_EMAIL"], let password = environment["CLOUD_PASSWORD"] else {
     36     fail("""
     37         usage: CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli <command>
     38           list                                        dives of the cloud logbook
     39           table                                       whole logbook as a markdown table
     40           sites                                       dive sites as a markdown table
     41           import <file>                               import a file into the logbook and push
     42           apply <changes.json>                        apply a JSON array of changes and push
     43           locate <site> <latitude> <longitude>        set the position of a site
     44           merge <file> <from> <to> <number>           merge several immersions of a file into one dive
     45           check <file>                                what importing a file would do, without changing anything
     46           renumber-plan                               JSON list of the dives whose number differs from their rank in time
     47         usage: divelog-cli inspect <file>             show what a file contains (no network)
     48         """)
     49 }
     50 
     51 let account = SubsurfaceCloud.sanitize(email: email)
     52 let transport = SubsurfaceCloud.transport(email: account, password: password)
     53 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("divelog-cli-\(UUID().uuidString)")
     54 defer { try? FileManager.default.removeItem(at: directory) }
     55 
     56 func describe(_ log: Logbook) {
     57     print("\(log.dives.count) dives, \(log.sites.count) sites, \(log.trips.count) trips")
     58     for dive in log.dives {
     59         let c = NaiveTime.components(dive.when)
     60         let date = String(format: "%04d-%02d-%02d %02d:%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0)
     61         let site = log.site(of: dive)?.name ?? "-"
     62         let depth = String(format: "%.1f", dive.maxDepth)
     63         print("  #\(dive.number)  \(date)  \(depth) m  \(dive.durationSeconds / 60) min  \(site)  [\(dive.computerModel ?? "manual")]")
     64     }
     65     for warning in log.warnings { print("  ! \(warning)") }
     66 }
     67 
     68 do {
     69     let repository = try LogRepository(directory: directory, branch: account, authorName: "Sub Rascasse", authorEmail: account)
     70     _ = try await repository.sync(transport: transport)
     71     switch command {
     72     case "list":
     73         describe(try await repository.logbook())
     74     case "check":
     75         // check <file>: what importing each dive of the file would do to the cloud logbook; nothing is changed.
     76         guard let path = arguments.dropFirst().first else { fail("missing file to check") }
     77         let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path))))
     78         let found = try await repository.dispositions(of: dives)
     79         for dive in dives {
     80             let c = NaiveTime.components(dive.when)
     81             let date = String(format: "%04d-%02d-%02d %02d:%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0)
     82             let what: String
     83             switch found[dive.id] {
     84             case .duplicate(let existing): what = "already in the logbook (dive \(existing.number))"
     85             case .merge(let existing): what = "would join dive \(existing.number) as one more computer"
     86             case .new, nil: what = "new"
     87             }
     88             print("  \(date)  \(dive.durationSeconds / 60) min  \(what)")
     89         }
     90     case "renumber-plan":
     91         // Dives in chronological order should be numbered 1, 2, 3…: lists those that are not, with their notes,
     92         // so that a list of changes can be prepared and reviewed before `apply`.
     93         struct Entry: Encodable { let when: Int, number: Int, newNumber: Int, notes: String }
     94         let ordered = try await repository.logbook().dives.sorted { $0.when < $1.when }
     95         let entries = ordered.enumerated().compactMap { index, dive in
     96             dive.number == index + 1 ? nil : Entry(when: dive.when, number: dive.number, newNumber: index + 1, notes: dive.notes)
     97         }
     98         let encoder = JSONEncoder()
     99         encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
    100         print(String(decoding: try encoder.encode(entries), as: UTF8.self))
    101     case "import":
    102         guard let path = arguments.dropFirst().first else { fail("missing file to import") }
    103         let all = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path))))
    104         // As in the app: dips shorter than two minutes are left out.
    105         let dives = all.filter { $0.durationSeconds >= 120 }
    106         print("file: \(all.count) logs, of which \(all.count - dives.count) short dips ignored")
    107         try await repository.enqueue(.ensureSettings)
    108         let summary = try await repository.importDives(dives)
    109         print("added to the logbook: \(summary.added), merged into a dive already there: \(summary.merged) (already there: \(dives.count - summary.added - summary.merged))")
    110         let report = try await repository.sync(transport: transport)
    111         print("pushed: \(report.sent.count) changes, commit \(report.head?.hex ?? "-")")
    112         for dropped in report.dropped { print("  dropped: \(dropped)") }
    113         // Read back through a fresh clone, to see what the server really kept.
    114         let check = try LogRepository(directory: directory.appendingPathComponent("readback"), branch: account, authorName: "Sub Rascasse", authorEmail: account)
    115         _ = try await check.sync(transport: transport)
    116         describe(try await check.logbook())
    117     case "table":
    118         // The whole logbook as a markdown table, from the oldest dive to the most recent.
    119         // Two markers written in French in the notes of existing logbooks are data and are matched as is:
    120         // "Heure non écrite sur la fiche" (the time was not written on the paper sheet, so it is a guess) and
    121         // "Carnet papier N, page P (écrit n° X)" (provenance: paper logbook N, page P, written dive number X).
    122         let log = try await repository.logbook()
    123         func cell(_ text: String) -> String { text.replacingOccurrences(of: "|", with: "/").replacingOccurrences(of: "\n", with: " ") }
    124         print("| No. | Date | Time | Site | Depth | Duration | Water | Buddy | Guide | Source |")
    125         print("|---|---|---|---|---|---|---|---|---|---|")
    126         for dive in log.dives.reversed() {
    127             let c = NaiveTime.components(dive.when)
    128             let date = String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
    129             let time = String(format: "%02d:%02d", c.hour ?? 0, c.minute ?? 0)
    130             let guessed = dive.notes.contains("Heure non écrite")
    131             var source = dive.computerModel ?? "manual"
    132             if let range = dive.notes.range(of: "Carnet papier [0-9]+, page [0-9]+( \\(écrit n° [0-9]+\\))?", options: .regularExpression) {
    133                 source = String(dive.notes[range]).replacingOccurrences(of: "Carnet papier ", with: "paper log ").replacingOccurrences(of: ", page ", with: " p. ")
    134                     .replacingOccurrences(of: "(écrit n° ", with: "(written no. ")
    135             }
    136             let temp = dive.waterTemperature.map { String(format: "%.0f °C", $0) } ?? ""
    137             print("| \(dive.number) | \(date) | \(time)\(guessed ? " ?" : "") | \(cell(log.site(of: dive)?.name ?? "")) | \(String(format: "%.1f", dive.maxDepth)) m | \(dive.durationSeconds / 60) min | \(temp) | \(cell(dive.buddy)) | \(cell(dive.divemaster)) | \(cell(source)) |")
    138         }
    139     case "sites":
    140         let log = try await repository.logbook()
    141         var counts = [UInt32: Int]()
    142         for dive in log.dives { if let uuid = dive.siteUUID { counts[uuid, default: 0] += 1 } }
    143         print("| Site | Dives | Latitude | Longitude |")
    144         print("|---|---|---|---|")
    145         for site in log.sites.values.sorted(by: { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }) {
    146             print("| \(site.name) | \(counts[site.uuid] ?? 0) | \(site.latitude.map { String(format: "%.5f", $0) } ?? "") | \(site.longitude.map { String(format: "%.5f", $0) } ?? "") |")
    147         }
    148     case "apply":
    149         // Applies a list of changes (JSON array of LogChange) and pushes it.
    150         guard let path = arguments.dropFirst().first else { fail("missing changes file") }
    151         let changes = try JSONDecoder().decode([LogChange].self, from: try Data(contentsOf: URL(fileURLWithPath: path)))
    152         for change in changes { try await repository.enqueue(change) }
    153         let report = try await repository.sync(transport: transport)
    154         print("pushed: \(report.sent.count) changes out of \(changes.count), commit \(report.head?.hex ?? "-")")
    155         for dropped in report.dropped { print("  dropped: \(dropped)") }
    156         describe(try await repository.logbook())
    157     case "merge":
    158         // merge <file> <from> <to> <number>: merges into one dive the immersions of the file that started between
    159         // two times (seconds, naive time). Those the logbook does not have yet are imported first, then the dives
    160         // are merged the way the app does it (LogRepository.mergeDives) and the result takes the number given.
    161         let rest = Array(arguments.dropFirst())
    162         guard rest.count == 4, let from = Int(rest[1]), let to = Int(rest[2]), let number = Int(rest[3]) else { fail("usage: merge <file> <from> <to> <number>") }
    163         let parts = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: rest[0])))).filter { $0.when >= from && $0.when <= to }
    164         guard parts.count > 1 else { fail("at least two immersions are needed in this interval") }
    165         try await repository.importDives(parts)
    166         let before = try await repository.logbook()
    167         var dives = [Dive]()
    168         for part in parts {
    169             switch DiveMerge.disposition(of: part, among: before.dives) {
    170             case .duplicate(let dive), .merge(let dive): if !dives.contains(where: { $0.id == dive.id }) { dives.append(dive) }
    171             case .new: break
    172             }
    173         }
    174         guard let target = dives.min(by: { ($0.when, $0.number) < ($1.when, $1.number) }) else { fail("these immersions did not reach the logbook") }
    175         // A single dive: importing was enough (the immersions joined a dive that was already there).
    176         if dives.count > 1 { try await repository.mergeDives(dives) }
    177         if target.number != number {
    178             try await repository.enqueue(.renumberDive(when: target.when, number: target.number, newNumber: number))
    179         }
    180         let report = try await repository.sync(transport: transport)
    181         let merged = try await repository.logbook().dive(when: target.when, number: number)
    182         print("\(dives.count) dives merged: \((merged?.durationSeconds ?? 0) / 60) min underwater, \(merged?.maxDepth ?? 0) m; pushed \(report.sent.count) changes, commit \(report.head?.hex ?? "-")")
    183         describe(try await repository.logbook())
    184     case "locate":
    185         // locate "Site name" latitude longitude
    186         let rest = Array(arguments.dropFirst())
    187         guard rest.count == 3, let latitude = Double(rest[1]), let longitude = Double(rest[2]) else { fail("usage: locate <site> <latitude> <longitude>") }
    188         let log = try await repository.logbook()
    189         guard let site = log.sites.values.first(where: { $0.name.compare(rest[0], options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) else {
    190             fail("site not found: \(rest[0])")
    191         }
    192         try await repository.enqueue(.locateSite(uuid: site.uuid, latitude: latitude, longitude: longitude))
    193         let report = try await repository.sync(transport: transport)
    194         print("\(site.name): position pushed (\(report.sent.count) change), commit \(report.head?.hex ?? "-")")
    195     default:
    196         fail("unknown command: \(command)")
    197     }
    198 } catch {
    199     fail("failed: \(error)")
    200 }