cmd_steal.v

15.2 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	if interactive() && os.is_atty(1) != 0 && !args.json() {52		if !ready_to_steal() {53			return 154		}55	}56	// A stolen repo has its own remote: the address it came from, until this machine signs in to57	// that Kepr, when the bucket takes over.58	source := exchange.source_of(store)59	mut upgraded := source != '' && exchange.signed_in_to(exchange.source_host(source))60	mut backend := remote.Backend(unsafe { nil })61	if source != '' && !upgraded {62		backend = exchange.read_only(source) or { return refuse(args.json(), err.msg()) }63	} else {64		backend = this_machine_backend() or { return refuse(args.json(), err.msg()) }65	}66	mut options := exchange.StealOptions{67		mine:   args.flag('mine')68		theirs: args.flag('theirs')69		yes:    args.flag('yes')70	}71	guided := !args.json() && interactive() && os.is_atty(1) != 072	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	offered := if source != '' && !upgraded { true } else { 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:  !offered97			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			if source != '' && !upgraded {116				'combined'117			} else if offered {118				'combined · offered to ${report.repo}'119			} else {120				'combined'121			}122		} else {123			'brought in ${report.fetched_saves} saves from "${report.repo}"'124		})125		if source != '' && !upgraded {126			note('your saves stay on this machine (read-only source)')127		} else if !guided {128			note("replayed ${report.replayed} of this machine's saves onto the remote head")129		}130		if report.kept_mine > 0 {131			note('kept mine for ${fmt.plural(report.kept_mine, 'file')}')132		}133		if guided {134			note('to undo all of it: koh load ${report.previous_head}')135		} else {136			note('the tree from before is kept — koh load ${report.previous_head} brings it back, less anything stripped')137		}138		for kept in report.kept_versions {139			parts := kept.split_nth(':', 2)140			note('your ${parts[0]} is in ${parts[1]} · koh peek ${parts[1]}')141		}142	}143	warn_flagged(report.flagged)144	if report.clashes.len > 0 {145		note('${report.clashes.len} changed on both machines: ${report.clashes.join(', ')}')146	}147	if !offered {148		warn('the remote was not updated — run "koh offer" when it is reachable again')149	}150	return 0151}152153fn ready_to_steal() bool {154	store := open_store() or { return true }155	head := history.head(store)156	dirty := exchange.dirty(store, head) or {157		store.close()158		return true159	}160	if !dirty {161		store.close()162		return true163	}164	paths := unsaved_paths(store, head) or { []string{} }165	store.close()166	println('  ${fmt.gold(fmt.glyph_ok + ' steal')}')167	println('')168	println('  you have ${fmt.plural(paths.len, 'unsaved file')}')169	if paths.len > 0 {170		println('    ${paths[..if paths.len < 5 { paths.len } else { 5 }].join(' · ')}')171		if paths.len > 5 {172			println('    and ${paths.len - 5} more')173		}174	}175	println('')176	println('  [c] checkpoint them and continue')177	println('  [s] save them with a message and continue')178	println('  [q] stop here')179	print('  › ')180	match os.get_line().trim_space() {181		'c' { return cmd_save(['before steal'], true) == 0 }182		's' {183			print('  message: ')184			message := os.get_line().trim_space()185			return message != '' && cmd_save([message], false) == 0186		}187		else { return false }188	}189}190191fn unsaved_paths(store &storage.Store, head ?history.Save) ![]string {192	now := snapshot.index_files(snapshot.walk(store, store.root, snapshot.load(store.root))!)193	before := if save := head {194		snapshot.index_files(history.files_of(store, save.id)!)195	} else {196		map[string]snapshot.FileEntry{}197	}198	mut paths := []string{}199	for path, file in now {200		old := before[path] or { snapshot.FileEntry{} }201		if file.hash != old.hash || file.executable != old.executable {202			paths << path203		}204	}205	for path, _ in before {206		if path !in now {207			paths << path208		}209	}210	paths.sort()211	return paths212}213214fn guide_steal(preview exchange.StealPreview) !map[string]exchange.Side {215	_, columns := view.terminal_size()216	width := if columns > 0 && columns < 80 { columns } else { 80 }217	println('')218	println('  ${fmt.gold('you')} and ${fmt.blue(preview.repo)} both moved since ${preview.base}')219	println('')220	println('    ${fmt.gold('you')}      ${fmt.plural(preview.local.len, 'save')}  ${messages(preview.local.map(it.message))}')221	println('    ${fmt.blue('remote')}   ${fmt.plural(preview.remote.len, 'save')}  ${messages(preview.remote.map(it.message))}')222	println('')223	println('  ${fmt.plural(preview.changed, 'file')} changed')224	println('    ${fmt.green('✓')} ${preview.automatic} combine by themselves')225	println('    ${fmt.green('✓')} ${preview.identical} changed the same way on both sides')226	println('    ${fmt.amber('!')} ${preview.clashes.len} ${if preview.clashes.len == 1 {227		'needs'228	} else {229		'need'230	}} you')231	mut answers := map[string]exchange.Side{}232	if preview.all_side != '' {233		for clash in preview.clashes {234			answers[clash.path] = if preview.all_side == 'mine' { .mine } else { .theirs }235		}236	}237	mut at := if preview.all_side == '' { 0 } else { preview.clashes.len }238	for at < preview.clashes.len {239		clash := preview.clashes[at]240		println('')241		println('  ── ${at + 1} of ${preview.clashes.len} · ${clash.path} ──')242		println(fmt.fit('    ${fmt.gold('you')}      ${clash.mine_stat}   ${clash.mine_save.message} · ${fmt.stamp(clash.mine_save.created_at)} · ${clash.mine_save.machine}',243			width))244		println(fmt.fit('    ${fmt.blue('remote')}   ${clash.theirs_stat}   ${clash.theirs_save.message} · ${fmt.stamp(clash.theirs_save.created_at)} · ${clash.theirs_save.machine}',245			width))246		println('')247		println('  [m] keep mine   [t] take theirs   [d] see both changes')248		println('  [b] back   [?] help')249		print('  › ')250		match os.get_line().trim_space() {251			'm' {252				answers[clash.path] = .mine253				at++254			}255			't' {256				answers[clash.path] = .theirs257				at++258			}259			'b' {260				if at > 0 { at-- }261			}262			'd' { show_clash(clash) }263			'?' {264				println('  mine keeps your version; theirs takes the remote version.')265				println('  Nothing is lost either way; both versions stay in history.')266			}267			'q' { return error('steal cancelled') }268			else {}269		}270	}271	println('')272	println('  ${fmt.gold('ready to combine')}')273	for clash in preview.clashes {274		choice := if answers[clash.path] == .mine { 'keep mine' } else { 'take theirs' }275		println('    ${choice}  ${clash.path}')276	}277	println('    replay your ${fmt.plural(preview.local.len, 'save')} on top of the remote')278	println('    your originals stay in history: ${preview.local.map(it.id).join(' · ')}')279	if !confirm(preview.yes)! {280		return error('steal cancelled')281	}282	return answers283}284285fn messages(items []string) string {286	return fmt.fit(items.map('"${it}"').join(' · '), 52)287}288289fn show_clash(clash exchange.Clash) {290	if clash.mine_patch == '' && clash.theirs_patch == '' {291		println('  binary file')292		return293	}294	mut lines := ['your changes']295	lines << clash.mine_patch.trim_right('\n').split_into_lines()296	lines << ''297	lines << 'remote changes'298	lines << clash.theirs_patch.trim_right('\n').split_into_lines()299	view.page_text(lines, clash.path)300}301302// offer_after_steal pushes what this machine just decided. A failure here does303// not undo the steal; it is reported.304fn offer_after_steal(store &storage.Store, mut backend remote.Backend) bool {305	if _ := exchange.offer(store, mut backend) {306		return true307	}308	return false309}310311fn list_repos(args Args) int {312	mut backend := this_machine_backend() or { return refuse(args.json(), err.msg()) }313	keys := backend.list('') or { return refuse(args.json(), err.msg()) }314	mut names := map[string]bool{}315	for key in keys {316		parts := key.trim_left('/').split('/')317		if parts.len > 0 && parts[0] != '' {318			names[parts[0]] = true319		}320	}321	mut sorted := names.keys()322	sorted.sort()323	if args.json() {324		emit_json(json2.encode(ReposJson{325			repos: sorted326		}))327		return 0328	}329	if sorted.len == 0 {330		ok('the remote has no repos yet')331		return 0332	}333	for name in sorted {334		println('  ${name}')335	}336	return 0337}338339// web_address splits a `<host>/<repo>` argument out of a steal name: a slash makes it an address340// (`kepr.uk/nina`, `http://127.0.0.1:3917/shipped`), a bare name is this machine's own remote. An341// addressed value that is missing either half is an error, never a name.342fn web_address(value string) ![]string {343	if !value.contains('/') {344		return []string{}345	}346	repo := value.all_after_last('/')347	host := value.all_before_last('/')348	if repo == '' || host == '' {349		return error('"${value}" is not <host>/<repo>')350	}351	return [host, repo]352}353354// clone_web fetches a public repo over HTTPS, read-only. Signed in to that Kepr, the same address355// names this machine's own bucket instead, so the bucket's copy — private or not — is the one to356// take.357fn clone_web(host string, repo string, args Args) int {358	base := remote.kepr_host(host) or { return refuse(args.json(), err.msg()) }359	if exchange.signed_in_to(base) {360		return clone_repo(repo, args)361	}362	mut backend := exchange.read_only('${base}/${repo}') or { return refuse(args.json(), err.msg()) }363	return clone_with(repo, args, mut backend, '${base}/${repo}')364}365366// clone_repo fetches a whole repo into ./<name>, for a machine that does not367// have it yet.368fn clone_repo(name string, args Args) int {369	mut backend := this_machine_backend() or { return refuse(args.json(), err.msg()) }370	return clone_with(name, args, mut backend, '')371}372373// clone_with is that fetch, from whichever remote was chosen: the whole history in, then the head's374// files onto the disk. A non-empty `source` means the repo came from a read-only address and stays375// local until this machine signs in there.376fn clone_with(name string, args Args, mut backend remote.Backend, source string) int {377	target := os.join_path(os.getwd(), name)378	if os.exists(target) {379		return refuse(args.json(), '${name} already exists here — run steal inside it instead')380	}381	fetched := exchange.fetch_repo(mut backend, name) or { return refuse(args.json(), err.msg()) }382	store := land_clone(target, name, fetched, source) or {383		os.rmdir_all(target) or {}384		return refuse(args.json(), err.msg())385	}386	// Anything that goes wrong from here leaves the folder half-made, and a retry would refuse it387	// as "already exists", so the whole clone goes.388	mut finished := false389	defer {390		store.close()391		if !finished {392			os.rmdir_all(target) or {}393		}394	}395	files := history.files_of(store, fetched.head) or { return refuse(args.json(), err.msg()) }396	snapshot.restore_files(store, target, snapshot.Ignore{}, files, []) or {397		return refuse(args.json(), err.msg())398	}399	mut flagged := []events.Flag{}400	for _, flag in events.latest_flags(store) or { return refuse(args.json(), err.msg()) } {401		if flag.flagged {402			flagged << flag403		}404	}405	flagged.sort(a.save_id < b.save_id)406	finished = true407	if args.json() {408		emit_json(json2.encode(StolenJson{409			repo:    name410			forward: true411			saves:   fetched.saves.len412			objects: fetched.repo_objects.len413			events:  fetched.events_out.len414			head:    fetched.head415			flagged: flagged.map(it.save_id)416		}))417		return 0418	}419	ok('fetched "${name}" into ${target}')420	note('${fetched.saves.len} saves at [${fetched.head}]')421	if source != '' {422		note('read-only: this clone keeps up with ${source} — sign in with "koh remote ${exchange.source_host(source)}" to make it yours')423	}424	warn_flagged(flagged)425	return 0426}427428// land_clone creates ./<name> and commits the fetched history into it. Objects429// are checked on the way in, so a damaged remote fails here.430fn land_clone(target string, name string, fetched exchange.Fetched, source string) !storage.Store {431	// SQLite creates the file, not the folder holding it.432	os.mkdir_all(target, os.MkdirParams{})!433	mut store := storage.create(target)!434	fill_clone(store, name, fetched, source) or {435		store.rollback()436		store.close()437		return err438	}439	return store440}441442fn fill_clone(store &storage.Store, name string, fetched exchange.Fetched, source string) ! {443	store.begin()!444	exchange.write_fetched(store, fetched)!445	history.set_head(store, fetched.head)!446	exchange.remember_repo(store, name)!447	if source != '' {448		exchange.remember_source(store, source)!449	}450	snapshot.mark_restore(store)!451	store.commit()!452}453454// warn_flagged prints the line the document asks for, per incoming flagged save.455fn warn_flagged(flags []events.Flag) {456	for flag in flags {457		reason := if flag.reason != '' { ' — ${flag.reason}' } else { '' }458		warn('[${flag.save_id}] came in flagged${reason}')459	}460}461462struct ReposJson {463	repos []string464}465466struct StolenJson {467	repo          string468	forward       bool469	saves         int470	objects       int471	events        int472	clashes       []string473	replayed      int474	kept_mine     int475	head          string476	offer_failed  bool477	flagged       []string478	previous_head string479	kept_versions []string480}