cmd_back.v

9.3 KB · raw

1//! Going back: `koh undo`, `koh revert` and `koh load`.2//!3//! Nothing here rewinds history. A going-back command restores an earlier tree4//! and records that as a new save whose `restores` field names the save it5//! brought back, so the move itself can be undone.6//!7//! The order matters and is the same everywhere: show what will change, ask,8//! record the new save, then write the files. Recording before writing means a9//! crash mid-restore shows up in `status` and `revert` finishes it.1011module cli1213import json214import src.fmt15import src.history16import src.snapshot17import src.storage1819pub fn cmd_undo(raw []string) int {20	args := parse('undo', raw, Options{21		flags: ['session', 'yes', 'json']22	}) or { return usage_error(err.msg()) }23	store := open_store() or { return refuse(args.json(), err.msg()) }24	defer {25		store.close()26	}27	effective := history.effective(store) or { return refuse(args.json(), err.msg()) }28	mut target := history.Save{}29	if args.flag('session') {30		start := history.session_start(store, effective.id) or {31			return refuse(args.json(), err.msg())32		}33		if start.parent == '' {34			return refuse(args.json(), 'there is nothing before session "${start.session}"')35		}36		target = history.by_id(store, start.parent) or { return refuse(args.json(), err.msg()) }37	} else {38		mut steps := 139		if args.positional.len > 0 {40			steps = args.positional_at(0).int()41			if steps < 1 {42				return usage_error('undo takes a positive number of saves')43			}44		}45		target = history.step_back(store, effective.id, steps) or {46			return refuse(args.json(), err.msg())47		}48	}49	return going_back(store, target, 'undo', args, false)50}5152pub fn cmd_revert(raw []string) int {53	args := parse('revert', raw, Options{54		flags: ['yes', 'json']55	}) or { return usage_error(err.msg()) }56	store := open_store() or { return refuse(args.json(), err.msg()) }57	defer {58		store.close()59	}60	head := history.head(store) or {61		return refuse(args.json(), 'this repo has no saves yet — nothing to revert to')62	}63	changes := compare_with_head(store, head) or { return refuse(args.json(), err.msg()) }64	if !changes.dirty {65		// The files all landed before whatever stopped the last restore.66		snapshot.clear_restore_mark(store) or { return refuse(args.json(), err.msg()) }67		if args.json() {68			emit_json(json2.encode(RevertJson{69				reverted: false70				head_id:  head.id71			}))72			return 073		}74		ok('working tree already matches [${head.id}]')75		return 076	}77	// The state about to be discarded is recorded as a checkpoint, so a revert78	// is itself undoable. `record_discard` does that only after the answer.79	return going_back(store, head, 'revert', args, true)80}8182pub fn cmd_load(raw []string) int {83	args := parse('load', raw, Options{84		flags: ['checkpoint', 'yes', 'json']85	}) or { return usage_error(err.msg()) }86	store := open_store() or { return refuse(args.json(), err.msg()) }87	defer {88		store.close()89	}90	mut target := history.Save{}91	if args.flag('checkpoint') {92		target = history.latest_checkpoint(store) or {93			return refuse(args.json(), 'this repo has no checkpoints')94		}95	} else {96		id := args.positional_at(0)97		if id == '' {98			return usage_error('load needs a save ID, or --checkpoint')99		}100		target = history.resolve(store, id) or { return refuse(args.json(), err.msg()) }101	}102	return going_back(store, target, 'load', args, false)103}104105// going_back is the shared path. `discard_first` is revert's extra step: record106// the changes being thrown away before restoring.107fn going_back(store &storage.Store, target history.Save, verb string, args Args, discard_first bool) int {108	as_json := args.json()109	if as_json && !args.flag('yes') {110		return refuse(true, 'needs --yes when not interactive')111	}112	if !discard_first {113		require_clean(store) or { return refuse(as_json, err.msg()) }114	}115	preview := plan_restore(store, target) or { return refuse(as_json, err.msg()) }116	if !as_json {117		ok('${verb}: [${target.id}]  ${target.message}')118		for delta in preview.deltas {119			println('  ${change_mark(delta.kind)} ${delta.path}')120		}121		note('${fmt.plural(preview.deltas.len, 'file')} change  ·  ${fmt.plural(preview.remove.len, 'file')} removed')122	}123	approved := confirm(args.flag('yes')) or { return refuse(as_json, err.msg()) }124	if !approved {125		return 1126	}127	// The tree may have changed while the prompt waited, so the restore acts on128	// a fresh plan; the one above only drew the preview.129	if !discard_first {130		require_clean(store) or { return refuse(as_json, err.msg()) }131	}132	plan := plan_restore(store, target) or { return refuse(as_json, err.msg()) }133	save := apply_restore(store, target, verb, plan, discard_first) or {134		return refuse(as_json, err.msg())135	}136	report := snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files,137		plan.remove) or { return refuse(as_json, err.msg()) }138	// A revert's restore save sits right on the checkpoint of what it threw away.139	kept := if discard_first { save.parent } else { '' }140	if as_json {141		emit_json(json2.encode(BackJson{142			id:         save.id143			restores:   target.id144			written:    report.written145			removed:    report.removed146			discarded:  discard_first147			checkpoint: kept148		}))149		return 0150	}151	ok('restored [${save.id}]  ${save.message}')152	if kept != '' {153		note('the discarded changes are kept in [${kept}] — koh load ${kept} brings them back')154	}155	return 0156}157158// apply_restore records the going-back as a new save. It does not touch the159// working tree and does not ask anything: the history view has already asked,160// and the order still has to be save-first, files-second.161pub fn apply_restore(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool) !history.Save {162	// A revert may be finishing an earlier restore; that one's mark stays163	// until the files are right.164	earlier := snapshot.restore_pending(store)165	snapshot.mark_restore(store)!166	return record_restore(store, target, verb, plan, discard_first) or {167		// Nothing moved, so this restore has nothing to finish. A mark that168		// cannot be lifted only means revert is suggested once needlessly.169		if !earlier {170			snapshot.clear_restore_mark(store) or {}171		}172		return err173	}174}175176fn record_restore(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool) !history.Save {177	discarded := if discard_first {178		snapshot.walk(store, store.root, snapshot.load(store.root))!179	} else {180		[]snapshot.FileEntry{}181	}182	// One transaction, as the document asks of every history change; it also183	// keeps the discard checkpoint the restore save's parent, which is how184	// revert names it.185	store.begin()!186	save := record_both(store, target, verb, plan, discard_first, discarded) or {187		store.rollback()188		return err189	}190	store.end()!191	history.refresh_log_md(store)192	return save193}194195fn record_both(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool, discarded []snapshot.FileEntry) !history.Save {196	if discard_first {197		// Recorded even while a restore is unfinished: finishing it is what198		// revert is for.199		history.record_save(store, store.root, discarded, history.SaveInput{200			message:       'revert: discarded changes'201			is_checkpoint: true202		})!203	}204	return history.record_save(store, '', plan.files, history.SaveInput{205		message:  '${verb}: ${target.id}'206		restores: target.id207	})!208}209210// restore_now performs a whole restore without prompting: the plan, the save211// and the files. The history view uses it for its `l` key.212pub fn restore_now(store &storage.Store, target history.Save, verb string) !history.Save {213	require_clean(store)!214	plan := plan_restore(store, target)!215	save := apply_restore(store, target, verb, plan, false)!216	snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files, plan.remove)!217	return save218}219220struct RestorePlan {221	files  []snapshot.FileEntry222	remove []string223	deltas []snapshot.Delta224}225226const unsaved_changes = 'unsaved changes — save or checkpoint first, or discard them with koh revert'227228// require_clean refuses to restore over work only the disk has, as Koh 2 did.229// `revert` is the one going-back that may discard it, and it records it first.230fn require_clean(store &storage.Store) ! {231	if snapshot.restore_pending(store) {232		return error(snapshot.restore_unfinished)233	}234	head := history.head(store) or { return }235	if compare_with_head(store, head)!.dirty {236		return error(unsaved_changes)237	}238}239240// plan_restore works out what writing `target` back onto disk involves. Every241// file on disk the target lacks goes: undo, load and pluck only run on a clean242// tree, so those are tracked files, and revert has recorded the rest.243fn plan_restore(store &storage.Store, target history.Save) !RestorePlan {244	files := history.files_of(store, target.id)!245	snapshot.check_links(store.root, files)!246	mut wanted := map[string]bool{}247	for file in files {248		wanted[file.path] = true249	}250	from := working_tree(store)!251	mut remove := []string{}252	for file in from.files {253		if file.path !in wanted {254			remove << file.path255		}256	}257	deltas := snapshot.changes(from.files, files)258	return RestorePlan{259		files:  files260		remove: remove261		deltas: deltas262	}263}264265fn change_mark(kind string) string {266	if kind == 'added' {267		return fmt.green('+')268	}269	if kind == 'removed' {270		return fmt.red('-')271	}272	return fmt.amber('~')273}274275struct BackJson {276	id         string277	restores   string278	written    int279	removed    int280	discarded  bool281	checkpoint string // revert only: the checkpoint holding what was discarded282}283284struct RevertJson {285	reverted bool286	head_id  string287}