steal.v

14.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	if snapshot.restore_pending(store) {67		return error(snapshot.restore_unfinished)68	}69	head_before := history.head(store)70	// Combining rewrites the working tree, so unsaved work would be lost.71	if dirty(store, head_before)! {72		if head_before == none {73			return error(no_saves_here)74		}75		return error(dirty_tree)76	}77	fetched := fetch_back_to_known(store, mut backend, name)!78	mut report := StealReport{79		repo:            name80		fetched_saves:   fetched.saves.len81		fetched_objects: fetched.repo_objects.len82		fetched_events:  fetched.events_out.len83		head:            fetched.head84	}85	mut local_only := []history.Save{}86	if head := head_before {87		// The remote builds on `base`. If that save is here but no longer on88		// the line, neither line contains the other; jumping to the remote89		// would silently leave this line behind.90		local_only = saves_after(store, head.id, fetched.base) or {91			return error('the remote builds on save ${fetched.base}, which is not on this line — load the save you want, then offer')92		}93	}94	if fetched.base == '' && local_only.len > 0 {95		return error('the remote keeps a different history — it shares no save with this repo')96	}9798	strips_before := events.strip_events(store)!.len99	mut clashes := []Clash{}100	mut side_of := map[string]Side{}101	if fetched.saves.len > 0 && local_only.len > 0 {102		clashes = combine_clashes(store, fetched)!103		report.clashes = clashes.map(it.path)104		// Asked before the write lock: a person thinking must not stall every105		// agent's save on this repo.106		side_of = choose_sides(clashes, opts)!107	}108109	store.begin() or { return err }110	// The questions ran without the lock. If a save or an edit landed111	// meanwhile, the answers were about a line that no longer exists.112	if moved := changed_since(store, head_before, strips_before) {113		if moved {114			store.rollback()115			return error('this repo changed while steal was asking — run koh steal again')116		}117	} else {118		store.rollback()119		return err120	}121	final := (write_and_combine(store, fetched, local_only, clashes, side_of, mut report) or {122		store.rollback()123		return err124	})125	files := history.files_of(store, final.id) or {126		store.rollback()127		return err128	}129	snapshot.check_links(store.root, files) or {130		store.rollback()131		return err132	}133	store.commit() or { return err }134	report.head = final.id135	flags := events.latest_flags(store)!136	for record in fetched.saves {137		if flag := flags[record.id] {138			if flag.flagged {139				report.flagged << flag140			}141		}142	}143144	if head := head_before {145		if final.id == head.id {146			// The line did not move, so neither does the working tree.147			return report148		}149		mut wanted := map[string]bool{}150		for file in files {151			wanted[file.path] = true152		}153		mut remove := []string{}154		for file in history.files_of(store, head.id)! {155			if file.path !in wanted {156				remove << file.path157			}158		}159		result := snapshot.restore_files(store, store.root, snapshot.load(store.root), files,160			remove)!161		report.removed = result.removed162	} else {163		snapshot.restore_files(store, store.root, snapshot.load(store.root), files, [])!164	}165	history.refresh_log_md(store)166	return report167}168169// write_and_combine lands a fetch and, when the local line has saves the remote170// lacks, replays them on top of the remote head. It runs inside the caller's171// transaction and returns the new head.172fn write_and_combine(store &storage.Store, fetched Fetched, local_only []history.Save, clashes []Clash, side_of map[string]Side, mut report StealReport) !history.Save {173	write_fetched(store, fetched)!174	if fetched.saves.len == 0 {175		// The remote head is already on this line: level, or this machine is176		// ahead and the offer that follows a steal sends the rest.177		return history.head(store) or { return error('this repo has no head') }178	}179	if local_only.len == 0 {180		// Nothing of ours is missing from the remote: the line simply moves on.181		history.set_head(store, fetched.head)!182		report.forward = true183		return history.head(store) or { return error('the remote head did not land') }184	}185	remote_files := history.files_of(store, fetched.head)!186	mut mine_files := []snapshot.FileEntry{}187	if our_head := history.head(store) {188		mine_files = history.files_of(store, our_head.id)!189	}190191	// A file the remote changed is a clash, decided below, or one this machine192	// left as it was or changed the same way, so the remote's version stands.193	// Replaying this machine's steps on it could only conflict: an edit it194	// later undid would no longer apply.195	base_files := history.files_of(store, fetched.base)!196	settled := changed_paths(base_files, remote_files)197198	// Take the remote's line first, so the replayed saves chain onto it.199	history.set_head(store, fetched.head)!200	mut current := remote_files.clone()201	for save in local_only {202		parent_files := if save.parent != '' {203			history.files_of(store, save.parent)!204		} else {205			[]snapshot.FileEntry{}206		}207		target_files := history.files_of(store, save.id)!208		plan := apply.three_way(current, parent_files, target_files, [], settled)209		if apply.conflicts(plan) {210			return error('combine could not apply ${plan.conflict} — it is not a clash file')211		}212		if plan.applied.len == 0 {213			// Everything this save touched was a file the remote changed.214			continue215		}216		history.record_save(store, '', plan.files, history.SaveInput{217			message:       save.message218			created_at:    save.created_at219			machine:       save.machine220			agent:         save.agent221			session:       save.session222			is_checkpoint: save.is_checkpoint223			replayed_from: save.id224		})!225		current = plan.files.clone()226		report.replayed++227	}228229	mut mine_paths := []string{}230	for clash in clashes {231		if side_of[clash.path] == .mine {232			mine_paths << clash.path233		}234	}235	if mine_paths.len > 0 {236		// One last save puts my versions of the chosen files back.237		final_plan := apply.three_way(current, current, mine_files, mine_paths, [])238		if final_plan.applied.len > 0 {239			history.record_save(store, '', final_plan.files, history.SaveInput{240				message: 'combine: kept mine for ${mine_paths.len} ${if mine_paths.len == 1 {241					'file'242				} else {243					'files'244				}}'245			})!246			report.kept_mine = mine_paths.len247		}248	}249	return history.head(store) or { return error('the combined line has no head') }250}251252// find_clashes lists the files both sides changed, differently. Files changed253// identically on both sides are not clashes: there is nothing to decide.254pub fn find_clashes(base []snapshot.FileEntry, mine []snapshot.FileEntry, theirs []snapshot.FileEntry) []Clash {255	base_map := snapshot.index_files(base)256	mine_map := snapshot.index_files(mine)257	theirs_map := snapshot.index_files(theirs)258	mut paths := mine_map.keys()259	for path in theirs_map.keys() {260		if path !in mine_map {261			paths << path262		}263	}264	paths.sort()265	mut clashes := []Clash{}266	for path in paths {267		here := mine_map[path] or {268			snapshot.FileEntry{269				path: path270			}271		}272		there := theirs_map[path] or {273			snapshot.FileEntry{274				path: path275			}276		}277		was := base_map[path] or {278			snapshot.FileEntry{279				path: path280			}281		}282		if same(here, there) {283			continue284		}285		if same(here, was) || same(there, was) {286			continue287		}288		clashes << Clash{289			path:   path290			mine:   here291			theirs: there292			base:   was293		}294	}295	return clashes296}297298// changed_paths lists the paths whose entry differs between two trees.299fn changed_paths(before []snapshot.FileEntry, after []snapshot.FileEntry) []string {300	was := snapshot.index_files(before)301	now := snapshot.index_files(after)302	mut paths := []string{}303	for path, entry in now {304		if !same(entry, was[path] or { snapshot.FileEntry{} }) {305			paths << path306		}307	}308	for path, _ in was {309		if path !in now {310			paths << path311		}312	}313	return paths314}315316// combine_clashes finds the files both lines changed, with the diff stat each317// prompt shows. It reads the remote head from the fetch, not the store, so it318// can run before anything is written.319fn combine_clashes(store &storage.Store, fetched Fetched) ![]Clash {320	base_files := if fetched.base != '' {321		history.files_of(store, fetched.base)!322	} else {323		[]snapshot.FileEntry{}324	}325	head := history.head(store) or { return []Clash{} }326	// The transaction applies the incoming strips before it replays, so the327	// clashes are found on the trees as they will be then, or the answers328	// would be about files that are no longer there.329	strips := fetched.events_out.filter(it.kind == events.kind_strip)330	// Base and mine are here already, so every strip reaches them (created 0).331	remote_head := fetched.saves.last()332	mut clashes := find_clashes(after_strips(base_files, fetched.base, 0, strips), after_strips(history.files_of(store,333		head.id)!, head.id, 0, strips), after_strips(to_files(remote_head), remote_head.id,334		remote_head.created_at, strips))335	for mut clash in clashes {336		mine := fetched_bytes(store, fetched, clash.mine)!337		theirs := fetched_bytes(store, fetched, clash.theirs)!338		delta := snapshot.diff_bytes(clash.path, 'modified', mine, theirs)!339		clash.stat = if delta.binary { 'binary' } else { '+${delta.added} -${delta.removed}' }340	}341	return clashes342}343344// after_strips is a save's file list once the given strip events are applied,345// by the same rule write_fetched uses.346fn after_strips(files []snapshot.FileEntry, save_id string, created_at i64, strips []events.Event) []snapshot.FileEntry {347	return files.filter(fn [strips, save_id, created_at] (file snapshot.FileEntry) bool {348		return !strips.any(reaches(it, save_id, created_at) && covers(it.path, file.path))349	})350}351352// fetched_bytes reads one side of a clash: from the fetch when it has just353// arrived, else from the store. An absent side is empty.354fn fetched_bytes(store &storage.Store, fetched Fetched, entry snapshot.FileEntry) ![]u8 {355	if entry.hash == '' {356		return []u8{}357	}358	if blob := fetched.repo_objects[entry.hash] {359		return zlib.decompress(blob)!360	}361	return store.get_object(entry.hash)!362}363364fn choose_sides(clashes []Clash, opts StealOptions) !map[string]Side {365	mut sides := map[string]Side{}366	if clashes.len == 0 {367		return sides368	}369	for clash in clashes {370		if opts.mine {371			sides[clash.path] = .mine372			continue373		}374		if opts.theirs {375			sides[clash.path] = .theirs376			continue377		}378		if opts.ask != unsafe { nil } {379			sides[clash.path] = opts.ask(clash)380			continue381		}382		return error('${clashes.len} files changed on both machines — run on a terminal to choose, or pass --mine or --theirs')383	}384	return sides385}386387fn same(a snapshot.FileEntry, b snapshot.FileEntry) bool {388	if a.hash == '' && b.hash == '' {389		return true390	}391	return a.hash == b.hash && a.executable == b.executable392}393394fn changed_since(store &storage.Store, before ?history.Save, strips_before int) !bool {395	if events.strip_events(store)!.len != strips_before {396		return true397	}398	now := history.head(store)399	if now or { history.Save{} }.id != before or { history.Save{} }.id {400		return true401	}402	return dirty(store, now)!403}404405// dirty reports whether the working tree holds anything a steal would406// overwrite. With no saves yet, that is every file but the untouched ignore407// list `koh init` wrote.408fn dirty(store &storage.Store, head ?history.Save) !bool {409	files := snapshot.walk(store, store.root, snapshot.load(store.root))!410	if saved := head {411		return !snapshot.same_tree(history.files_of(store, saved.id)!, files)412	}413	seed := storage.hash_hex(snapshot.default_ignore.bytes())414	return files.any(it.path != snapshot.ignore_file || it.hash != seed)415}416417// fetch_repo pulls a whole repo — head, saves, objects and events — for418// `koh steal <name>`, which lands a copy in a new folder.419pub fn fetch_repo(mut backend remote.Backend, name string) !Fetched {420	remote_head := backend.get(head_key(name))!421	if !remote_head.found {422		return error('the remote has no repo called "${name}"')423	}424	save_ids := backend.list('${name}/saves')!425	object_keys := backend.list('${name}/objects')!426	event_keys := backend.list('${name}/events')!427	mut fetched := Fetched{428		head: remote_head.body.bytestr().trim_space()429	}430	for key in object_keys {431		blob := backend.get(key)!432		if blob.found {433			fetched.repo_objects[os.base(key)] = blob.body434		}435	}436	for key in save_ids {437		body := backend.get(key)!438		if !body.found {439			continue440		}441		record := decode_save(body.body)!442		fetched.saves << record443	}444	fetched.saves = parent_first(fetched.saves)!445	for key in event_keys {446		body := backend.get(key)!447		if body.found {448			fetched.events_out << decode_event(body.body)!449		}450	}451	return fetched452}453454// parent_first orders saves so every parent lands before its children, as the455// foreign key on `parent` demands. Time cannot do it: a replayed save keeps its456// original, older time but sits on a newer parent.457fn parent_first(records []SaveRecord) ![]SaveRecord {458	mut by_id := map[string]SaveRecord{}459	for record in records {460		by_id[record.id] = record461	}462	mut placed := map[string]bool{}463	mut ordered := []SaveRecord{}464	for record in records {465		mut chain := []SaveRecord{}466		mut cursor := record.id467		for cursor != '' && cursor !in placed {468			if chain.len > records.len {469				return error('the save records on the remote form a loop')470			}471			current := by_id[cursor] or { return error('the remote is missing save ${cursor}') }472			chain << current473			cursor = current.parent474		}475		chain.reverse_in_place()476		for current in chain {477			placed[current.id] = true478			ordered << current479		}480	}481	return ordered482}