//! Going back: `koh undo`, `koh revert` and `koh load`. //! //! Nothing here rewinds history. A going-back command restores an earlier tree //! and records that as a new save whose `restores` field names the save it //! brought back, so the move itself can be undone. //! //! The order matters and is the same everywhere: show what will change, ask, //! record the new save, then write the files. Recording before writing means a //! crash mid-restore shows up in `status` and `revert` finishes it. module cli import json import src.history import src.snapshot import src.storage pub fn cmd_undo(raw []string) int { args := parse('undo', raw, Options{ flags: ['session', 'yes', 'json'] }) or { return usage_error(err.msg()) } store := open_store() or { return refuse(args.json(), err.msg()) } defer { store.close() } effective := history.effective(store) or { return refuse(args.json(), err.msg()) } mut target := history.Save{} if args.flag('session') { start := history.session_start(store, effective.id) or { return refuse(args.json(), err.msg()) } if start.parent == '' { return refuse(args.json(), 'there is nothing before session "${start.session}"') } target = history.by_id(store, start.parent) or { return refuse(args.json(), err.msg()) } } else { mut steps := 1 if args.positional.len > 0 { steps = args.positional_at(0).int() if steps < 1 { return usage_error('undo takes a positive number of saves') } } target = history.step_back(store, effective.id, steps) or { return refuse(args.json(), err.msg()) } } return going_back(store, target, 'undo', args, false) } pub fn cmd_revert(raw []string) int { args := parse('revert', raw, Options{ flags: ['yes', 'json'] }) or { return usage_error(err.msg()) } store := open_store() or { return refuse(args.json(), err.msg()) } defer { store.close() } head := history.head(store) or { return refuse(args.json(), 'this repo has no saves yet — nothing to revert to') } changes := compare_with_head(store, head) or { return refuse(args.json(), err.msg()) } if !changes.dirty { if args.json() { emit_json(json.encode(RevertJson{ reverted: false head_id: head.id })) return 0 } ok('working tree already matches [${head.id}]') return 0 } // The state about to be discarded is recorded as a checkpoint, so a revert // is itself undoable. `record_discard` does that only after the answer. return going_back(store, head, 'revert', args, true) } pub fn cmd_load(raw []string) int { args := parse('load', raw, Options{ flags: ['checkpoint', 'yes', 'json'] }) or { return usage_error(err.msg()) } store := open_store() or { return refuse(args.json(), err.msg()) } defer { store.close() } mut target := history.Save{} if args.flag('checkpoint') { target = history.latest_checkpoint(store) or { return refuse(args.json(), 'this repo has no checkpoints') } } else { id := args.positional_at(0) if id == '' { return usage_error('load needs a save ID, or --checkpoint') } target = history.resolve(store, id) or { return refuse(args.json(), err.msg()) } } return going_back(store, target, 'load', args, false) } // going_back is the shared path. `discard_first` is revert's extra step: record // the changes being thrown away before restoring. fn going_back(store &storage.Store, target history.Save, verb string, args Args, discard_first bool) int { as_json := args.json() if as_json && !args.flag('yes') { return refuse(true, 'needs --yes when not interactive') } plan := plan_restore(store, target, discard_first) or { return refuse(as_json, err.msg()) } if !as_json { ok('${verb}: [${target.id}] ${target.message}') for delta in plan.deltas { println(' ${change_mark(delta.kind)} ${delta.path}') } note('${plural(plan.deltas.len, 'file')} change · ${plural(plan.remove.len, 'file')} removed') } approved := confirm(args.flag('yes')) or { return refuse(as_json, err.msg()) } if !approved { return 1 } if discard_first { history.commit_worktree(store, store.root, snapshot.load(store.root), history.SaveInput{ message: 'revert: discarded changes' is_checkpoint: true }) or { return refuse(as_json, err.msg()) } } save := history.commit_files(store, '', plan.files, history.SaveInput{ message: '${verb}: ${target.id}' restores: target.id }) or { return refuse(as_json, err.msg()) } report := snapshot.restore_files(store, store.root, plan.files, plan.remove) or { return refuse(as_json, err.msg()) } if as_json { emit_json(json.encode(BackJson{ id: save.id restores: target.id written: report.written removed: report.removed discarded: discard_first })) return 0 } ok('restored [${save.id}] ${save.message}') return 0 } struct RestorePlan { files []snapshot.FileEntry remove []string deltas []snapshot.Delta } // plan_restore works out what writing `target` back onto disk involves. // // `prune_untracked` is revert's rule: revert promises to discard unsaved // changes, so a file that was never saved goes too. undo and load are more // conservative and only remove paths history already knows about; a file the // user never saved is not theirs to delete. fn plan_restore(store &storage.Store, target history.Save, prune_untracked bool) !RestorePlan { files := history.files_of(store, target.id)! mut wanted := map[string]bool{} for file in files { wanted[file.path] = true } from := working_tree(store)! mut remove := []string{} if prune_untracked { for file in from.files { if file.path !in wanted { remove << file.path } } } else if head := history.head(store) { for file in history.files_of(store, head.id) or { []snapshot.FileEntry{} } { if file.path !in wanted { remove << file.path } } } deltas := snapshot.diff_trees(store, from, snapshot.Tree{ files: files })! return RestorePlan{ files: files remove: remove deltas: deltas } } fn change_mark(kind string) string { if kind == 'added' { return green('+') } if kind == 'removed' { return red('-') } return amber('~') } struct BackJson { id string restores string written int removed int discarded bool } struct RevertJson { reverted bool head_id string }