steal.v

13.9 KB · raw

1//! Stealing: bringing another machine's saves in, and combining when both2//! machines moved.3//!4//! The order is always the same, and it is what makes an interrupted steal5//! harmless: read everything from the remote first, then land it in one6//! transaction, then write the working tree. Divergence is resolved per file —7//! a clash is never merged line by line, it is chosen.89module sync1011import compress.zlib12import os13import src.apply14import src.events15import src.history16import src.remote17import src.snapshot18import src.storage1920pub enum Side {21	mine22	theirs23}2425// Clash is one file both machines changed differently. `stat` is the short26// diff stat the terminal prompt shows, so the choice is informed.27pub 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 // resolve every clash as mine39	theirs bool // resolve every clash as theirs40	// Asked once per clash when neither flag is set. Nil means "nobody to ask".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 // incoming saves that are flagged57}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>"'6162// steal brings the remote's new saves in. Inside a repo with its own work this63// may have to combine; a repo with nothing of its own simply fast-forwards.64pub 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	// Combining rewrites the working tree, so unsaved work would be lost.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		// The remote builds on `base`. If that save is here but no longer on85		// the line, neither line contains the other; jumping to the remote86		// would silently leave this line behind.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		// Asked before the write lock: a person thinking must not stall every102		// agent's save on this repo.103		side_of = choose_sides(clashes, opts)!104	}105106	store.begin() or { return err }107	// The questions ran without the lock. If a save or an edit landed108	// meanwhile, the answers were about a line that no longer exists.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			// The line did not move, so neither does the working tree.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}159160// write_and_combine lands a fetch and, when the local line has saves the remote161// lacks, replays them on top of the remote head. It runs inside the caller's162// transaction and returns the new head.163fn 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		// The remote head is already on this line: level, or this machine is167		// ahead and the offer that follows a steal sends the rest.168		return history.head(store) or { return error('this repo has no head') }169	}170	if local_only.len == 0 {171		// Nothing of ours is missing from the remote: the line simply moves on.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	// Take the remote's line first, so the replayed saves chain onto it.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			// Everything this save touched was a clash resolved as theirs.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		// One last save puts my versions of the chosen files back.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}235236// find_clashes lists the files both sides changed, differently. Files changed237// identically on both sides are not clashes: there is nothing to decide.238pub 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}281282// combine_clashes finds the files both lines changed, with the diff stat each283// prompt shows. It reads the remote head from the fetch, not the store, so it284// can run before anything is written.285fn 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	// The transaction applies the incoming strips before it replays, so the293	// clashes are found on the trees as they will be then, or the answers294	// would be about files that are no longer there.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}307308// after_strips is a save's file list once the given strip events are applied.309fn 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}319320// fetched_bytes reads one side of a clash: from the fetch when it has just321// arrived, else from the store. An absent side is empty.322fn 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}372373// dirty reports whether the working tree holds anything a steal would374// overwrite. With no saves yet, that is every file but the untouched ignore375// list `koh init` wrote.376fn 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}384385// fetch_repo pulls a whole repo — head, saves, objects and events — for386// `koh steal <name>`, which lands a copy in a new folder.387pub 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	}398	for key in object_keys {399		blob := backend.get(key)!400		if blob.found {401			fetched.repo_objects[os.base(key)] = blob.body402		}403	}404	for key in save_ids {405		body := backend.get(key)!406		if !body.found {407			continue408		}409		record := decode_save(body.body)!410		fetched.saves << record411	}412	fetched.saves = parent_first(fetched.saves)!413	for key in event_keys {414		body := backend.get(key)!415		if body.found {416			fetched.events_out << decode_event(body.body)!417		}418	}419	return fetched420}421422// parent_first orders saves so every parent lands before its children, as the423// foreign key on `parent` demands. Time cannot do it: a replayed save keeps its424// original, older time but sits on a newer parent.425fn parent_first(records []SaveRecord) ![]SaveRecord {426	mut by_id := map[string]SaveRecord{}427	for record in records {428		by_id[record.id] = record429	}430	mut placed := map[string]bool{}431	mut ordered := []SaveRecord{}432	for record in records {433		mut chain := []SaveRecord{}434		mut cursor := record.id435		for cursor != '' && cursor !in placed {436			if chain.len > records.len {437				return error('the save records on the remote form a loop')438			}439			current := by_id[cursor] or { return error('the remote is missing save ${cursor}') }440			chain << current441			cursor = current.parent442		}443		chain.reverse_in_place()444		for current in chain {445			placed[current.id] = true446			ordered << current447		}448	}449	return ordered450}