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 184 185 186 base_files := history.files_of(store, fetched.base)!187 settled := changed_paths(base_files, remote_files)188189 190 history.set_head(store, fetched.head)!191 mut current := remote_files.clone()192 for save in local_only {193 parent_files := if save.parent != '' {194 history.files_of(store, save.parent)!195 } else {196 []snapshot.FileEntry{}197 }198 target_files := history.files_of(store, save.id)!199 plan := apply.three_way(current, parent_files, target_files, [], settled)200 if apply.conflicts(plan) {201 return error('combine could not apply ${plan.conflict} — it is not a clash file')202 }203 if plan.applied.len == 0 {204 205 continue206 }207 history.record_save(store, '', plan.files, history.SaveInput{208 message: save.message209 created_at: save.created_at210 machine: save.machine211 agent: save.agent212 session: save.session213 is_checkpoint: save.is_checkpoint214 replayed_from: save.id215 })!216 current = plan.files.clone()217 report.replayed++218 }219220 mut mine_paths := []string{}221 for clash in clashes {222 if side_of[clash.path] == .mine {223 mine_paths << clash.path224 }225 }226 if mine_paths.len > 0 {227 228 final_plan := apply.three_way(current, current, mine_files, mine_paths, [])229 if final_plan.applied.len > 0 {230 history.record_save(store, '', final_plan.files, history.SaveInput{231 message: 'combine: kept mine for ${mine_paths.len} ${if mine_paths.len == 1 {232 'file'233 } else {234 'files'235 }}'236 })!237 report.kept_mine = mine_paths.len238 }239 }240 return history.head(store) or { return error('the combined line has no head') }241}242243244245pub fn find_clashes(base []snapshot.FileEntry, mine []snapshot.FileEntry, theirs []snapshot.FileEntry) []Clash {246 base_map := snapshot.index_files(base)247 mine_map := snapshot.index_files(mine)248 theirs_map := snapshot.index_files(theirs)249 mut paths := mine_map.keys()250 for path in theirs_map.keys() {251 if path !in mine_map {252 paths << path253 }254 }255 paths.sort()256 mut clashes := []Clash{}257 for path in paths {258 here := mine_map[path] or {259 snapshot.FileEntry{260 path: path261 }262 }263 there := theirs_map[path] or {264 snapshot.FileEntry{265 path: path266 }267 }268 was := base_map[path] or {269 snapshot.FileEntry{270 path: path271 }272 }273 if same(here, there) {274 continue275 }276 if same(here, was) || same(there, was) {277 continue278 }279 clashes << Clash{280 path: path281 mine: here282 theirs: there283 base: was284 }285 }286 return clashes287}288289290fn changed_paths(before []snapshot.FileEntry, after []snapshot.FileEntry) []string {291 was := snapshot.index_files(before)292 now := snapshot.index_files(after)293 mut paths := []string{}294 for path, entry in now {295 if !same(entry, was[path] or { snapshot.FileEntry{} }) {296 paths << path297 }298 }299 for path, _ in was {300 if path !in now {301 paths << path302 }303 }304 return paths305}306307308309310fn combine_clashes(store &storage.Store, fetched Fetched) ![]Clash {311 base_files := if fetched.base != '' {312 history.files_of(store, fetched.base)!313 } else {314 []snapshot.FileEntry{}315 }316 head := history.head(store) or { return []Clash{} }317 318 319 320 strips := fetched.events_out.filter(it.kind == events.kind_strip)321 322 remote_head := fetched.saves.last()323 mut clashes := find_clashes(after_strips(base_files, fetched.base, 0, strips), after_strips(history.files_of(store,324 head.id)!, head.id, 0, strips), after_strips(to_files(remote_head), remote_head.id,325 remote_head.created_at, strips))326 for mut clash in clashes {327 mine := fetched_bytes(store, fetched, clash.mine)!328 theirs := fetched_bytes(store, fetched, clash.theirs)!329 delta := snapshot.diff_bytes(clash.path, 'modified', mine, theirs)!330 clash.stat = if delta.binary { 'binary' } else { '+${delta.added} -${delta.removed}' }331 }332 return clashes333}334335336337fn after_strips(files []snapshot.FileEntry, save_id string, created_at i64, strips []events.Event) []snapshot.FileEntry {338 return files.filter(fn [strips, save_id, created_at] (file snapshot.FileEntry) bool {339 return !strips.any(reaches(it, save_id, created_at) && covers(it.path, file.path))340 })341}342343344345fn fetched_bytes(store &storage.Store, fetched Fetched, entry snapshot.FileEntry) ![]u8 {346 if entry.hash == '' {347 return []u8{}348 }349 if blob := fetched.repo_objects[entry.hash] {350 return zlib.decompress(blob)!351 }352 return store.get_object(entry.hash)!353}354355fn choose_sides(clashes []Clash, opts StealOptions) !map[string]Side {356 mut sides := map[string]Side{}357 if clashes.len == 0 {358 return sides359 }360 for clash in clashes {361 if opts.mine {362 sides[clash.path] = .mine363 continue364 }365 if opts.theirs {366 sides[clash.path] = .theirs367 continue368 }369 if opts.ask != unsafe { nil } {370 sides[clash.path] = opts.ask(clash)371 continue372 }373 return error('${clashes.len} files changed on both machines — run on a terminal to choose, or pass --mine or --theirs')374 }375 return sides376}377378fn same(a snapshot.FileEntry, b snapshot.FileEntry) bool {379 if a.hash == '' && b.hash == '' {380 return true381 }382 return a.hash == b.hash && a.executable == b.executable383}384385fn changed_since(store &storage.Store, before ?history.Save, strips_before int) !bool {386 if events.strip_events(store)!.len != strips_before {387 return true388 }389 now := history.head(store)390 if now or { history.Save{} }.id != before or { history.Save{} }.id {391 return true392 }393 return dirty(store, now)!394}395396397398399fn dirty(store &storage.Store, head ?history.Save) !bool {400 files := snapshot.walk(store, store.root, snapshot.load(store.root))!401 if saved := head {402 return !snapshot.same_tree(history.files_of(store, saved.id)!, files)403 }404 seed := storage.hash_hex(snapshot.default_ignore.bytes())405 return files.any(it.path != snapshot.ignore_file || it.hash != seed)406}407408409410pub fn fetch_repo(mut backend remote.Backend, name string) !Fetched {411 remote_head := backend.get(head_key(name))!412 if !remote_head.found {413 return error('the remote has no repo called "${name}"')414 }415 save_ids := backend.list('${name}/saves')!416 object_keys := backend.list('${name}/objects')!417 event_keys := backend.list('${name}/events')!418 mut fetched := Fetched{419 head: remote_head.body.bytestr().trim_space()420 }421 for key in object_keys {422 blob := backend.get(key)!423 if blob.found {424 fetched.repo_objects[os.base(key)] = blob.body425 }426 }427 for key in save_ids {428 body := backend.get(key)!429 if !body.found {430 continue431 }432 record := decode_save(body.body)!433 fetched.saves << record434 }435 fetched.saves = parent_first(fetched.saves)!436 for key in event_keys {437 body := backend.get(key)!438 if body.found {439 fetched.events_out << decode_event(body.body)!440 }441 }442 return fetched443}444445446447448fn parent_first(records []SaveRecord) ![]SaveRecord {449 mut by_id := map[string]SaveRecord{}450 for record in records {451 by_id[record.id] = record452 }453 mut placed := map[string]bool{}454 mut ordered := []SaveRecord{}455 for record in records {456 mut chain := []SaveRecord{}457 mut cursor := record.id458 for cursor != '' && cursor !in placed {459 if chain.len > records.len {460 return error('the save records on the remote form a loop')461 }462 current := by_id[cursor] or { return error('the remote is missing save ${cursor}') }463 chain << current464 cursor = current.parent465 }466 chain.reverse_in_place()467 for current in chain {468 placed[current.id] = true469 ordered << current470 }471 }472 return ordered473}