123456789module sync1011import compress.zlib12import os13import src.apply14import src.events15import src.history16import src.remote17import src.snapshot18import src.storage1920pub enum Side {21 mine22 theirs23}24252627pub struct Clash {28pub mut:29 path string30 mine snapshot.FileEntry31 theirs snapshot.FileEntry32 base snapshot.FileEntry33 stat string34}3536pub struct StealOptions {37pub mut:38 mine bool 39 theirs bool 40 41 ask fn (clash Clash) Side = unsafe { nil }42}4344pub struct StealReport {45pub mut:46 repo string47 forward bool48 fetched_saves int49 fetched_objects int50 fetched_events int51 clashes []string52 kept_mine int53 replayed int54 removed int55 head string56 flagged []events.Flag 57}5859pub const dirty_tree = 'save or checkpoint first — steal needs a clean tree'60pub const no_saves_here = 'this folder has files but no saves — steal a repo into an empty folder with "koh steal <name>"'61626364pub fn steal(store &storage.Store, mut backend remote.Backend, opts StealOptions) !StealReport {65 name := repo_name(store, mut backend)!66 head_before := history.head(store)67 68 if dirty(store, head_before)! {69 if head_before == none {70 return error(no_saves_here)71 }72 return error(dirty_tree)73 }74 fetched := fetch_back_to_known(store, mut backend, name)!75 mut report := StealReport{76 repo: name77 fetched_saves: fetched.saves.len78 fetched_objects: fetched.repo_objects.len79 fetched_events: fetched.events_out.len80 head: fetched.head81 }82 mut local_only := []history.Save{}83 if head := head_before {84 85 86 87 local_only = saves_after(store, head.id, fetched.base) or {88 return error('the remote builds on save ${fetched.base}, which is not on this line — load the save you want, then offer')89 }90 }91 if fetched.base == '' && local_only.len > 0 {92 return error('the remote keeps a different history — it shares no save with this repo')93 }9495 strips_before := events.strip_events(store)!.len96 mut clashes := []Clash{}97 mut side_of := map[string]Side{}98 if fetched.saves.len > 0 && local_only.len > 0 {99 clashes = combine_clashes(store, fetched)!100 report.clashes = clashes.map(it.path)101 102 103 side_of = choose_sides(clashes, opts)!104 }105106 store.begin() or { return err }107 108 109 if moved := changed_since(store, head_before, strips_before) {110 if moved {111 store.rollback()112 return error('this repo changed while steal was asking — run koh steal again')113 }114 } else {115 store.rollback()116 return err117 }118 final := (write_and_combine(store, fetched, local_only, clashes, side_of, mut report) or {119 store.rollback()120 return err121 })122 store.commit() or { return err }123 report.head = final.id124 flags := events.latest_flags(store)!125 for record in fetched.saves {126 if flag := flags[record.id] {127 if flag.flagged {128 report.flagged << flag129 }130 }131 }132133 if head := head_before {134 if final.id == head.id {135 136 return report137 }138 files := history.files_of(store, final.id)!139 mut wanted := map[string]bool{}140 for file in files {141 wanted[file.path] = true142 }143 mut remove := []string{}144 for file in history.files_of(store, head.id)! {145 if file.path !in wanted {146 remove << file.path147 }148 }149 result := snapshot.restore_files(store, store.root, snapshot.load(store.root), files,150 remove)!151 report.removed = result.removed152 } else {153 files := history.files_of(store, final.id)!154 snapshot.restore_files(store, store.root, snapshot.load(store.root), files, [])!155 }156 history.refresh_log_md(store)157 return report158}159160161162163fn write_and_combine(store &storage.Store, fetched Fetched, local_only []history.Save, clashes []Clash, side_of map[string]Side, mut report StealReport) !history.Save {164 write_fetched(store, fetched)!165 if fetched.saves.len == 0 {166 167 168 return history.head(store) or { return error('this repo has no head') }169 }170 if local_only.len == 0 {171 172 history.set_head(store, fetched.head)!173 report.forward = true174 return history.head(store) or { return error('the remote head did not land') }175 }176 remote_files := history.files_of(store, fetched.head)!177 mut mine_files := []snapshot.FileEntry{}178 if our_head := history.head(store) {179 mine_files = history.files_of(store, our_head.id)!180 }181182 183 history.set_head(store, fetched.head)!184 mut current := remote_files.clone()185 for save in local_only {186 parent_files := if save.parent != '' {187 history.files_of(store, save.parent)!188 } else {189 []snapshot.FileEntry{}190 }191 target_files := history.files_of(store, save.id)!192 plan := apply.three_way(current, parent_files, target_files, [], clashes.map(it.path))193 if apply.conflicts(plan) {194 return error('combine could not apply ${plan.conflict} — it is not a clash file')195 }196 if plan.applied.len == 0 {197 198 continue199 }200 history.record_save(store, '', plan.files, history.SaveInput{201 message: save.message202 created_at: save.created_at203 machine: save.machine204 agent: save.agent205 session: save.session206 is_checkpoint: save.is_checkpoint207 replayed_from: save.id208 })!209 current = plan.files.clone()210 report.replayed++211 }212213 mut mine_paths := []string{}214 for clash in clashes {215 if side_of[clash.path] == .mine {216 mine_paths << clash.path217 }218 }219 if mine_paths.len > 0 {220 221 final_plan := apply.three_way(current, current, mine_files, mine_paths, [])222 if final_plan.applied.len > 0 {223 history.record_save(store, '', final_plan.files, history.SaveInput{224 message: 'combine: kept mine for ${mine_paths.len} ${if mine_paths.len == 1 {225 'file'226 } else {227 'files'228 }}'229 })!230 report.kept_mine = mine_paths.len231 }232 }233 return history.head(store) or { return error('the combined line has no head') }234}235236237238pub fn find_clashes(base []snapshot.FileEntry, mine []snapshot.FileEntry, theirs []snapshot.FileEntry) []Clash {239 base_map := snapshot.index_files(base)240 mine_map := snapshot.index_files(mine)241 theirs_map := snapshot.index_files(theirs)242 mut paths := mine_map.keys()243 for path in theirs_map.keys() {244 if path !in mine_map {245 paths << path246 }247 }248 paths.sort()249 mut clashes := []Clash{}250 for path in paths {251 here := mine_map[path] or {252 snapshot.FileEntry{253 path: path254 }255 }256 there := theirs_map[path] or {257 snapshot.FileEntry{258 path: path259 }260 }261 was := base_map[path] or {262 snapshot.FileEntry{263 path: path264 }265 }266 if same(here, there) {267 continue268 }269 if same(here, was) || same(there, was) {270 continue271 }272 clashes << Clash{273 path: path274 mine: here275 theirs: there276 base: was277 }278 }279 return clashes280}281282283284285fn combine_clashes(store &storage.Store, fetched Fetched) ![]Clash {286 base_files := if fetched.base != '' {287 history.files_of(store, fetched.base)!288 } else {289 []snapshot.FileEntry{}290 }291 head := history.head(store) or { return []Clash{} }292 293 294 295 strips := fetched.events_out.filter(it.kind == events.kind_strip)296 mut clashes := find_clashes(after_strips(base_files, fetched.base, strips), after_strips(history.files_of(store,297 head.id)!, head.id, strips), after_strips(to_files(fetched.saves.last()), fetched.head,298 strips))299 for mut clash in clashes {300 mine := fetched_bytes(store, fetched, clash.mine)!301 theirs := fetched_bytes(store, fetched, clash.theirs)!302 delta := snapshot.diff_bytes(clash.path, 'modified', mine, theirs)!303 clash.stat = if delta.binary { 'binary' } else { '+${delta.added} -${delta.removed}' }304 }305 return clashes306}307308309fn after_strips(files []snapshot.FileEntry, save_id string, strips []events.Event) []snapshot.FileEntry {310 return files.filter(fn [strips, save_id] (file snapshot.FileEntry) bool {311 for strip in strips {312 if (strip.save_id == '' || strip.save_id == save_id) && covers(strip.path, file.path) {313 return false314 }315 }316 return true317 })318}319320321322fn fetched_bytes(store &storage.Store, fetched Fetched, entry snapshot.FileEntry) ![]u8 {323 if entry.hash == '' {324 return []u8{}325 }326 if blob := fetched.repo_objects[entry.hash] {327 return zlib.decompress(blob)!328 }329 return store.get_object(entry.hash)!330}331332fn choose_sides(clashes []Clash, opts StealOptions) !map[string]Side {333 mut sides := map[string]Side{}334 if clashes.len == 0 {335 return sides336 }337 for clash in clashes {338 if opts.mine {339 sides[clash.path] = .mine340 continue341 }342 if opts.theirs {343 sides[clash.path] = .theirs344 continue345 }346 if opts.ask != unsafe { nil } {347 sides[clash.path] = opts.ask(clash)348 continue349 }350 return error('${clashes.len} files changed on both machines — run on a terminal to choose, or pass --mine or --theirs')351 }352 return sides353}354355fn same(a snapshot.FileEntry, b snapshot.FileEntry) bool {356 if a.hash == '' && b.hash == '' {357 return true358 }359 return a.hash == b.hash && a.executable == b.executable360}361362fn changed_since(store &storage.Store, before ?history.Save, strips_before int) !bool {363 if events.strip_events(store)!.len != strips_before {364 return true365 }366 now := history.head(store)367 if now or { history.Save{} }.id != before or { history.Save{} }.id {368 return true369 }370 return dirty(store, now)!371}372373374375376fn dirty(store &storage.Store, head ?history.Save) !bool {377 files := snapshot.walk(store, store.root, snapshot.load(store.root))!378 if saved := head {379 return !snapshot.same_tree(history.files_of(store, saved.id)!, files)380 }381 seed := storage.hash_hex(snapshot.default_ignore.bytes())382 return files.any(it.path != snapshot.ignore_file || it.hash != seed)383}384385386387pub fn fetch_repo(mut backend remote.Backend, name string) !Fetched {388 remote_head := backend.get(head_key(name))!389 if !remote_head.found {390 return error('the remote has no repo called "${name}"')391 }392 save_ids := backend.list('${name}/saves')!393 object_keys := backend.list('${name}/objects')!394 event_keys := backend.list('${name}/events')!395 mut fetched := Fetched{396 head: remote_head.body.bytestr().trim_space()397 remote_save_ids: map[string]bool{}398 }399 for key in object_keys {400 blob := backend.get(key)!401 if blob.found {402 fetched.repo_objects[os.base(key)] = blob.body403 }404 }405 for key in save_ids {406 body := backend.get(key)!407 if !body.found {408 continue409 }410 record := decode_save(body.body)!411 fetched.remote_save_ids[record.id] = true412 fetched.saves << record413 }414 fetched.saves = parent_first(fetched.saves)!415 for key in event_keys {416 body := backend.get(key)!417 if body.found {418 fetched.events_out << decode_event(body.body)!419 }420 }421 return fetched422}423424425426427fn parent_first(records []SaveRecord) ![]SaveRecord {428 mut by_id := map[string]SaveRecord{}429 for record in records {430 by_id[record.id] = record431 }432 mut placed := map[string]bool{}433 mut ordered := []SaveRecord{}434 for record in records {435 mut chain := []SaveRecord{}436 mut cursor := record.id437 for cursor != '' && cursor !in placed {438 if chain.len > records.len {439 return error('the save records on the remote form a loop')440 }441 current := by_id[cursor] or { return error('the remote is missing save ${cursor}') }442 chain << current443 cursor = current.parent444 }445 chain.reverse_in_place()446 for current in chain {447 placed[current.id] = true448 ordered << current449 }450 }451 return ordered452}