123456789module exchange1011import src.apply12import src.events13import src.fmt14import src.history15import src.remote16import src.snapshot17import src.storage18import strconv1920pub enum Side {21 mine22 theirs23}24252627pub struct Clash {28pub mut:29 path string30 mine snapshot.FileEntry31 theirs snapshot.FileEntry32 base snapshot.FileEntry33 mine_stat string34 theirs_stat string35 mine_patch string36 theirs_patch string37 mine_save history.Save38 theirs_save history.Save39}4041pub struct StealPreview {42pub:43 repo string44 base history.Save45 local []history.Save46 remote []SaveRecord47 changed int48 automatic int49 identical int50 clashes []Clash51 yes bool52 all_side string53}5455pub struct StealOptions {56pub mut:57 mine bool 58 theirs bool 59 60 guide fn (preview StealPreview) !map[string]Side = unsafe { nil }61 yes bool62 json bool63 approve fn (saves int, events int, yes bool, json bool) ! = unsafe { nil }64}6566pub struct StealReport {67pub mut:68 repo string69 forward bool70 fetched_saves int71 fetched_objects int72 fetched_events int73 clashes []string74 kept_mine int75 replayed int76 removed int77 head string78 flagged []events.Flag 79 80 81 previous_head string82 kept_versions []string83 unsafe_paths []string84}8586pub const dirty_tree = 'save or checkpoint first — steal needs a clean tree'87888990pub struct ClashError {91 Error92pub:93 paths []string94}9596pub fn (e ClashError) msg() string {97 return '${e.paths.join(', ')} changed on both machines — run on a terminal to choose, or pass --mine or --theirs with --yes'98}99100pub const no_saves_here = 'this folder has files but no saves — steal a repo into an empty folder with "koh steal <name>"'101102103104pub fn steal(store &storage.Store, mut backend remote.Backend, opts StealOptions) !StealReport {105 name := repo_name(store, mut backend)!106 if snapshot.restore_pending(store) {107 return error(snapshot.restore_unfinished)108 }109 head_before := history.head(store)110 111 if dirty(store, head_before)! {112 if head_before == none {113 return error(no_saves_here)114 }115 return error(dirty_tree)116 }117 fetched := fetch_back_to_known(store, mut backend, name)!118 mut report := StealReport{119 repo: name120 fetched_saves: fetched.saves.len121 fetched_objects: fetched.repo_objects.len122 fetched_events: fetched.events_out.len123 head: fetched.head124 unsafe_paths: fetched.unsafe_paths125 }126 mut local_only := []history.Save{}127 if head := head_before {128 129 130 131 local_only = saves_after(store, head.id, fetched.base) or {132 return error('the remote builds on save ${fetched.base}, which is not on this line — load the save you want, then offer')133 }134 }135 if fetched.base == '' && local_only.len > 0 {136 return error('the remote keeps a different history — it shares no save with this repo')137 }138 if (fetched.saves.len > 0 || fetched.events_out.len > 0)139 && !(fetched.saves.len > 0 && local_only.len > 0 && opts.guide != unsafe { nil })140 && opts.approve != unsafe { nil } {141 opts.approve(fetched.saves.len, fetched.events_out.len, opts.yes, opts.json)!142 }143 if fetched.saves.len > 0 {144 store.begin()!145 write_fetched_records(store, fetched) or {146 store.rollback()147 return err148 }149 store.end()!150 }151152 strips_before := events.strip_events(store)!.len153 mut clashes := []Clash{}154 mut side_of := map[string]Side{}155 if fetched.saves.len > 0 && local_only.len > 0 {156 clashes = combine_clashes(store, fetched, local_only)!157 report.clashes = clashes.map(it.path)158 if opts.guide != unsafe { nil } {159 side_of = opts.guide(combine_preview(store, name, fetched, local_only, clashes,160 opts.yes, if opts.mine {161 'mine'162 } else if opts.theirs { 'theirs' } else { '' })!)!163 } else {164 165 166 side_of = choose_sides(clashes, opts)!167 }168 }169 for clash in clashes {170 if side_of[clash.path] == .theirs {171 report.kept_versions << '${clash.path}:${local_only.last().id}'172 }173 }174175 store.begin() or { return err }176 177 178 if moved := changed_since(store, head_before, strips_before) {179 if moved {180 store.rollback()181 return error('this repo changed while steal was asking — run koh steal again')182 }183 } else {184 store.rollback()185 return err186 }187 final := (write_and_combine(store, fetched, local_only, clashes, side_of, mut report) or {188 store.rollback()189 return err190 })191 files := history.files_of(store, final.id) or {192 store.rollback()193 return err194 }195 snapshot.check_links(store.root, files) or {196 store.rollback()197 return err198 }199 200 201 moved := if head := head_before { final.id != head.id } else { true }202 if moved {203 snapshot.mark_restore(store) or {204 store.rollback()205 return err206 }207 }208 store.end() or { return err }209 report.head = final.id210 if local_only.len > 0 && report.fetched_saves > 0 {211 report.previous_head = local_only.last().id212 }213 flags := events.latest_flags(store)!214 for record in fetched.saves {215 if flag := flags[record.id] {216 if flag.flagged {217 report.flagged << flag218 }219 }220 }221222 if head := head_before {223 if final.id == head.id {224 225 return report226 }227 mut wanted := map[string]bool{}228 for file in files {229 wanted[file.path] = true230 }231 mut remove := []string{}232 for file in history.files_of(store, head.id)! {233 if file.path !in wanted {234 remove << file.path235 }236 }237 result := snapshot.restore_files(store, store.root, snapshot.load(store.root), files,238 remove)!239 report.removed = result.removed240 } else {241 snapshot.restore_files(store, store.root, snapshot.load(store.root), files, [])!242 }243 history.refresh_log_md(store)244 return report245}246247248249250fn write_and_combine(store &storage.Store, fetched Fetched, local_only []history.Save, clashes []Clash, side_of map[string]Side, mut report StealReport) !history.Save {251 write_fetched(store, fetched)!252 if fetched.saves.len == 0 {253 254 255 return history.head(store) or { return error('this repo has no head') }256 }257 if local_only.len == 0 {258 259 history.set_head(store, fetched.head)!260 report.forward = true261 return history.head(store) or { return error('the remote head did not land') }262 }263 remote_files := history.files_of(store, fetched.head)!264 mut mine_files := []snapshot.FileEntry{}265 if our_head := history.head(store) {266 mine_files = history.files_of(store, our_head.id)!267 }268269 270 271 272 273 base_files := history.files_of(store, fetched.base)!274 settled := changed_paths(base_files, remote_files)275276 277 history.set_head(store, fetched.head)!278 mut current := remote_files.clone()279 for save in local_only {280 parent_files := if save.parent != '' {281 history.files_of(store, save.parent)!282 } else {283 []snapshot.FileEntry{}284 }285 target_files := history.files_of(store, save.id)!286 plan := apply.three_way(current, parent_files, target_files, [], settled)287 if apply.conflicts(plan) {288 return error('combine could not apply ${plan.conflict} — it is not a clash file')289 }290 if plan.applied.len == 0 {291 292 continue293 }294 history.record_save(store, '', plan.files, history.SaveInput{295 message: save.message296 created_at: save.created_at297 machine: save.machine298 agent: save.agent299 session: save.session300 is_checkpoint: save.is_checkpoint301 replayed_from: save.id302 })!303 current = plan.files.clone()304 report.replayed++305 }306307 mut mine_paths := []string{}308 for clash in clashes {309 if side_of[clash.path] == .mine {310 mine_paths << clash.path311 }312 }313 if mine_paths.len > 0 {314 315 final_plan := apply.three_way(current, current, mine_files, mine_paths, [])316 if final_plan.applied.len > 0 {317 history.record_save(store, '', final_plan.files, history.SaveInput{318 message: 'combine: kept mine for ${mine_paths.len} ${if mine_paths.len == 1 {319 'file'320 } else {321 'files'322 }}'323 })!324 report.kept_mine = mine_paths.len325 }326 }327 return history.head(store) or { return error('the combined line has no head') }328}329330331332pub fn find_clashes(base []snapshot.FileEntry, mine []snapshot.FileEntry, theirs []snapshot.FileEntry) []Clash {333 base_map := snapshot.index_files(base)334 mine_map := snapshot.index_files(mine)335 theirs_map := snapshot.index_files(theirs)336 mut paths := mine_map.keys()337 for path in theirs_map.keys() {338 if path !in mine_map {339 paths << path340 }341 }342 paths.sort()343 mut clashes := []Clash{}344 for path in paths {345 here := mine_map[path] or {346 snapshot.FileEntry{347 path: path348 }349 }350 there := theirs_map[path] or {351 snapshot.FileEntry{352 path: path353 }354 }355 was := base_map[path] or {356 snapshot.FileEntry{357 path: path358 }359 }360 if same(here, there) {361 continue362 }363 if same(here, was) || same(there, was) {364 continue365 }366 clashes << Clash{367 path: path368 mine: here369 theirs: there370 base: was371 }372 }373 return clashes374}375376377fn changed_paths(before []snapshot.FileEntry, after []snapshot.FileEntry) []string {378 was := snapshot.index_files(before)379 now := snapshot.index_files(after)380 mut paths := []string{}381 for path, entry in now {382 if !same(entry, was[path] or { snapshot.FileEntry{} }) {383 paths << path384 }385 }386 for path, _ in was {387 if path !in now {388 paths << path389 }390 }391 return paths392}393394395396397fn combine_clashes(store &storage.Store, fetched Fetched, local_only []history.Save) ![]Clash {398 base_files := if fetched.base != '' {399 history.files_of(store, fetched.base)!400 } else {401 []snapshot.FileEntry{}402 }403 head := history.head(store) or { return []Clash{} }404 405 406 407 strips := known_strips(store, fetched)!408 remote_head := fetched.saves.last()409 mut clashes := find_clashes(after_strips(base_files, fetched.base, strips), after_strips(history.files_of(store,410 head.id)!, head.id, strips), after_strips(to_files(remote_head), remote_head.id, strips))411 for mut clash in clashes {412 base := fetched_bytes(store, fetched, clash.base)!413 mine := fetched_bytes(store, fetched, clash.mine)!414 theirs := fetched_bytes(store, fetched, clash.theirs)!415 mine_delta := snapshot.diff_bytes(clash.path, 'modified', base, mine)!416 theirs_delta := snapshot.diff_bytes(clash.path, 'modified', base, theirs)!417 clash.mine_stat = delta_stat(mine_delta, clash.mine.size)418 clash.theirs_stat = delta_stat(theirs_delta, clash.theirs.size)419 clash.mine_patch = mine_delta.patch420 clash.theirs_patch = theirs_delta.patch421 clash.mine_save = last_touch(store, local_only, clash.path)!422 clash.theirs_save = last_touch(store, fetched.saves.map(to_save(it)), clash.path)!423 }424 return clashes425}426427fn delta_stat(delta snapshot.Delta, size i64) string {428 if delta.binary {429 return fmt.human_bytes(size)430 }431 return '+${delta.added} -${delta.removed}'432}433434fn last_touch(store &storage.Store, saves []history.Save, path string) !history.Save {435 for index := saves.len - 1; index >= 0; index-- {436 save := saves[index]437 current := snapshot.index_files(history.files_of(store, save.id)!)[path] or {438 snapshot.FileEntry{}439 }440 parent := if save.parent != '' {441 snapshot.index_files(history.files_of(store, save.parent)!)[path] or {442 snapshot.FileEntry{}443 }444 } else {445 snapshot.FileEntry{}446 }447 if !same(current, parent) {448 return save449 }450 }451 return saves.last()452}453454455456fn combine_preview(store &storage.Store, name string, fetched Fetched, local []history.Save, clashes []Clash, yes bool, all_side string) !StealPreview {457 base := history.files_of(store, fetched.base)!458 mine := history.files_of(store, local.last().id)!459 theirs := history.files_of(store, fetched.head)!460 mine_changed := changed_paths(base, mine)461 theirs_changed := changed_paths(base, theirs)462 mut changed := map[string]bool{}463 for path in mine_changed {464 changed[path] = true465 }466 for path in theirs_changed {467 changed[path] = true468 }469 mut identical := 0470 base_map := snapshot.index_files(base)471 mine_map := snapshot.index_files(mine)472 theirs_map := snapshot.index_files(theirs)473 for path, _ in changed {474 if !same(mine_map[path] or { snapshot.FileEntry{} }, base_map[path] or { snapshot.FileEntry{} })475 && same(mine_map[path] or { snapshot.FileEntry{} }, theirs_map[path] or { snapshot.FileEntry{} }) {476 identical++477 }478 }479 return StealPreview{480 repo: name481 base: history.by_id(store, fetched.base) or { history.Save{} }482 local: local483 remote: fetched.saves484 changed: changed.len485 automatic: changed.len - identical - clashes.len486 identical: identical487 clashes: clashes488 yes: yes489 all_side: all_side490 }491}492493494495fn after_strips(files []snapshot.FileEntry, save_id string, strips []events.Event) []snapshot.FileEntry {496 return files.filter(fn [strips, save_id] (file snapshot.FileEntry) bool {497 return !strips.any(reaches(it, save_id) && covers(it.path, file.path))498 })499}500501502503fn fetched_bytes(store &storage.Store, fetched Fetched, entry snapshot.FileEntry) ![]u8 {504 if entry.hash == '' {505 return []u8{}506 }507 if blob := fetched.repo_objects[entry.hash] {508 return storage.inflate_bounded(blob, storage.max_file_size)!509 }510 return store.get_object(entry.hash)!511}512513fn choose_sides(clashes []Clash, opts StealOptions) !map[string]Side {514 mut sides := map[string]Side{}515 if clashes.len == 0 {516 return sides517 }518 for clash in clashes {519 if opts.mine {520 sides[clash.path] = .mine521 continue522 }523 if opts.theirs {524 sides[clash.path] = .theirs525 continue526 }527 return ClashError{528 paths: clashes.map(it.path)529 }530 }531 return sides532}533534fn same(a snapshot.FileEntry, b snapshot.FileEntry) bool {535 if a.hash == '' && b.hash == '' {536 return true537 }538 return a.hash == b.hash && a.executable == b.executable539}540541fn changed_since(store &storage.Store, before ?history.Save, strips_before int) !bool {542 if events.strip_events(store)!.len != strips_before {543 return true544 }545 now := history.head(store)546 if now or { history.Save{} }.id != before or { history.Save{} }.id {547 return true548 }549 return dirty(store, now)!550}551552553554555pub fn dirty(store &storage.Store, head ?history.Save) !bool {556 files := snapshot.walk(store, store.root, snapshot.load(store.root))!557 if saved := head {558 return !snapshot.same_tree(history.files_of(store, saved.id)!, files)559 }560 seed := storage.hash_hex(snapshot.default_ignore.bytes())561 return files.any(it.path != snapshot.ignore_file || it.hash != seed)562}563564565566pub fn fetch_repo(mut backend remote.Backend, name string) !Fetched {567 check_format(mut backend, name)!568 remote_head := backend.get(head_key(name))!569 if !remote_head.found {570 return error('the remote has no repo called "${name}"')571 }572 mut fetched := Fetched{573 head: remote_head.body.bytestr().trim_space()574 }575 if !valid_save_id(fetched.head) {576 return error('the remote head has invalid save ID ${fetched.head}')577 }578 mut bundle := &Bundle{579 fetched: fetched580 }581 if fetch_bundle(mut backend, bundle_key(name), mut bundle)! {582 fetched = bundle.fetched583 } else {584 for kind in ['objects', 'saves', 'events'] {585 for key in backend.list('${name}/${kind}')! {586 body := backend.get(key)!587 if body.found {588 take(mut fetched, key.all_after('${name}/'), body.body)!589 }590 }591 }592 }593 fetched.saves = parent_first(fetched.saves)!594 if !fetched.saves.any(it.id == fetched.head) {595 return error('the remote is missing its head save ${fetched.head}')596 }597 fetched.events_out.sort(a.id < b.id)598 return fetched599}600601602603fn fetch_bundle(mut backend remote.Backend, key string, mut bundle Bundle) !bool {604 found := if mut backend is remote.Web {605 backend.stream(key, fn [mut bundle] (piece []u8) ! {606 bundle.feed(piece)!607 })!608 } else {609 whole := backend.get(key)!610 if whole.found {611 bundle.feed(whole.body)!612 }613 whole.found614 }615 if found {616 bundle.finish()!617 }618 return found619}620621622623624625struct Bundle {626mut:627 fetched Fetched628 pending []u8 629 ended bool630}631632fn (mut b Bundle) feed(piece []u8) ! {633 b.pending << piece634 mut at := 0635 for at < b.pending.len {636 637 mut newline := at638 for newline < b.pending.len && b.pending[newline] != `\n` {639 newline++640 }641 if newline == b.pending.len {642 break643 }644 header := b.pending[at..newline].bytestr()645 if b.ended {646 return error('the bundle goes on after its end')647 }648 if header == 'end 0' {649 b.ended = true650 at = newline + 1651 continue652 }653 length := strconv.atoi(header.all_after(' '))!654 start := newline + 1655 if length < 0 {656 return error('the bundle has a negative length for ${header.all_before(' ')}')657 }658 if length > b.pending.len - start {659 break660 }661 take(mut b.fetched, header.all_before(' '), b.pending[start..start + length])!662 at = start + length663 }664 if at > 0 {665 b.pending = b.pending[at..]666 }667}668669fn (b &Bundle) finish() ! {670 if !b.ended || b.pending.len > 0 {671 return error('the bundle was cut short — try the steal again')672 }673}674675676fn take(mut fetched Fetched, key string, body []u8) ! {677 id := key.all_after('/')678 match key.all_before('/') {679 'objects' {680 if !storage.valid_hash(id) {681 return error('the remote has invalid object hash ${id}')682 }683 fetched.repo_objects[id] = body684 }685 'saves' {686 mut record := decode_save(body)!687 validate_save(record, id)!688 fetched.unsafe_paths << drop_unsafe_paths(mut record)689 validate_hashes(record.id, record.files)!690 fetched.saves << record691 }692 'events' {693 if !valid_event_id(id) {694 return error('the remote has invalid event ID ${id}')695 }696 event := decode_event(body)!697 if event.id != id {698 return error('remote event record ID ${event.id} disagrees with key ${id}')699 }700 if !ignored_strip(event) {701 fetched.events_out << event702 }703 }704 else {705 return error('the remote sent "${key}", which is not part of a repo')706 }707 }708}709710711712713fn parent_first(records []SaveRecord) ![]SaveRecord {714 mut by_id := map[string]SaveRecord{}715 for record in records {716 by_id[record.id] = record717 }718 mut placed := map[string]bool{}719 mut ordered := []SaveRecord{}720 for record in records {721 mut chain := []SaveRecord{}722 mut cursor := record.id723 for cursor != '' && cursor !in placed {724 if chain.len > records.len {725 return error('the save records on the remote form a loop')726 }727 current := by_id[cursor] or { return error('the remote is missing save ${cursor}') }728 chain << current729 cursor = current.parent730 }731 chain.reverse_in_place()732 for current in chain {733 placed[current.id] = true734 ordered << current735 }736 }737 return ordered738}