Merge.swift (32193B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import GitLite 4 5 /// A dive of the logbook, the way changes point at it. 6 public struct DiveRef: Codable, Sendable, Equatable, Hashable { 7 public var when: Int 8 public var number: Int 9 10 public init(when: Int, number: Int) { 11 self.when = when 12 self.number = number 13 } 14 } 15 16 /// Rules for dives recorded by several dive computers. A merged dive is ONE dive with several dive computers, as 17 /// Subsurface stores it (`Divecomputer-001`, `Divecomputer-002`…): the first one is the primary computer, whose 18 /// profile and values are shown by default. 19 /// 20 /// What is written here was checked against the Subsurface sources (`core/save-git.cpp`, `core/load-git.cpp`, 21 /// `core/dive.cpp`, `core/divecomputer.cpp`, `core/event.cpp`, master of 2026-11-14): 22 /// - File names: `save_one_dive` numbers the computers from 1 when there are several and passes 0 for a single 23 /// one; `save_one_divecomputer` formats `"Divecomputer%c%03u"` with the dash only for a non-zero index, hence 24 /// `Divecomputer`, or `Divecomputer-001`, `Divecomputer-002`… `walk_tree_file` reads them in the order of the git 25 /// tree (the "Dive" file sorts before them) and `create_new_dc` appends each one: the first file is `dcs[0]`. 26 /// - Start of a computer: `save_dc` calls `show_date` (`date %04u-%02u-%02u`, `time %02u:%02u:%02u`) when 27 /// `dc.when != dive.when`, after `model`, `lastmanualtime`, `deviceid`, `diveid` and before `duration`; 28 /// `create_new_dc` starts from the dive's time and `parse_dc_date` / `parse_dc_time` override it. 29 /// - Duration: `create_dive_buffer` writes the `duration` of the "Dive" file from `dcs[0].duration`, and `save_dc` 30 /// gives a computer its own `duration` line when it differs from that. On load both are recomputed anyway: 31 /// `fixup_dc_duration` from the samples (surface segments left out) and `fixup_duration` as the longest of the 32 /// computers. Depths and temperatures live in the computer files and are likewise recomputed (`fixup_dive`). 33 /// - Cylinders: a gas change says `cylinder=N`, the zero-based index of the cylinder in the "Dive" file 34 /// (`save_one_event`, `parse_event_keyvalue`); `flags` holds the same index plus one as an older extension 35 /// (`event::event`). A pressure `…bar:N` names a sensor (`save_sample`, `parse_sample_unit`); sensor N is 36 /// cylinder N unless the computer has `tanksensormapping "sensor" "cylinder"` lines (`save_tank_sensor_mappings`, 37 /// `get_tank_sensor_mappings_for_storage`, where sensor -1 only says "no mapping"). 38 /// - Subsurface's own merge (`dive::create_merged_dive`) joins profiles on one timeline for the same device at 39 /// another time (`interleave_dive_computers`) and keeps different computers side by side 40 /// (`join_dive_computers`); `LogEditor.merged` does the same. 41 public enum DiveMerge { 42 /// Place of a dive computer in a merged dive, lowest first: Open Rémora (the primary computer), then any other 43 /// dive computer (a Petrel…), then Open Mérou, then the made-up profile of a dive entered by hand. 44 public static func rank(model: String) -> Int { 45 let name = model.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) 46 if name.hasPrefix("open remora") { return 0 } 47 if name.hasPrefix("open merou") { return 2 } 48 if name == "manually added dive" { return 3 } 49 return 1 50 } 51 52 /// Same model, and serial numbers that do not contradict each other (a missing one matches anything; the same 53 /// number is written in hexadecimal by some sources and in decimal by others). 54 public static func sameComputer(model: String, serial: String, as otherModel: String, serial otherSerial: String) -> Bool { 55 func fold(_ text: String) -> String { 56 text.trimmingCharacters(in: .whitespaces).folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) 57 } 58 guard fold(model) == fold(otherModel) else { return false } 59 let a = String(fold(serial).drop { $0 == "0" }), b = String(fold(otherSerial).drop { $0 == "0" }) 60 if a.isEmpty || b.isEmpty || a == b { return true } 61 if let hex = Int(a, radix: 16), hex == Int(b) { return true } 62 if let hex = Int(b, radix: 16), hex == Int(a) { return true } 63 return false 64 } 65 66 /// Seconds shared by two time ranges; nil when they do not meet (ranges that just touch share 0 seconds). 67 public static func overlap(_ a: ClosedRange<Int>, _ b: ClosedRange<Int>) -> Int? { 68 let shared = min(a.upperBound, b.upperBound) - max(a.lowerBound, b.lowerBound) 69 return shared >= 0 ? shared : nil 70 } 71 72 public enum Disposition: Equatable, Sendable { 73 /// No dive of the logbook at that time: the dive is added. 74 case new 75 /// The logbook already has this dive from this very computer: nothing to do. 76 case duplicate(Dive) 77 /// The logbook has a dive at that time, recorded by something else: the incoming dive joins it as one more 78 /// dive computer. 79 case merge(Dive) 80 } 81 82 /// What importing `incoming` does to a logbook holding `dives`. 83 /// 84 /// The rule is the overlap of the [start, end] ranges, not the start time: each device notices the submersion 85 /// at its own moment. Among several overlapping dives, the one sharing the most time wins. A computer already 86 /// on an overlapping dive (same model and serial, its own recording overlapping too) makes it a re-import. 87 public static func disposition(of incoming: ImportedDive, among dives: [Dive]) -> Disposition { 88 let range = incoming.when...(incoming.when + max(incoming.durationSeconds, incoming.samples.last?.time ?? 0, 0)) 89 var best: (dive: Dive, shared: Int)? 90 for dive in dives { 91 guard let shared = overlap(range, dive.timeRange) else { continue } 92 for computer in dive.computers 93 where sameComputer(model: computer.model, serial: computer.serial, as: incoming.model, serial: incoming.serial) 94 && overlap(range, computer.timeRange(in: dive)) != nil { 95 return .duplicate(dive) 96 } 97 if let current = best, (current.shared, -abs(current.dive.when - incoming.when)) >= (shared, -abs(dive.when - incoming.when)) { continue } 98 best = (dive, shared) 99 } 100 return best.map { .merge($0.dive) } ?? .new 101 } 102 } 103 104 /// A "Divecomputer" file handled as text: merging moves computers between dives without decoding them, so the 105 /// lines this app does not know about survive, and a file that needs no change keeps its bytes (and its git blob). 106 struct ComputerFile { 107 struct Line { 108 var keyword: String 109 var bytes: [UInt8] 110 } 111 112 /// The file as it was read, until something changes it. 113 private var original: [UInt8]? 114 private(set) var header: [Line] = [] 115 private(set) var events: [[UInt8]] = [] 116 private(set) var samples: [[UInt8]] = [] 117 private(set) var model = "" 118 private(set) var serial = "" 119 /// Start of the recording, naive local time. 120 private(set) var start: Int 121 /// Dive time: the `duration` line, else the time of the last sample, else the duration of the dive it came with. 122 private(set) var duration: Int 123 private var hasOwnStart = false 124 125 init(_ data: [UInt8], diveWhen: Int, diveDuration: Int) { 126 original = data 127 start = diveWhen 128 var date: [Int]?, time: [Int]?, explicit: Int? 129 for line in LogFormat.lines(data) { 130 var bytes = Array(data[line.range]) 131 if bytes.last != 0x0a { bytes.append(0x0a) } 132 guard let first = bytes.first else { continue } 133 if first == 0x20 || (first >= 0x30 && first <= 0x39) { 134 samples.append(bytes) 135 continue 136 } 137 let keyword = String(line.keyword) 138 if keyword == "event" { 139 events.append(bytes) 140 continue 141 } 142 header.append(Line(keyword: keyword, bytes: bytes)) 143 switch keyword { 144 case "model": model = line.strings.first ?? "" 145 case "keyvalue": if line.strings.count == 2, line.strings[0] == "Serial" { serial = line.strings[1] } 146 case "date": date = line.argument.split(separator: "-").compactMap { Int($0) } 147 case "time": time = line.argument.split(separator: ":").compactMap { Int($0) } 148 case "duration": explicit = LogFormat.duration(line.argument) 149 default: break 150 } 151 } 152 if date?.count == 3 || time?.count == 3 { 153 let base = NaiveTime.components(diveWhen) 154 let d = date?.count == 3 ? date! : [base.year!, base.month!, base.day!] 155 let t = time?.count == 3 ? time! : [base.hour!, base.minute!, base.second!] 156 if let own = NaiveTime.timestamp(year: d[0], month: d[1], day: d[2], hour: t[0], minute: t[1], second: t[2]) { 157 start = own 158 hasOwnStart = true 159 } 160 } 161 duration = diveDuration 162 duration = explicit ?? lastSampleTime ?? diveDuration 163 } 164 165 var bytes: [UInt8] { 166 original ?? (header.flatMap(\.bytes) + events.flatMap { $0 } + samples.flatMap { $0 }) 167 } 168 169 var lastSampleTime: Int? { samples.last.map(Self.sampleTime) } 170 /// End of the recording (a profile joined from several immersions lasts longer than its dive time). 171 var end: Int { start + max(duration, lastSampleTime ?? 0) } 172 173 // MARK: Lines 174 175 private static func text(_ bytes: [UInt8]) -> String { 176 var text = String(decoding: bytes, as: UTF8.self) 177 if text.hasSuffix("\n") { text.removeLast() } 178 return text 179 } 180 181 /// " 1:30 12.0m …": the time, in seconds. 182 static func sampleTime(_ line: [UInt8]) -> Int { 183 let trimmed = text(line).drop { $0 == " " } 184 return LogFormat.duration(trimmed.prefix { $0 != " " }) 185 } 186 187 private static func sample(_ line: [UInt8], shiftedBy offset: Int) -> [UInt8] { 188 let trimmed = text(line).drop { $0 == " " } 189 let token = trimmed.prefix { $0 != " " } 190 let time = LogFormat.duration(token) + offset 191 return Array("\(String(format: "%3d:%02d", time / 60, time % 60))\(trimmed.dropFirst(token.count))\n".utf8) 192 } 193 194 /// "event 12:10 type=3 …" 195 private static func event(_ line: [UInt8], shiftedBy offset: Int) -> [UInt8] { 196 let rest = text(line).dropFirst("event".count).drop { $0 == " " } 197 let token = rest.prefix { $0 != " " } 198 return Array("event \(LogFormat.minutes(LogFormat.duration(token) + offset))\(rest.dropFirst(token.count))\n".utf8) 199 } 200 201 /// Last value written for a key of the samples (they only say what changes). 202 private func lastSampleValue(_ key: String) -> Substring? { 203 let prefix = key + "=" 204 for line in samples.reversed() { 205 for token in Self.text(line).split(separator: " ") where token.hasPrefix(prefix) { 206 return token.dropFirst(prefix.count) 207 } 208 } 209 return nil 210 } 211 212 private func headerNumber(_ keyword: String) -> Double? { 213 header.first { $0.keyword == keyword }.map { LogFormat.number(Self.text($0.bytes).dropFirst(keyword.count)) } 214 } 215 216 private mutating func setHeader(_ keyword: String, _ line: String, before: Set<String> = []) { 217 let bytes = Array((line + "\n").utf8) 218 if let index = header.firstIndex(where: { $0.keyword == keyword }) { 219 header[index].bytes = bytes 220 } else { 221 // Subsurface writes: model, lastmanualtime, deviceid, diveid, date, time, duration, then the rest. 222 let index = before.isEmpty ? header.count : (header.firstIndex { !before.contains($0.keyword) } ?? header.count) 223 header.insert(Line(keyword: keyword, bytes: bytes), at: index) 224 } 225 original = nil 226 } 227 228 // MARK: Changes 229 230 /// A computer that did not start with the dive it now belongs to says when it did (`date` and `time` lines). 231 mutating func anchor(toDiveAt diveWhen: Int) { 232 guard start != diveWhen, !hasOwnStart else { return } 233 let c = NaiveTime.components(start) 234 let identity: Set<String> = ["model", "lastmanualtime", "deviceid", "diveid"] 235 setHeader("date", String(format: "date %04d-%02d-%02d", c.year!, c.month!, c.day!), before: identity) 236 setHeader("time", String(format: "time %02d:%02d:%02d", c.hour!, c.minute!, c.second!), before: identity.union(["date"])) 237 hasOwnStart = true 238 } 239 240 /// The cylinders of a dive are numbered in its "Dive" file; a computer moved to another dive follows the new 241 /// numbers: in its gas changes, and for its pressure sensors either in its `tanksensormapping` lines or, without 242 /// any (sensor N is then cylinder N), in the samples themselves. 243 mutating func remapCylinders(_ map: [Int: Int]) { 244 guard map.contains(where: { $0.key != $0.value }) else { return } 245 let mapped = header.contains { $0.keyword == "tanksensormapping" } 246 header = header.map { line in 247 guard line.keyword == "tanksensormapping", let strings = LogFormat.lines(line.bytes).first?.strings, strings.count == 2, 248 let sensor = Int(strings[0]), sensor >= 0, let old = Int(strings[1]), let new = map[old] else { return line } 249 return Line(keyword: line.keyword, bytes: Array("tanksensormapping \"\(sensor)\" \"\(new)\"\n".utf8)) 250 } 251 events = events.map { line in 252 let text = Self.text(line) 253 let isGasChange = text.contains("name=\"gaschange") 254 let tokens = text.split(separator: " ", omittingEmptySubsequences: false).map { token -> String in 255 if token.hasPrefix("cylinder="), let old = Int(token.dropFirst(9)), let new = map[old] { return "cylinder=\(new)" } 256 // Older files carry the cylinder in the flags of a gas change, counted from 1. 257 if isGasChange, token.hasPrefix("flags="), let old = Int(token.dropFirst(6)), old > 0, let new = map[old - 1] { return "flags=\(new + 1)" } 258 return String(token) 259 } 260 return Array((tokens.joined(separator: " ") + "\n").utf8) 261 } 262 samples = samples.map { line in 263 let text = Self.text(line) 264 guard !mapped, text.contains("bar") || text.contains("sensor=") else { return line } 265 let tokens = text.split(separator: " ", omittingEmptySubsequences: false).map { token -> String in 266 // Old files: "sensor=N" sets the sensor of the pressures that follow, and a bare "bar" is sensor 0. 267 if token.hasPrefix("sensor="), let old = Int(token.dropFirst(7)), let new = map[old] { return "sensor=\(new)" } 268 if token.hasSuffix("bar"), !token.contains("="), !text.contains("sensor="), let new = map[0], new != 0 { return "\(token):\(new)" } 269 guard let marker = token.range(of: "bar:"), let old = Int(token[marker.upperBound...]), let new = map[old] else { return String(token) } 270 return "\(token[..<marker.upperBound])\(new)" 271 } 272 return Array((tokens.joined(separator: " ") + "\n").utf8) 273 } 274 original = nil 275 } 276 277 /// Joins a later immersion recorded by the same computer: the profiles follow one another on the same timeline, 278 /// separated by their surface interval, like Subsurface's merge. The dive time is the time spent underwater. 279 mutating func append(_ next: ComputerFile) { 280 let offset = next.start - start 281 var last = lastSampleTime 282 if let surfaced = last, let first = next.samples.first.map(Self.sampleTime) { 283 // Back to the surface after this immersion, then at the surface until the next one starts. Samples only 284 // say what changes: what the deco state was is cleared, so that it does not leak into the next immersion. 285 var resets = "" 286 if let tts = lastSampleValue("tts"), LogFormat.duration(tts) != 0 { resets += " tts=0:00" } 287 if let deco = lastSampleValue("in_deco"), LogFormat.integer(deco) != 0 { resets += " in_deco=0" } 288 if let time = lastSampleValue("stoptime"), LogFormat.duration(time) != 0 { resets += " stoptime=0:00" } 289 if let depth = lastSampleValue("stopdepth"), LogFormat.number(depth) != 0 { resets += " stopdepth=0.0m" } 290 let up = surfaced + 10 291 let down = max(up + 10, offset) 292 for (time, extra) in [(up, resets), (down, "")] where time < offset + first { 293 samples.append(Array((String(format: "%3d:%02d", time / 60, time % 60) + " 0.0m" + extra + "\n").utf8)) 294 last = time 295 } 296 } 297 for line in next.samples { 298 let time = Self.sampleTime(line) + offset 299 if let last, time <= last { continue } 300 samples.append(Self.sample(line, shiftedBy: offset)) 301 last = time 302 } 303 events += next.events.map { Self.event($0, shiftedBy: offset) } 304 305 if let a = headerNumber("maxdepth"), let b = next.headerNumber("maxdepth") { 306 setHeader("maxdepth", "maxdepth \(LogFormat.milli(max(a, b)))m") 307 } 308 if let a = headerNumber("meandepth"), let b = next.headerNumber("meandepth"), duration + next.duration > 0 { 309 let mean = (a * Double(duration) + b * Double(next.duration)) / Double(duration + next.duration) 310 setHeader("meandepth", "meandepth \(LogFormat.milli(mean))m") 311 } 312 if let a = headerNumber("watertemp"), let b = next.headerNumber("watertemp") { 313 setHeader("watertemp", "watertemp \(LogFormat.milli(min(a, b)))°C") 314 } 315 for line in next.header where line.keyword == "keyvalue" && !header.contains(where: { $0.bytes == line.bytes }) { 316 header.append(line) 317 } 318 duration += next.duration 319 setHeader("duration", "duration \(LogFormat.minutes(duration)) min", before: ["model", "lastmanualtime", "deviceid", "diveid", "date", "time"]) 320 original = nil 321 } 322 } 323 324 /// What makes a dive in the git tree, as text. 325 struct DiveParts { 326 var when: Int 327 var diveFile: [UInt8] 328 var computers: [ComputerFile] 329 } 330 331 extension LogEditor { 332 private struct FileLine { 333 var keyword: String 334 var line: LogLine 335 var bytes: [UInt8] 336 337 init?(_ bytes: [UInt8]) { 338 guard let line = LogFormat.lines(bytes).first else { return nil } 339 self.keyword = String(line.keyword) 340 self.line = line 341 self.bytes = bytes.last == 0x0a ? bytes : bytes + [0x0a] 342 } 343 344 var text: String? { line.strings.first } 345 var pairs: [(key: String, value: String)] { LogFormat.keyValues(line.argument, strings: line.strings) } 346 var gas: GasMix { 347 var gas = GasMix() 348 for (key, value) in pairs { 349 if key == "o2" { gas.o2Permille = Int((LogFormat.number(value) * 10).rounded()) } 350 if key == "he" { gas.hePermille = Int((LogFormat.number(value) * 10).rounded()) } 351 } 352 return gas 353 } 354 } 355 356 private static func fileLines(_ data: [UInt8]) -> [FileLine] { 357 LogFormat.lines(data).compactMap { FileLine(Array(data[$0.range])) } 358 } 359 360 /// Fills the gaps of a "Dive" file from the one of a dive merged into it. Nothing of the target changes; the 361 /// source brings what the target lacks: a field that is missing or empty, its notes (appended), its tags and 362 /// buddies (added to the lists), its cylinders (matched by gas mix, else added) and any line the target has no 363 /// equivalent of. Returns the file and where each cylinder of the source ended up. 364 static func fill(diveFile target: [UInt8], from source: [UInt8]) -> (file: [UInt8], cylinders: [Int: Int]) { 365 var lines = fileLines(target) 366 func rank(_ keyword: String) -> Int { order.firstIndex(of: keyword) ?? order.count } 367 func insert(_ line: FileLine) { 368 lines.insert(line, at: lines.firstIndex { rank($0.keyword) > rank(line.keyword) } ?? lines.count) 369 } 370 func set(_ keyword: String, _ text: String?) { 371 guard let text, let line = FileLine(Array(text.utf8)) else { return } 372 if let index = lines.firstIndex(where: { $0.keyword == keyword }) { lines[index] = line } else { insert(line) } 373 } 374 func names(_ text: String) -> [String] { 375 text.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } 376 } 377 func union(_ a: [String], _ b: [String]) -> [String] { 378 a + b.filter { new in !a.contains { $0.compare(new, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame } } 379 } 380 let hadWeights = lines.contains { $0.keyword == "weightsystem" } 381 let hadSite = lines.contains { ["divesiteid", "location", "gps"].contains($0.keyword) } 382 var cylinders = [Int: Int]() 383 var taken = Set<Int>() 384 var sourceCylinder = 0 385 386 for line in fileLines(source) { 387 let existing = lines.first { $0.keyword == line.keyword } 388 switch line.keyword { 389 case "duration": 390 break 391 case "cylinder": 392 let slots = lines.indices.filter { lines[$0].keyword == "cylinder" } 393 let gas = line.gas 394 if let slot = slots.indices.first(where: { !taken.contains($0) && (lines[slots[$0]].gas == gas || (lines[slots[$0]].gas.isAir && gas.isAir)) }) { 395 // Same gas: the same cylinder. The richer description wins when it only adds to the other. 396 let known = Set(lines[slots[slot]].pairs.map(\.key)), offered = Set(line.pairs.map(\.key)) 397 if known.isStrictSubset(of: offered) { lines[slots[slot]] = line } 398 cylinders[sourceCylinder] = slot 399 taken.insert(slot) 400 } else { 401 insert(line) 402 cylinders[sourceCylinder] = slots.count 403 taken.insert(slots.count) 404 } 405 sourceCylinder += 1 406 case "weightsystem": 407 if !hadWeights { insert(line) } 408 case "notes": 409 let mine = existing?.text ?? "", theirs = line.text ?? "" 410 if mine.isEmpty { set("notes", LogEditor.line(.notes, theirs)) } 411 else if !theirs.isEmpty, !mine.contains(theirs) { set("notes", LogEditor.line(.notes, mine + "\n" + theirs)) } 412 case "tags": 413 set("tags", LogEditor.line(.tags, union(existing?.line.strings ?? [], line.line.strings).joined(separator: ","))) 414 case "buddy", "divemaster": 415 let all = union(names(existing?.text ?? ""), names(line.text ?? "")) 416 if !all.isEmpty { set(line.keyword, "\(line.keyword) \(LogFormat.quote(all.joined(separator: ", ")))\n") } 417 case "divesiteid", "location", "gps": 418 // One site per dive, whatever the way it is written. 419 if !hadSite { insert(line) } 420 default: 421 if let existing { 422 if existing.line.strings == [""], let index = lines.firstIndex(where: { $0.keyword == line.keyword }) { lines[index] = line } 423 } else { 424 insert(line) 425 } 426 } 427 } 428 return (lines.flatMap(\.bytes), cylinders) 429 } 430 431 static func duration(ofDiveFile data: [UInt8]) -> Int { 432 LogFormat.lines(data).first { $0.keyword == "duration" }.map { LogFormat.duration($0.argument) } ?? 0 433 } 434 435 static func setting(duration seconds: Int, inDiveFile data: [UInt8]) -> [UInt8] { 436 var lines = fileLines(data) 437 guard let line = FileLine(Array("duration \(LogFormat.minutes(seconds)) min\n".utf8)) else { return data } 438 if let index = lines.firstIndex(where: { $0.keyword == "duration" }) { lines[index] = line } else { lines.insert(line, at: 0) } 439 return lines.flatMap(\.bytes) 440 } 441 442 /// Merges dives into `target`, which keeps its date, number, site, notes and everything else it has; the others 443 /// fill its gaps (see `fill`). Every dive computer is kept: the same computer on successive immersions becomes 444 /// one profile on one timeline, different computers stay side by side, ordered by `DiveMerge.rank`. The 445 /// duration of the dive is the one of its first computer, as Subsurface writes it. 446 static func merged(_ target: DiveParts, with others: [DiveParts]) -> (diveFile: [UInt8], computers: [[UInt8]]) { 447 var file = target.diveFile 448 var computers = [ComputerFile]() 449 func add(_ computer: ComputerFile) { 450 for index in computers.indices 451 where DiveMerge.sameComputer(model: computers[index].model, serial: computers[index].serial, as: computer.model, serial: computer.serial) { 452 if computers[index].end < computer.start { 453 computers[index].append(computer) 454 return 455 } 456 if computer.end < computers[index].start { 457 var earlier = computer 458 earlier.append(computers[index]) 459 computers[index] = earlier 460 return 461 } 462 } 463 computers.append(computer) 464 } 465 target.computers.forEach(add) 466 for other in others.sorted(by: { $0.when < $1.when }) { 467 let filled = fill(diveFile: file, from: other.diveFile) 468 file = filled.file 469 for var computer in other.computers { 470 computer.remapCylinders(filled.cylinders) 471 add(computer) 472 } 473 } 474 // The existing order is kept among computers of the same rank. 475 var ordered = computers.enumerated().sorted { 476 (DiveMerge.rank(model: $0.element.model), $0.offset) < (DiveMerge.rank(model: $1.element.model), $1.offset) 477 }.map(\.element) 478 for index in ordered.indices { ordered[index].anchor(toDiveAt: target.when) } 479 if let primary = ordered.first, primary.duration > 0 { file = setting(duration: primary.duration, inDiveFile: file) } 480 return (file, ordered.map(\.bytes)) 481 } 482 483 // MARK: In the tree 484 485 private static func isComputer(_ entry: TreeEntry) -> Bool { !entry.isTree && entry.name.hasPrefix("Divecomputer") } 486 private static func isDiveFile(_ entry: TreeEntry) -> Bool { !entry.isTree && LogWalker.diveNumber(fileName: entry.name) != nil } 487 488 static func parts(of directory: DiveDirectory, store: ObjectStore) throws -> DiveParts { 489 let entries = try store.tree(directory.tree) 490 let file = try entries.first(where: isDiveFile).map { try store.blob($0.id) } ?? [] 491 let duration = duration(ofDiveFile: file) 492 let computers = try entries.filter(isComputer).map { 493 ComputerFile(try store.blob($0.id), diveWhen: directory.when, diveDuration: duration) 494 } 495 return DiveParts(when: directory.when, diveFile: file, computers: computers) 496 } 497 498 /// Rewrites the directory of `target` as the merge of it and `others`: its "Dive" file keeps its name (hence 499 /// its number), the computers are renumbered `Divecomputer-001…` (a single one is plain `Divecomputer`), and 500 /// whatever else the directories hold (pictures) is kept. 501 static func merging(_ others: [DiveParts], extra: [TreeEntry] = [], into target: DiveDirectory, root: ObjectID, store: ObjectStore) throws -> ObjectID? { 502 let entries = try store.tree(target.tree) 503 let result = merged(try parts(of: target, store: store), with: others) 504 let fileName = entries.first(where: isDiveFile)?.name ?? "Dive" 505 var kept = entries.filter { !isComputer($0) && $0.name != fileName } 506 kept += extra.filter { new in !isComputer(new) && !isDiveFile(new) && !kept.contains { $0.name == new.name } } 507 kept.append(.blob(fileName, try store.put(GitObject(type: .blob, data: result.diveFile)))) 508 for (index, bytes) in result.computers.enumerated() { 509 let name = result.computers.count == 1 ? "Divecomputer" : String(format: "Divecomputer-%03d", index + 1) 510 kept.append(.blob(name, try store.put(GitObject(type: .blob, data: bytes)))) 511 } 512 return try replacing(root: root, path: target.path, with: .tree(target.path.last!, try store.putTree(kept)), store: store) 513 } 514 515 /// What importing a dive does to the logbook at `root` (see `DiveMerge.disposition`), with the directory of the 516 /// dive it meets. Only the dives around that time are read, profiles included, to know when each computer stopped. 517 static func disposition(of dive: ImportedDive, root: ObjectID, store: ObjectStore) throws -> (DiveMerge.Disposition, DiveDirectory?) { 518 let end = dive.when + max(dive.durationSeconds, dive.samples.last?.time ?? 0) 519 let near = try LogWalker.diveDirectories(root: root, store: store).filter { $0.when <= end && $0.when >= dive.when - 2 * 86_400 } 520 var scratch = Logbook() 521 let dives = near.compactMap { try? LogLoader.loadDive($0, store: store, log: &scratch, withSamples: true) } 522 let disposition = DiveMerge.disposition(of: dive, among: dives) 523 switch disposition { 524 case .new: return (disposition, nil) 525 case .duplicate(let found), .merge(let found): return (disposition, near.first { $0.path == found.path }) 526 } 527 } 528 529 /// `.importDive`: a new directory, or one more computer on the dive already there at that time. 530 static func importing(_ dive: ImportedDive, number: Int, siteUUID: UInt32?, root: ObjectID, store: ObjectStore) throws -> ObjectID? { 531 let diveText = diveFile(dive, siteUUID: siteUUID) 532 let computerText = computerFile(dive) 533 switch try disposition(of: dive, root: root, store: store) { 534 case (.duplicate, _): 535 throw ChangeError.diveAlreadyExists(dive.when) 536 case (.merge, let directory?): 537 let computer = ComputerFile(Array(computerText.utf8), diveWhen: dive.when, diveDuration: dive.durationSeconds) 538 let incoming = DiveParts(when: dive.when, diveFile: Array(diveText.utf8), computers: [computer]) 539 return try merging([incoming], into: directory, root: root, store: store) 540 default: 541 let name = number > 0 ? "Dive-\(number)" : "Dive" 542 let tree = try store.putTree([.blob(name, try store.putBlob(diveText)), .blob("Divecomputer", try store.putBlob(computerText))]) 543 let path = divePath(when: dive.when) 544 return try replacing(root: root, path: path, with: .tree(path.last!, tree), store: store) 545 } 546 } 547 548 /// `.mergeDives`: the other dives join the target and their directories go away. Dives that are no longer 549 /// there are left out; with none of them left there is nothing to merge. 550 static func merging(_ others: [DiveRef], into target: DiveRef, root: ObjectID, store: ObjectStore) throws -> ObjectID? { 551 guard let directory = try LogWalker.find(when: target.when, number: target.number, root: root, store: store) else { 552 throw ChangeError.diveNotFound(target.when) 553 } 554 var sources = [DiveDirectory]() 555 for other in others { 556 guard let found = try LogWalker.find(when: other.when, number: other.number, root: root, store: store), 557 found.path != directory.path, !sources.contains(where: { $0.path == found.path }) else { continue } 558 sources.append(found) 559 } 560 guard !sources.isEmpty else { throw ChangeError.diveNotFound(others.first?.when ?? target.when) } 561 let extra = try sources.flatMap { try store.tree($0.tree) } 562 var result = try merging(try sources.map { try parts(of: $0, store: store) }, extra: extra, into: directory, root: root, store: store) 563 for source in sources { 564 result = try replacing(root: result, path: source.path, with: nil, store: store) 565 } 566 return result 567 } 568 }