cmd_steal.v

15.4 KB · raw

1//! `koh steal` — bring another machine's saves in.2//!3//! Inside a repo this pulls the remote's new saves and combines when both4//! machines moved. Outside one it fetches a whole repo into a new folder.5//! `--list` shows what the remote holds.67module cli89import json210import os11import src.events12import src.fmt13import src.history14import src.remote15import src.snapshot16import src.storage17import src.exchange18import src.view1920pub fn cmd_steal(raw []string) int {21	args := parse('steal', raw, Options{22		flags: ['list', 'mine', 'theirs', 'json', 'yes']23	}) or { return usage_error(err.msg()) }24	if args.flag('list') {25		if args.positional.len > 0 {26			return usage_error('steal --list takes no arguments')27		}28		return list_repos(args)29	}30	if storage.find_root(os.getwd()) == none {31		name := args.positional_at(0)32		if name == '' {33			return usage_error('steal needs a repo name outside a repo, e.g. koh steal myproject')34		}35		if args.positional.len > 1 {36			return usage_error('steal takes one repo: koh steal myproject, or koh steal kepr.uk/nina')37		}38		address := web_address(name) or { return refuse(args.json(), err.msg()) }39		if address.len > 0 {40			return clone_web(address[0], address[1], args)41		}42		return clone_repo(name, args)43	}44	store := open_store() or { return refuse(args.json(), err.msg()) }45	defer {46		store.close()47	}48	if args.positional.len > 0 {49		return usage_error('steal takes no name inside a repo — run it outside to fetch a whole repo')50	}51	guided := on_terminal(args.json())52	if guided {53		if !ready_to_steal() {54			return 155		}56	}57	// A stolen repo has its own remote: the address it came from, until this machine signs in to58	// that Kepr, when the bucket takes over.59	source := exchange.source_of(store)60	upgraded := source != '' && exchange.signed_in_to(exchange.source_host(source))61	read_only := source != '' && !upgraded62	mut backend := if read_only {63		exchange.read_only(source) or { return refuse(args.json(), err.msg()) }64	} else {65		this_machine_backend() or { return refuse(args.json(), err.msg()) }66	}67	mut options := exchange.StealOptions{68		mine:   args.flag('mine')69		theirs: args.flag('theirs')70		yes:    args.flag('yes')71	}72	if guided {73		options.guide = guide_steal74	}75	report := exchange.steal(store, mut backend, options) or { return refuse(args.json(), err.msg()) }76	if upgraded {77		exchange.forget_source(store) or { return refuse(args.json(), err.msg()) }78		if !args.json() {79			ok('signed in to ${exchange.source_host(source)}: this repo now syncs with your bucket')80		}81	}82	// The remote should end up with whatever this machine just decided — unless there is no remote83	// to write to: a repo still riding its source stays read-only, and quietly so.84	offer_failed := !read_only && !offer_after_steal(store, mut backend)85	if args.json() {86		emit_json(json2.encode(StolenJson{87			repo:          report.repo88			forward:       report.forward89			saves:         report.fetched_saves90			objects:       report.fetched_objects91			events:        report.fetched_events92			clashes:       report.clashes93			replayed:      report.replayed94			kept_mine:     report.kept_mine95			head:          report.head96			offer_failed:  offer_failed97			flagged:       report.flagged.map(it.save_id)98			previous_head: report.previous_head99			kept_versions: report.kept_versions100		}))101		return 0102	}103	if report.fetched_saves == 0 {104		ok('already up to date with "${report.repo}" — head is [${report.head}]')105		return 0106	}107	if report.forward {108		if guided {109			ok('${report.repo} is up to date · ${report.fetched_saves} new saves')110		} else {111			ok('brought in ${report.fetched_saves} saves from "${report.repo}" — head is now [${report.head}]')112		}113	} else {114		ok(if !guided {115			'brought in ${report.fetched_saves} saves from "${report.repo}"'116		} else if read_only || offer_failed {117			'combined'118		} else {119			'combined · offered to ${report.repo}'120		})121		if read_only {122			note('your saves stay on this machine (read-only source)')123		} else if !guided {124			note("replayed ${report.replayed} of this machine's saves onto the remote head")125		}126		if report.kept_mine > 0 {127			note('kept mine for ${fmt.plural(report.kept_mine, 'file')}')128		}129		if guided {130			note('to undo all of it: koh load ${report.previous_head}')131		} else {132			note('the tree from before is kept — koh load ${report.previous_head} brings it back, less anything stripped')133		}134		note_kept_versions(report)135	}136	warn_flagged(report.flagged)137	if report.clashes.len > 0 {138		note('${report.clashes.len} changed on both machines: ${report.clashes.join(', ')}')139	}140	if offer_failed {141		warn('the remote was not updated — run "koh offer" when it is reachable again')142	}143	return 0144}145146// on_terminal is when a steal asks rather than refuses: a person at both ends, and no --json.147fn on_terminal(json bool) bool {148	return !json && interactive() && os.is_atty(1) != 0149}150151// note_kept_versions names, for each file answered "theirs", the save that still holds this152// machine's version.153fn note_kept_versions(report exchange.StealReport) {154	for kept in report.kept_versions {155		parts := kept.split_nth(':', 2)156		note('your ${parts[0]} is in ${parts[1]} · koh peek ${parts[1]}')157	}158}159160fn ready_to_steal() bool {161	store := open_store() or { return true }162	head := history.head(store)163	dirty := exchange.dirty(store, head) or {164		store.close()165		return true166	}167	if !dirty {168		store.close()169		return true170	}171	paths := unsaved_paths(store, head) or { []string{} }172	store.close()173	println('  ${fmt.gold(fmt.glyph_ok + ' steal')}')174	println('')175	println('  you have ${fmt.plural(paths.len, 'unsaved file')}')176	if paths.len > 0 {177		println('    ${paths[..if paths.len < 5 { paths.len } else { 5 }].join(' · ')}')178		if paths.len > 5 {179			println('    and ${paths.len - 5} more')180		}181	}182	println('')183	println('  [c] checkpoint them and continue')184	println('  [s] save them with a message and continue')185	println('  [q] stop here')186	print('  › ')187	match os.get_line().trim_space() {188		'c' { return cmd_save(['before steal'], true) == 0 }189		's' {190			print('  message: ')191			message := os.get_line().trim_space()192			return message != '' && cmd_save([message], false) == 0193		}194		else { return false }195	}196}197198fn unsaved_paths(store &storage.Store, head ?history.Save) ![]string {199	now := snapshot.index_files(snapshot.walk(store, store.root, snapshot.load(store.root))!)200	before := if save := head {201		snapshot.index_files(history.files_of(store, save.id)!)202	} else {203		map[string]snapshot.FileEntry{}204	}205	mut paths := []string{}206	for path, file in now {207		old := before[path] or { snapshot.FileEntry{} }208		if file.hash != old.hash || file.executable != old.executable {209			paths << path210		}211	}212	for path, _ in before {213		if path !in now {214			paths << path215		}216	}217	paths.sort()218	return paths219}220221fn guide_steal(preview exchange.StealPreview) !map[string]exchange.Side {222	_, columns := view.terminal_size()223	width := if columns > 0 && columns < 80 { columns } else { 80 }224	println('')225	println('  ${fmt.gold('you')} and ${fmt.blue(preview.repo)} both moved since ${preview.base}')226	println('')227	println('    ${fmt.gold('you')}      ${fmt.plural(preview.local.len, 'save')}  ${messages(preview.local.map(it.message))}')228	println('    ${fmt.blue('remote')}   ${fmt.plural(preview.remote.len, 'save')}  ${messages(preview.remote.map(it.message))}')229	println('')230	println('  ${fmt.plural(preview.changed, 'file')} changed')231	println('    ${fmt.green('✓')} ${preview.automatic} combine by themselves')232	println('    ${fmt.green('✓')} ${preview.identical} changed the same way on both sides')233	println('    ${fmt.amber('!')} ${preview.clashes.len} ${if preview.clashes.len == 1 {234		'needs'235	} else {236		'need'237	}} you')238	mut answers := map[string]exchange.Side{}239	if preview.all_side != '' {240		for clash in preview.clashes {241			answers[clash.path] = if preview.all_side == 'mine' { .mine } else { .theirs }242		}243	}244	mut at := if preview.all_side == '' { 0 } else { preview.clashes.len }245	for at < preview.clashes.len {246		clash := preview.clashes[at]247		println('')248		println('  ── ${at + 1} of ${preview.clashes.len} · ${clash.path} ──')249		println(fmt.fit('    ${fmt.gold('you')}      ${clash.mine_stat}   ${clash.mine_save.message} · ${fmt.stamp(clash.mine_save.created_at)} · ${clash.mine_save.machine}',250			width))251		println(fmt.fit('    ${fmt.blue('remote')}   ${clash.theirs_stat}   ${clash.theirs_save.message} · ${fmt.stamp(clash.theirs_save.created_at)} · ${clash.theirs_save.machine}',252			width))253		println('')254		println('  [m] keep mine   [t] take theirs   [d] see both changes')255		println('  [b] back   [?] help')256		print('  › ')257		match os.get_line().trim_space() {258			'm' {259				answers[clash.path] = .mine260				at++261			}262			't' {263				answers[clash.path] = .theirs264				at++265			}266			'b' {267				if at > 0 { at-- }268			}269			'd' { show_clash(clash) }270			'?' {271				println('  mine keeps your version; theirs takes the remote version.')272				println('  Nothing is lost either way; both versions stay in history.')273			}274			'q' { return error('steal cancelled') }275			else {}276		}277	}278	println('')279	println('  ${fmt.gold('ready to combine')}')280	for clash in preview.clashes {281		choice := if answers[clash.path] == .mine { 'keep mine' } else { 'take theirs' }282		println('    ${choice}  ${clash.path}')283	}284	println('    replay your ${fmt.plural(preview.local.len, 'save')} on top of the remote')285	println('    your originals stay in history: ${preview.local.map(it.id).join(' · ')}')286	if !confirm(preview.yes)! {287		return error('steal cancelled')288	}289	return answers290}291292fn messages(items []string) string {293	return fmt.fit(items.map('"${it}"').join(' · '), 52)294}295296fn show_clash(clash exchange.Clash) {297	if clash.mine_patch == '' && clash.theirs_patch == '' {298		println('  binary file')299		return300	}301	mut lines := ['your changes']302	lines << clash.mine_patch.trim_right('\n').split_into_lines()303	lines << ''304	lines << 'remote changes'305	lines << clash.theirs_patch.trim_right('\n').split_into_lines()306	view.page_text(lines, clash.path)307}308309// offer_after_steal pushes what this machine just decided. A failure here does310// not undo the steal; it is reported.311fn offer_after_steal(store &storage.Store, mut backend remote.Backend) bool {312	if _ := exchange.offer(store, mut backend) {313		return true314	}315	return false316}317318fn list_repos(args Args) int {319	mut backend := this_machine_backend() or { return refuse(args.json(), err.msg()) }320	keys := backend.list('') or { return refuse(args.json(), err.msg()) }321	mut names := map[string]bool{}322	for key in keys {323		parts := key.trim_left('/').split('/')324		if parts.len > 0 && parts[0] != '' {325			names[parts[0]] = true326		}327	}328	mut sorted := names.keys()329	sorted.sort()330	if args.json() {331		emit_json(json2.encode(ReposJson{332			repos: sorted333		}))334		return 0335	}336	if sorted.len == 0 {337		ok('the remote has no repos yet')338		return 0339	}340	for name in sorted {341		println('  ${name}')342	}343	return 0344}345346// web_address splits a `<host>/<repo>` argument out of a steal name: a slash makes it an address347// (`kepr.uk/nina`, `http://127.0.0.1:3917/shipped`), a bare name is this machine's own remote. An348// addressed value that is missing either half is an error, never a name.349fn web_address(value string) ![]string {350	if !value.contains('/') {351		return []string{}352	}353	repo := value.all_after_last('/')354	host := value.all_before_last('/')355	if repo == '' || host == '' {356		return error('"${value}" is not <host>/<repo>')357	}358	return [host, repo]359}360361// clone_web fetches a public repo over HTTPS, read-only. Signed in to that Kepr, the same address362// names this machine's own bucket instead, so the bucket's copy — private or not — is the one to363// take.364fn clone_web(host string, repo string, args Args) int {365	base := remote.kepr_host(host) or { return refuse(args.json(), err.msg()) }366	if exchange.signed_in_to(base) {367		return clone_repo(repo, args)368	}369	mut backend := exchange.read_only('${base}/${repo}') or { return refuse(args.json(), err.msg()) }370	return clone_with(repo, args, mut backend, '${base}/${repo}')371}372373// clone_repo fetches a whole repo into ./<name>, for a machine that does not374// have it yet.375fn clone_repo(name string, args Args) int {376	mut backend := this_machine_backend() or { return refuse(args.json(), err.msg()) }377	return clone_with(name, args, mut backend, '')378}379380// clone_with is that fetch, from whichever remote was chosen: the whole history in, then the head's381// files onto the disk. A non-empty `source` means the repo came from a read-only address and stays382// local until this machine signs in there.383fn clone_with(name string, args Args, mut backend remote.Backend, source string) int {384	target := os.join_path(os.getwd(), name)385	if os.exists(target) {386		return refuse(args.json(), '${name} already exists here — run steal inside it instead')387	}388	fetched := exchange.fetch_repo(mut backend, name) or { return refuse(args.json(), err.msg()) }389	store := land_clone(target, name, fetched, source) or {390		os.rmdir_all(target) or {}391		return refuse(args.json(), err.msg())392	}393	// Anything that goes wrong from here leaves the folder half-made, and a retry would refuse it394	// as "already exists", so the whole clone goes.395	mut finished := false396	defer {397		store.close()398		if !finished {399			os.rmdir_all(target) or {}400		}401	}402	files := history.files_of(store, fetched.head) or { return refuse(args.json(), err.msg()) }403	snapshot.restore_files(store, target, snapshot.Ignore{}, files, []) or {404		return refuse(args.json(), err.msg())405	}406	mut flagged := []events.Flag{}407	for _, flag in events.latest_flags(store) or { return refuse(args.json(), err.msg()) } {408		if flag.flagged {409			flagged << flag410		}411	}412	flagged.sort(a.save_id < b.save_id)413	finished = true414	if args.json() {415		emit_json(json2.encode(StolenJson{416			repo:    name417			forward: true418			saves:   fetched.saves.len419			objects: fetched.repo_objects.len420			events:  fetched.events_out.len421			head:    fetched.head422			flagged: flagged.map(it.save_id)423		}))424		return 0425	}426	ok('fetched "${name}" into ${target}')427	note('${fetched.saves.len} saves at [${fetched.head}]')428	if source != '' {429		note('read-only: this clone keeps up with ${source} — sign in with "koh remote ${exchange.source_host(source)}" to make it yours')430	}431	warn_flagged(flagged)432	return 0433}434435// land_clone creates ./<name> and commits the fetched history into it. Objects436// are checked on the way in, so a damaged remote fails here.437fn land_clone(target string, name string, fetched exchange.Fetched, source string) !storage.Store {438	// SQLite creates the file, not the folder holding it.439	os.mkdir_all(target, os.MkdirParams{})!440	mut store := storage.create(target)!441	fill_clone(store, name, fetched, source) or {442		store.rollback()443		store.close()444		return err445	}446	return store447}448449fn fill_clone(store &storage.Store, name string, fetched exchange.Fetched, source string) ! {450	store.begin()!451	exchange.write_fetched(store, fetched)!452	history.set_head(store, fetched.head)!453	exchange.remember_repo(store, name)!454	if source != '' {455		exchange.remember_source(store, source)!456	}457	snapshot.mark_restore(store)!458	store.commit()!459}460461// warn_flagged prints the line the document asks for, per incoming flagged save.462fn warn_flagged(flags []events.Flag) {463	for flag in flags {464		reason := if flag.reason != '' { ' — ${flag.reason}' } else { '' }465		warn('[${flag.save_id}] came in flagged${reason}')466	}467}468469struct ReposJson {470	repos []string471}472473struct StolenJson {474	repo          string475	forward       bool476	saves         int477	objects       int478	events        int479	clashes       []string480	replayed      int481	kept_mine     int482	head          string483	offer_failed  bool484	flagged       []string485	previous_head string486	kept_versions []string487}