cmd_back.v

10.0 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.storage1819// cmd_undo goes back one save, N saves, or to before the current --session. Unsaved changes refuse it.20pub fn cmd_undo(raw []string) int {21	args := parse('undo', raw, Options{22		flags: ['session', 'yes', 'json']23	}) or { return usage_error(err.msg()) }24	store := open_store() or { return refuse(args.json(), err.msg()) }25	defer {26		store.close()27	}28	effective := history.effective(store) or { return refuse(args.json(), err.msg()) }29	mut target := history.Save{}30	if args.flag('session') {31		start := history.session_start(store, effective.id) or {32			return refuse(args.json(), err.msg())33		}34		if start.parent == '' {35			return refuse(args.json(), 'there is nothing before session "${fmt.safe_text(start.session)}"')36		}37		target = history.by_id(store, start.parent) or { return refuse(args.json(), err.msg()) }38	} else {39		mut steps := 140		if args.positional.len > 0 {41			steps = args.positional_at(0).int()42			if steps < 1 {43				return usage_error('undo takes a positive number of saves')44			}45		}46		target = history.step_back(store, effective.id, steps) or {47			return refuse(args.json(), err.msg())48		}49	}50	return going_back(store, target, 'undo', args, false)51}5253// cmd_revert puts the tree back to head, checkpointing what is there first, and finishes a restore that54// stopped part way.55pub fn cmd_revert(raw []string) int {56	args := parse('revert', raw, Options{57		flags: ['yes', 'json']58	}) or { return usage_error(err.msg()) }59	store := open_store() or { return refuse(args.json(), err.msg()) }60	defer {61		store.close()62	}63	head := history.head(store) or {64		return refuse(args.json(), 'this repo has no saves yet — nothing to revert to')65	}66	changes := compare_with_head(store, head) or { return refuse(args.json(), err.msg()) }67	if !changes.dirty {68		// The files all landed before whatever stopped the last restore.69		snapshot.clear_restore_mark(store) or { return refuse(args.json(), err.msg()) }70		if args.json() {71			emit_json(json2.encode(RevertJson{72				reverted: false73				head_id:  head.id74			}))75			return 076		}77		ok('working tree already matches [${head.id}]')78		return 079	}80	// The state about to be discarded is recorded as a checkpoint, so a revert81	// is itself undoable. `record_discard` does that only after the answer.82	return going_back(store, head, 'revert', args, true)83}8485// cmd_load restores any save, or the newest checkpoint with --checkpoint. Unsaved changes refuse it;86// --json needs --yes.87pub fn cmd_load(raw []string) int {88	args := parse('load', raw, Options{89		flags: ['checkpoint', 'yes', 'json']90	}) or { return usage_error(err.msg()) }91	store := open_store() or { return refuse(args.json(), err.msg()) }92	defer {93		store.close()94	}95	mut target := history.Save{}96	if args.flag('checkpoint') {97		target = history.latest_checkpoint(store) or {98			return refuse(args.json(), 'this repo has no checkpoints')99		}100	} else {101		id := args.positional_at(0)102		if id == '' {103			return usage_error('load needs a save ID, or --checkpoint')104		}105		target = history.resolve(store, id) or { return refuse(args.json(), err.msg()) }106	}107	return going_back(store, target, 'load', args, false)108}109110// going_back is the shared path. `discard_first` is revert's extra step: record111// the changes being thrown away before restoring.112fn going_back(store &storage.Store, target history.Save, verb string, args Args, discard_first bool) int {113	as_json := args.json()114	if as_json && !args.flag('yes') {115		return refuse(true, 'needs --yes when not interactive')116	}117	preview := plan_restore(store, target, !discard_first) or { return refuse(as_json, err.msg()) }118	if !as_json {119		ok('${verb}: [${target.id}]  ${fmt.safe_text(target.message)}')120		for delta in preview.deltas {121			println('  ${change_mark(delta.kind)} ${delta.path}')122		}123		note('${fmt.plural(preview.deltas.len, 'file')} change  ·  ${fmt.plural(preview.remove.len, 'file')} removed')124	}125	approved := confirm(args.flag('yes')) or { return refuse(as_json, err.msg()) }126	if !approved {127		return 1128	}129	// The tree may have changed while the prompt waited, so the restore acts on130	// a fresh plan; the one above only drew the preview.131	plan := plan_restore(store, target, !discard_first) or {132		return refuse(as_json, err.msg())133	}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	// A revert's restore save sits right on the checkpoint of what it threw away.140	kept := if discard_first { save.parent } else { '' }141	if as_json {142		emit_json(json2.encode(BackJson{143			id:         save.id144			restores:   target.id145			written:    report.written146			removed:    report.removed147			discarded:  discard_first148			checkpoint: kept149		}))150		return 0151	}152	ok('restored [${save.id}]  ${fmt.safe_text(save.message)}')153	if kept != '' {154		note('the discarded changes are kept in [${kept}] — koh load ${kept} brings them back')155	}156	return 0157}158159// apply_restore records the going-back as a new save. It does not touch the160// working tree and does not ask anything: the history view has already asked,161// and the order still has to be save-first, files-second.162pub fn apply_restore(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool) !history.Save {163	// A revert may be finishing an earlier restore; that one's mark stays164	// until the files are right.165	earlier := snapshot.restore_pending(store)166	snapshot.mark_restore(store)!167	return record_restore(store, target, verb, plan, discard_first) or {168		// Nothing moved, so this restore has nothing to finish. A mark that169		// cannot be lifted only means revert is suggested once needlessly.170		if !earlier {171			snapshot.clear_restore_mark(store) or {}172		}173		return err174	}175}176177fn record_restore(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool) !history.Save {178	discarded := if discard_first {179		snapshot.walk(store, store.root, snapshot.load(store.root))!180	} else {181		[]snapshot.FileEntry{}182	}183	// One transaction, as the document asks of every history change; it also184	// keeps the discard checkpoint the restore save's parent, which is how185	// revert names it.186	store.begin()!187	save := record_both(store, target, verb, plan, discard_first, discarded) or {188		store.rollback()189		return err190	}191	store.end()!192	history.refresh_log_md(store)193	return save194}195196fn record_both(store &storage.Store, target history.Save, verb string, plan RestorePlan, discard_first bool, discarded []snapshot.FileEntry) !history.Save {197	if discard_first {198		// Recorded even while a restore is unfinished: finishing it is what199		// revert is for.200		history.record_save(store, store.root, discarded, history.SaveInput{201			message:       'revert: discarded changes'202			is_checkpoint: true203		})!204	}205	return history.record_save(store, '', plan.files, history.SaveInput{206		message:  '${verb}: ${target.id}'207		restores: target.id208	})!209}210211// restore_now performs a whole restore without prompting: the plan, the save212// and the files. The history view uses it for its `l` key.213pub fn restore_now(store &storage.Store, target history.Save, verb string) !history.Save {214	plan := plan_restore(store, target, true)!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, from one walk of the tree.241// With `check_clean` it also refuses a tree holding work only the disk has: undo and load only run on242// a clean tree, so those are tracked files, and revert has recorded the rest.243fn plan_restore(store &storage.Store, target history.Save, check_clean bool) !RestorePlan {244	if check_clean && snapshot.restore_pending(store) {245		return error(snapshot.restore_unfinished)246	}247	mut hashing := reading()248	walked := snapshot.walk_report(store, store.root, snapshot.load(store.root), mut hashing)!249	if check_clean {250		if head := history.head(store) {251			if compare_walked(history.files_of(store, head.id)!, walked).dirty {252				return error(unsaved_changes)253			}254		}255	}256	files := history.files_of(store, target.id)!257	snapshot.check_links(store.root, files)!258	mut wanted := map[string]bool{}259	for file in files {260		wanted[file.path] = true261	}262	mut remove := []string{}263	for file in walked.files {264		if file.path !in wanted {265			remove << file.path266		}267	}268	deltas := snapshot.changes(walked.files, files)269	return RestorePlan{270		files:  files271		remove: remove272		deltas: deltas273	}274}275276fn change_mark(kind string) string {277	if kind == 'added' {278		return fmt.green('+')279	}280	if kind == 'removed' {281		return fmt.red('-')282	}283	return fmt.amber('~')284}285286struct BackJson {287	id         string288	restores   string289	written    int290	removed    int291	discarded  bool292	checkpoint string // revert only: the checkpoint holding what was discarded293}294295struct RevertJson {296	reverted bool297	head_id  string298}