cmd_steal.v

19.1 KB · raw

1//! `koh steal` — bring another machine's saves in.2//!3//! Inside a repo this takes 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.view19import time2021pub fn cmd_steal(raw []string) int {22	args := parse('steal', raw, Options{23		flags: ['list', 'mine', 'theirs', 'json', 'yes']24	}) or { return usage_error(err.msg()) }25	if args.flag('list') {26		if args.positional.len > 0 {27			return usage_error('steal --list takes no arguments')28		}29		return list_repos(args)30	}31	if storage.find_root(os.getwd()) == none {32		name := args.positional_at(0)33		if name == '' {34			return usage_error('steal needs a repo name outside a repo, e.g. koh steal myproject')35		}36		if args.positional.len > 1 {37			return usage_error('steal takes one repo: koh steal myproject, or koh steal kepr.uk/nina')38		}39		// A bare name becomes both a remote key and a folder here, so it obeys the40		// same rule before anything is asked of a remote.41		if !name.contains('/') && !exchange.valid_repo_name(name) {42			return usage_error('"${name}" is not a repo name — a repo name is letters, digits, ., _ and -')43		}44		address := web_address(name) or { return refuse(args.json(), err.msg()) }45		if address.len > 0 {46			return steal_web(address[0], address[1], args)47		}48		return steal_repo(name, args)49	}50	store := open_store() or { return refuse(args.json(), err.msg()) }51	defer {52		store.close()53	}54	if args.positional.len > 0 {55		return usage_error('steal takes no name inside a repo — run it outside to fetch a whole repo')56	}57	guided := on_terminal(args.json())58	if guided {59		if !ready_to_steal() {60			return 161		}62	}63	// A stolen repo has its own remote: the address it came from, until this machine signs in to64	// that Kepr, when the bucket takes over.65	source := exchange.source_of(store)66	upgraded := source != '' && exchange.signed_in_to(exchange.source_host(source))67	read_only := source != '' && !upgraded68	mut backend := if read_only {69		remote.Backend(watch('stealing', exchange.read_only(source) or {70			return refuse(args.json(), err.msg())71		}))72	} else {73		watched_backend('stealing') or { return refuse(args.json(), err.msg()) }74	}75	mut options := exchange.StealOptions{76		mine:    args.flag('mine')77		theirs:  args.flag('theirs')78		yes:     args.flag('yes')79		json:    args.json()80		approve: approve_sync81	}82	if guided {83		options.guide = guide_steal84	}85	report := exchange.steal(store, mut backend, options) or { return refuse(args.json(), err.msg()) }86	if upgraded {87		exchange.forget_source(store) or { return refuse(args.json(), err.msg()) }88		if !args.json() {89			ok('signed in to ${exchange.source_host(source)}: this repo now syncs with your bucket')90		}91	}92	// The remote should end up with whatever this machine just decided — unless there is no remote93	// to write to: a repo still riding its source stays read-only, and quietly so.94	offer_failed := !read_only && !offer_after_steal(store, mut backend)95	if args.json() {96		emit_json(json2.encode(StolenJson{97			repo:          report.repo98			forward:       report.forward99			saves:         report.fetched_saves100			objects:       report.fetched_objects101			events:        report.fetched_events102			clashes:       report.clashes103			replayed:      report.replayed104			kept_mine:     report.kept_mine105			head:          report.head106			offer_failed:  offer_failed107			flagged:       report.flagged.map(it.save_id)108			previous_head: report.previous_head109			kept_versions: report.kept_versions110			unsafe_paths:  report.unsafe_paths111		}))112		return 0113	}114	print_steal(report, guided, read_only, offer_failed)115	return 0116}117118// print_steal tells the person how a finished steal went: what came in, what the two machines119// disagreed on, and how to get back.120fn print_steal(report exchange.StealReport, guided bool, read_only bool, offer_failed bool) {121	if report.fetched_saves == 0 {122		ok('already up to date with "${report.repo}" — head is [${report.head}]')123		return124	}125	if report.forward {126		if guided {127			ok('${report.repo} is up to date · ${fmt.plural(report.fetched_saves, 'new save')}')128		} else {129			ok('brought in ${fmt.plural(report.fetched_saves, 'save')} from "${report.repo}" — head is now [${report.head}]')130		}131	} else {132		ok(if !guided {133			'brought in ${fmt.plural(report.fetched_saves, 'save')} from "${report.repo}"'134		} else if read_only || offer_failed {135			'combined'136		} else {137			'combined · offered to ${report.repo}'138		})139		if read_only {140			note('your saves stay on this machine (read-only source)')141		} else if !guided {142			note("replayed ${report.replayed} of this machine's saves onto the remote head")143		}144		if guided {145			note_choices(report)146		} else if report.kept_mine > 0 {147			note('kept mine for ${fmt.plural(report.kept_mine, 'file')}')148		}149		if guided {150			note('to undo all of it: koh load ${report.previous_head}')151		} else {152			note('the tree from before is kept — koh load ${report.previous_head} brings it back, less anything stripped')153		}154		note_kept_versions(report)155	}156	warn_flagged(report.flagged)157	warn_unsafe_paths(report.unsafe_paths)158	if report.clashes.len > 0 {159		note('${report.clashes.len} changed on both machines: ${report.clashes.join(', ')}')160	}161	if offer_failed {162		warn('the remote was not updated — run "koh offer" when it is reachable again')163	}164}165166// on_terminal is when a steal asks rather than refuses: a person at both ends, and no --json.167fn on_terminal(json bool) bool {168	return !json && interactive() && os.is_atty(1) != 0169}170171// note_kept_versions names, for each file answered "theirs", the save that still holds this172// machine's version.173fn note_kept_versions(report exchange.StealReport) {174	// `<path>:<save>`: a save ID has no colon, a path may.175	for kept in report.kept_versions {176		path := kept.all_before_last(':')177		save := kept.all_after_last(':')178		note('your ${path} is in ${save} · koh peek ${save}')179	}180}181182// note_choices is the done screen's line of answers: `kept mine: a · took theirs: b`.183fn note_choices(report exchange.StealReport) {184	theirs := report.kept_versions.map(it.all_before_last(':'))185	mine := report.clashes.filter(it !in theirs)186	mut parts := []string{}187	if mine.len > 0 {188		parts << 'kept mine: ${mine.join(' · ')}'189	}190	if theirs.len > 0 {191		parts << 'took theirs: ${theirs.join(' · ')}'192	}193	if parts.len > 0 {194		note(parts.join(' · '))195	}196}197198// ready_to_steal is the guided steal's first step: with unsaved work it offers checkpoint, save or stop,199// and answers whether to go on. A tree it cannot read counts as ready.200fn ready_to_steal() bool {201	store := open_store() or { return true }202	head := history.head(store)203	dirty := exchange.dirty(store, head) or {204		store.close()205		return true206	}207	if !dirty {208		store.close()209		return true210	}211	paths := unsaved_paths(store, head) or { []string{} }212	name := os.base(store.root)213	store.close()214	println('  ${fmt.gold('${fmt.glyph_ok} steal ${name}')}')215	println('')216	println('  you have ${fmt.plural(paths.len, 'unsaved file')}')217	if paths.len > 0 {218		println('    ${paths[..if paths.len < 5 { paths.len } else { 5 }].join(' · ')}')219		if paths.len > 5 {220			println('    and ${paths.len - 5} more')221		}222	}223	println('')224	println('  [c] checkpoint them and continue')225	println('  [s] save them with a message and continue')226	println('  [q] stop here')227	print('  › ')228	match os.get_line().trim_space() {229		'c' { return cmd_save(['before steal'], true) == 0 }230		's' {231			print('  message: ')232			message := os.get_line().trim_space()233			if message == '' {234				println('  no message — nothing was saved')235				return false236			}237			return cmd_save([message], false) == 0238		}239		else { return false }240	}241}242243fn unsaved_paths(store &storage.Store, head ?history.Save) ![]string {244	now := snapshot.index_files(snapshot.walk(store, store.root, snapshot.load(store.root))!)245	before := if save := head {246		snapshot.index_files(history.files_of(store, save.id)!)247	} else {248		map[string]snapshot.FileEntry{}249	}250	mut paths := []string{}251	for path, file in now {252		old := before[path] or { snapshot.FileEntry{} }253		if file.hash != old.hash || file.executable != old.executable {254			paths << path255		}256	}257	for path, _ in before {258		if path !in now {259			paths << path260		}261	}262	paths.sort()263	return paths264}265266// guide_steal is the terminal walk-through steal calls as `guide`: overview, one prompt per clash (`b`267// steps back), then the summary and confirm. It returns each clash's side; quitting or declining cancels268// with an error, and the line and tree are unchanged. --mine/--theirs answer the clashes, not the summary.269fn guide_steal(preview exchange.StealPreview) !map[string]exchange.Side {270	done_working()271	_, columns := view.terminal_size()272	width := if columns > 0 && columns < 80 { columns } else { 80 }273	println('')274	println('  ${fmt.gold('you')} and ${fmt.blue(preview.repo)} both moved since ${preview.base.id} · ${ago(preview.base.created_at)}')275	println('')276	println(overview_row('    ${fmt.gold('you')}      ${fmt.plural(preview.local.len, 'save')}  ${messages(preview.local.map(it.message))}',277		width))278	println(overview_row('    ${fmt.blue('remote')}   ${fmt.plural(preview.remote.len, 'save')}  ${messages(preview.remote.map(it.message))}',279		width))280	println('')281	println('  ${fmt.plural(preview.changed, 'file')} changed')282	println('    ${fmt.green('✓')} ${preview.automatic} combine by themselves')283	println('    ${fmt.green('✓')} ${preview.identical} changed the same way on both sides')284	println('    ${fmt.amber('!')} ${preview.clashes.len} ${if preview.clashes.len == 1 {285		'needs'286	} else {287		'need'288	}} you')289	mut answers := map[string]exchange.Side{}290	if preview.all_side != '' {291		for clash in preview.clashes {292			answers[clash.path] = if preview.all_side == 'mine' { .mine } else { .theirs }293		}294	}295	mut at := if preview.all_side == '' { 0 } else { preview.clashes.len }296	for at < preview.clashes.len {297		clash := preview.clashes[at]298		println('')299		println('  ── ${at + 1} of ${preview.clashes.len} · ${clash.path} ──')300		println(fmt.fit('    ${fmt.gold('you')}      ${clash.mine_stat}   ${fmt.safe_text(clash.mine_save.message)} · ${ago(clash.mine_save.created_at)} · ${fmt.safe_text(clash.mine_save.machine)}',301			width))302		println(fmt.fit('    ${fmt.blue('remote')}   ${clash.theirs_stat}   ${fmt.safe_text(clash.theirs_save.message)} · ${ago(clash.theirs_save.created_at)} · ${fmt.safe_text(clash.theirs_save.machine)}',303			width))304		println('')305		println('  [m] keep mine   [t] take theirs   [d] see both changes')306		println('  [b] back   [?] help')307		print('  › ')308		match os.get_line().trim_space() {309			'm' {310				answers[clash.path] = .mine311				at++312			}313			't' {314				answers[clash.path] = .theirs315				at++316			}317			'b' {318				if at > 0 { at-- }319			}320			'd' { show_clash(clash) }321			'?' {322				println('  mine keeps your version; theirs takes the remote version.')323				println('  Nothing is lost either way; both versions stay in history.')324			}325			'q' { return error('steal cancelled') }326			else {}327		}328	}329	println('')330	println('  ${fmt.gold('ready to combine')}')331	for clash in preview.clashes {332		choice := if answers[clash.path] == .mine { 'keep mine' } else { 'take theirs' }333		println('    ${choice}  ${clash.path}')334	}335	println('    replay your ${fmt.plural(preview.local.len, 'save')} on top of the remote')336	println('    your originals stay in history: ${preview.local.map(it.id).join(' · ')}')337	if !confirm(preview.yes)! {338		return error('steal cancelled')339	}340	return answers341}342343fn messages(items []string) string {344	return items.map('"${fmt.safe_text(it)}"').join(' · ')345}346347// overview_row cuts a row of save messages to the terminal, ending in `· …` when some were left out.348fn overview_row(text string, width int) string {349	if fmt.visible_width(text) <= width {350		return text351	}352	return fmt.fit(text, width - 4) + ' · …'353}354355fn ago(unix_seconds i64) string {356	return time.unix(unix_seconds).relative()357}358359fn show_clash(clash exchange.Clash) {360	if clash.mine_patch == '' && clash.theirs_patch == '' {361		println('  binary file')362		return363	}364	mut lines := ['your changes']365	lines << clash.mine_patch.trim_right('\n').split_into_lines()366	lines << ''367	lines << 'remote changes'368	lines << clash.theirs_patch.trim_right('\n').split_into_lines()369	view.page_text(lines, clash.path)370}371372// offer_after_steal sends what this machine just decided. A failure here does373// not undo the steal; it is reported.374fn offer_after_steal(store &storage.Store, mut backend remote.Backend) bool {375	if _ := exchange.offer(store, mut backend) {376		return true377	}378	return false379}380381// list_repos names the repos on this machine's remote: the first path segment of every key.382fn list_repos(args Args) int {383	mut backend := this_machine_backend() or { return refuse(args.json(), err.msg()) }384	keys := backend.list('') or { return refuse(args.json(), err.msg()) }385	mut names := map[string]bool{}386	for key in keys {387		// A repo is a folder with a `head`. Anything else at the top of the remote, such as388		// Kepr's own `.kepr/` folder of uploads, is not one and cannot be stolen.389		parts := key.trim_left('/').split('/')390		if parts.len == 2 && parts[0] != '' && parts[1] == 'head' {391			names[parts[0]] = true392		}393	}394	mut sorted := names.keys()395	sorted.sort()396	if args.json() {397		emit_json(json2.encode(ReposJson{398			repos: sorted399		}))400		return 0401	}402	if sorted.len == 0 {403		ok('the remote has no repos yet')404		return 0405	}406	for name in sorted {407		println('  ${name}')408	}409	return 0410}411412// web_address splits a `<host>/<repo>` argument out of a steal name: a slash makes it an address413// (`kepr.uk/nina`, `http://127.0.0.1:3917/shipped`), a bare name is this machine's own remote. An414// addressed value that is missing either half is an error, never a name. The repo half becomes a415// URL path segment and a folder here, so it must be a name Kepr serves: letters, digits, `.`, `_`416// and `-`, and never `.` or `..`.417fn web_address(value string) ![]string {418	if !value.contains('/') {419		return []string{}420	}421	repo := value.all_after_last('/')422	host := value.all_before_last('/')423	if host == '' || !exchange.valid_repo_name(repo) {424		return error('"${value}" is not <host>/<repo> — a repo name is letters, digits, ., _ and -')425	}426	return [host, repo]427}428429// steal_web fetches a public repo over HTTPS, read-only. Signed in to that Kepr, the same address430// names this machine's own bucket instead, so the bucket's copy — private or not — is the one to431// take.432fn steal_web(host string, repo string, args Args) int {433	base := remote.kepr_host(host) or { return refuse(args.json(), err.msg()) }434	if exchange.signed_in_to(base) {435		return steal_repo(repo, args)436	}437	mut web := remote.new_web(base) or { return refuse(args.json(), err.msg()) }438	web.on_body = fn [repo] (received u64) {439		working('stealing ${repo} · ${fmt.human_bytes(i64(received))} received')440	}441	return steal_whole(repo, args, web, '${base}/${repo}')442}443444// steal_repo fetches a whole repo into ./<name>, for a machine that does not445// have it yet.446fn steal_repo(name string, args Args) int {447	// Counted against the listings, so the line can say how many of each kind are in.448	backend := Watched{449		label: 'stealing ${name}'450		whole: true451		inner: this_machine_backend() or { return refuse(args.json(), err.msg()) }452	}453	return steal_whole(name, args, backend, '')454}455456// steal_whole is that fetch, from whichever remote was chosen: the whole history in, then the head's457// files onto the disk. A non-empty `source` means the repo came from a read-only address and stays458// local until this machine signs in there.459fn steal_whole(name string, args Args, chosen remote.Backend, source string) int {460	target := os.join_path(os.getwd(), name)461	if os.exists(target) {462		return refuse(args.json(), '${name} already exists here — run steal inside it instead')463	}464	mut backend := chosen465	fetched := exchange.fetch_repo(mut backend, name) or { return refuse(args.json(), err.msg()) }466	store := land_repo(target, name, fetched, source) or {467		os.rmdir_all(target) or {}468		return refuse(args.json(), err.msg())469	}470	// Anything that goes wrong from here leaves the folder half-made, and a retry would refuse it471	// as "already exists", so the whole new folder goes.472	mut finished := false473	defer {474		store.close()475		if !finished {476			os.rmdir_all(target) or {}477		}478	}479	files := history.files_of(store, fetched.head) or { return refuse(args.json(), err.msg()) }480	snapshot.restore_files(store, target, snapshot.Ignore{}, files, []) or {481		return refuse(args.json(), err.msg())482	}483	mut flagged := []events.Flag{}484	for _, flag in events.latest_flags(store) or { return refuse(args.json(), err.msg()) } {485		if flag.flagged {486			flagged << flag487		}488	}489	flagged.sort(a.save_id < b.save_id)490	finished = true491	if args.json() {492		emit_json(json2.encode(StolenJson{493			repo:         name494			forward:      true495			saves:        fetched.saves.len496			objects:      fetched.repo_objects.len497			events:       fetched.events_out.len498			head:         fetched.head499			flagged:      flagged.map(it.save_id)500			unsafe_paths: fetched.unsafe_paths501		}))502		return 0503	}504	ok('fetched "${name}" into ${target}')505	note('${fmt.plural(fetched.saves.len, 'save')} at [${fetched.head}]')506	if source != '' {507		note('read-only: steal keeps this copy up to date from ${source}; run "koh remote ${exchange.source_host(source)}" to offer from it')508	}509	warn_flagged(flagged)510	warn_unsafe_paths(fetched.unsafe_paths)511	return 0512}513514// land_repo creates ./<name> and writes the fetched history into it. Objects515// are checked on the way in, so a damaged remote fails here.516fn land_repo(target string, name string, fetched exchange.Fetched, source string) !storage.Store {517	// SQLite creates the file, not the folder holding it.518	os.mkdir_all(target, os.MkdirParams{})!519	mut store := storage.create(target)!520	fill_repo(store, name, fetched, source) or {521		store.rollback()522		store.close()523		return err524	}525	return store526}527528fn fill_repo(store &storage.Store, name string, fetched exchange.Fetched, source string) ! {529	store.begin()!530	exchange.write_fetched(store, fetched)!531	history.set_head(store, fetched.head)!532	exchange.remember_repo(store, name)!533	if source != '' {534		exchange.remember_source(store, source)!535	}536	snapshot.mark_restore(store)!537	store.end()!538}539540// warn_flagged prints the line the document asks for, per incoming flagged save.541fn warn_flagged(flags []events.Flag) {542	for flag in flags {543		reason := if flag.reason != '' { ' — ${fmt.safe_text(flag.reason)}' } else { '' }544		warn('[${flag.save_id}] came in flagged${reason}')545	}546}547548fn warn_unsafe_paths(paths []string) {549	for path in paths {550		warn('dropped unsafe path ${path}')551	}552}553554struct ReposJson {555	repos []string556}557558struct StolenJson {559	repo          string560	forward       bool561	saves         int562	objects       int563	events        int564	clashes       []string565	replayed      int566	kept_mine     int567	head          string568	offer_failed  bool569	flagged       []string570	previous_head string571	kept_versions []string572	unsafe_paths  []string573}574575fn approve_sync(saves int, incoming_events int, yes bool, json bool) ! {576	if json && !yes {577		return error('needs --yes with --json')578	}579	if interactive() && !json {580		note('apply ${saves} incoming saves and ${incoming_events} events; working files and stripped history may change')581	}582	if !confirm(yes)! {583		return error('nothing was applied')584	}585}