cmd_back.v

7.7 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 json14import 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(json.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,122			'file')} removed')123	}124	approved := confirm(args.flag('yes')) or { return refuse(as_json, err.msg()) }125	if !approved {126		return 1127	}128	// The tree may have changed while the prompt waited, so the restore acts on129	// a fresh plan; the one above only drew the preview.130	if !discard_first {131		require_clean(store) or { return refuse(as_json, err.msg()) }132	}133	plan := plan_restore(store, target) or { return refuse(as_json, err.msg()) }134	save := apply_restore(store, target, verb, plan, discard_first) or {135		return refuse(as_json, err.msg())136	}137	report := snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files,138		plan.remove) or { return refuse(as_json, err.msg()) }139	if as_json {140		emit_json(json.encode(BackJson{141			id:        save.id142			restores:  target.id143			written:   report.written144			removed:   report.removed145			discarded: discard_first146		}))147		return 0148	}149	ok('restored [${save.id}]  ${save.message}')150	return 0151}152153// apply_restore records the going-back as a new save. It does not touch the154// working tree and does not ask anything: the history view has already asked,155// and the order still has to be save-first, files-second.156pub fn apply_restore(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool) !history.Save {157	if discard_first {158		history.commit_worktree(store, store.root, snapshot.load(store.root), history.SaveInput{159			message:       'revert: discarded changes'160			is_checkpoint: true161		})!162	}163	return history.commit_files(store, '', plan.files, history.SaveInput{164		message:  '${verb}: ${target.id}'165		restores: target.id166	})!167}168169// restore_now performs a whole restore without prompting: the plan, the save170// and the files. The history view uses it for its `l` key.171pub fn restore_now(store &storage.Store, target history.Save, verb string) !history.Save {172	require_clean(store)!173	plan := plan_restore(store, target)!174	save := apply_restore(store, target, verb, plan, false)!175	snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files, plan.remove)!176	return save177}178179struct RestorePlan {180	files  []snapshot.FileEntry181	remove []string182	deltas []snapshot.Delta183}184185const unsaved_changes = 'unsaved changes — save or checkpoint first, or discard them with koh revert'186187// require_clean refuses to restore over work only the disk has, as Koh 2 did.188// `revert` is the one going-back that may discard it, and it records it first.189fn require_clean(store &storage.Store) ! {190	if snapshot.restore_pending(store) {191		return error(snapshot.restore_unfinished)192	}193	head := history.head(store) or { return }194	if compare_with_head(store, head)!.dirty {195		return error(unsaved_changes)196	}197}198199// plan_restore works out what writing `target` back onto disk involves. Every200// file on disk the target lacks goes: undo, load and pluck only run on a clean201// tree, so those are tracked files, and revert has recorded the rest.202fn plan_restore(store &storage.Store, target history.Save) !RestorePlan {203	files := history.files_of(store, target.id)!204	snapshot.check_links(store.root, files)!205	mut wanted := map[string]bool{}206	for file in files {207		wanted[file.path] = true208	}209	from := working_tree(store)!210	mut remove := []string{}211	for file in from.files {212		if file.path !in wanted {213			remove << file.path214		}215	}216	deltas := snapshot.changes(from.files, files)217	return RestorePlan{218		files:  files219		remove: remove220		deltas: deltas221	}222}223224fn change_mark(kind string) string {225	if kind == 'added' {226		return fmt.green('+')227	}228	if kind == 'removed' {229		return fmt.red('-')230	}231	return fmt.amber('~')232}233234struct BackJson {235	id        string236	restores  string237	written   int238	removed   int239	discarded bool240}241242struct RevertJson {243	reverted bool244	head_id  string245}