cmd_back.v

8.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 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	// A revert may be finishing an earlier restore; that one's mark stays158	// until the files are right.159	earlier := snapshot.restore_pending(store)160	snapshot.mark_restore(store)!161	return record_restore(store, target, verb, plan, discard_first) or {162		// Nothing moved, so this restore has nothing to finish. A mark that163		// cannot be lifted only means revert is suggested once needlessly.164		if !earlier {165			snapshot.clear_restore_mark(store) or {}166		}167		return err168	}169}170171fn record_restore(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool) !history.Save {172	if discard_first {173		history.commit_worktree(store, store.root, snapshot.load(store.root), history.SaveInput{174			message:       'revert: discarded changes'175			is_checkpoint: true176		})!177	}178	return history.commit_files(store, '', plan.files, history.SaveInput{179		message:  '${verb}: ${target.id}'180		restores: target.id181	})!182}183184// restore_now performs a whole restore without prompting: the plan, the save185// and the files. The history view uses it for its `l` key.186pub fn restore_now(store &storage.Store, target history.Save, verb string) !history.Save {187	require_clean(store)!188	plan := plan_restore(store, target)!189	save := apply_restore(store, target, verb, plan, false)!190	snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files, plan.remove)!191	return save192}193194struct RestorePlan {195	files  []snapshot.FileEntry196	remove []string197	deltas []snapshot.Delta198}199200const unsaved_changes = 'unsaved changes — save or checkpoint first, or discard them with koh revert'201202// require_clean refuses to restore over work only the disk has, as Koh 2 did.203// `revert` is the one going-back that may discard it, and it records it first.204fn require_clean(store &storage.Store) ! {205	if snapshot.restore_pending(store) {206		return error(snapshot.restore_unfinished)207	}208	head := history.head(store) or { return }209	if compare_with_head(store, head)!.dirty {210		return error(unsaved_changes)211	}212}213214// plan_restore works out what writing `target` back onto disk involves. Every215// file on disk the target lacks goes: undo, load and pluck only run on a clean216// tree, so those are tracked files, and revert has recorded the rest.217fn plan_restore(store &storage.Store, target history.Save) !RestorePlan {218	files := history.files_of(store, target.id)!219	snapshot.check_links(store.root, files)!220	mut wanted := map[string]bool{}221	for file in files {222		wanted[file.path] = true223	}224	from := working_tree(store)!225	mut remove := []string{}226	for file in from.files {227		if file.path !in wanted {228			remove << file.path229		}230	}231	deltas := snapshot.changes(from.files, files)232	return RestorePlan{233		files:  files234		remove: remove235		deltas: deltas236	}237}238239fn change_mark(kind string) string {240	if kind == 'added' {241		return fmt.green('+')242	}243	if kind == 'removed' {244		return fmt.red('-')245	}246	return fmt.amber('~')247}248249struct BackJson {250	id        string251	restores  string252	written   int253	removed   int254	discarded bool255}256257struct RevertJson {258	reverted bool259	head_id  string260}