history.v

7.3 KB · raw

1//! History: one line of saves, and the queries every command needs.23module history45import src.storage6import src.snapshot78// A save is a full snapshot of the tree plus what made it.9pub struct Save {10pub mut:11	id            string12	parent        string13	manifest      string14	message       string15	created_at    i6416	machine       string17	is_checkpoint bool18	size_bytes    i6419	agent         string20	session       string21	restores      string22	replayed_from string23}2425const select_save = 'SELECT id, parent, message, created_at, machine, is_checkpoint, size_bytes,26	agent, session, restores, replayed_from, manifest FROM saves'2728fn read_save(stmt &storage.Stmt) Save {29	return Save{30		id:            stmt.text(0)31		parent:        stmt.text_or_none(1) or { '' }32		message:       stmt.text(2)33		created_at:    stmt.int(3)34		machine:       stmt.text(4)35		is_checkpoint: stmt.int(5) != 036		size_bytes:    stmt.int(6)37		agent:         stmt.text_or_none(7) or { '' }38		session:       stmt.text_or_none(8) or { '' }39		restores:      stmt.text_or_none(9) or { '' }40		replayed_from: stmt.text_or_none(10) or { '' }41		manifest:      stmt.text(11)42	}43}4445// head is the newest save on the line.46pub fn head(store &storage.Store) ?Save {47	id := store.state(storage.head_key) or { return none }48	return by_id(store, id) or { none }49}5051// head_id is the head save's ID, or '' before the first save.52pub fn head_id(store &storage.Store) string {53	return store.state(storage.head_key) or { '' }54}5556// save_row is the strict lookup: a database error comes back unchanged, and57// only a statement that returns no row means the save is missing. Callers that58// walk a parent chain use this so a bad read cannot pass for the end of it.59fn save_row(store &storage.Store, id string) !Save {60	mut stmt := store.db.prepare('${select_save} WHERE id = ?')!61	defer {62		stmt.finalize()63	}64	stmt.bind_text(1, id)!65	if stmt.step()! {66		return read_save(stmt)67	}68	return error('save ${id} is missing')69}7071// by_id answers "does this save exist" for callers that only branch on it.72pub fn by_id(store &storage.Store, id string) ?Save {73	return save_row(store, id) or { none }74}7576// resolve accepts any unique prefix of six characters or more, the way Koh 277// did, so an agent can name a save without quoting the whole ID.78pub fn resolve(store &storage.Store, prefix string) !Save {79	if prefix.len < 6 {80		return error('"${prefix}" is too short — give at least 6 characters of a save ID')81	}82	// Save IDs are hexadecimal. Anything else here would be read as a LIKE83	// wildcard and scan the table, so reject it before the query.84	for c in prefix {85		if !(c >= `0` && c <= `9`) && !(c >= `a` && c <= `f`) && !(c >= `A` && c <= `F`) {86			return error('"${prefix}" is not a save ID prefix — save IDs are hexadecimal')87		}88	}89	mut stmt := store.db.prepare('${select_save} WHERE id LIKE ? ORDER BY id')!90	defer {91		stmt.finalize()92	}93	stmt.bind_text(1, '${prefix}%')!94	mut found := []Save{}95	for stmt.step()! {96		found << read_save(stmt)97	}98	match found.len {99		0 { return error('no save starts with "${prefix}"') }100		1 { return found[0] }101		else { return error('"${prefix}" matches ${found.len} saves — give more characters') }102	}103}104105// all_saves returns every save Koh knows, newest first. This is the "all" tab:106// it includes saves that were replayed away and are no longer on the line.107pub fn all_saves(store &storage.Store) ![]Save {108	// Saves made within one second share a time; the order they were written109	// in breaks the tie, as in Koh 2. An ID is a hash and would shuffle them.110	mut stmt := store.db.prepare('${select_save} ORDER BY created_at DESC, rowid DESC')!111	defer {112		stmt.finalize()113	}114	mut saves := []Save{}115	for stmt.step()! {116		saves << read_save(stmt)117	}118	return saves119}120121// line returns the saves that are on the line, newest first.122pub fn line(store &storage.Store) ![]Save {123	mut saves := []Save{}124	mut cursor := head_id(store)125	for cursor != '' {126		save := save_row(store, cursor)!127		saves << save128		cursor = save.parent129	}130	return saves131}132133// effective is where the line actually sits: `head.restores` when the newest134// save was a going-back, else `head`. Going back repeatedly therefore keeps135// stepping further back instead of undoing the undo.136pub fn effective(store &storage.Store) !Save {137	current := head(store) or { return error('this repo has no saves yet') }138	if current.restores != '' {139		return by_id(store, current.restores) or {140			return error('save ${current.restores} is missing')141		}142	}143	return current144}145146// step_back walks `n` parents back from `id`.147pub fn step_back(store &storage.Store, id string, n int) !Save {148	mut current := by_id(store, id) or { return error('save ${id} is missing') }149	for _ in 0 .. n {150		if current.parent == '' {151			return error('there is nothing before ${current.id} — it is the first save')152		}153		current = by_id(store, current.parent) or {154			return error('save ${current.parent} is missing')155		}156	}157	return current158}159160// session_start returns the oldest save of the session `id` belongs to.161pub fn session_start(store &storage.Store, id string) !Save {162	current := by_id(store, id) or { return error('save ${id} is missing') }163	if current.session == '' {164		return error('save ${current.id} is not part of a session')165	}166	mut oldest := current167	mut cursor := current.parent168	for cursor != '' {169		previous := save_row(store, cursor)!170		if previous.session != current.session {171			break172		}173		oldest = previous174		cursor = previous.parent175	}176	return oldest177}178179// last_session finds the most recent session name on the line.180pub fn last_session(store &storage.Store) !string {181	for save in line(store)! {182		if save.session != '' {183			return save.session184		}185	}186	return error('no save on the line belongs to a session')187}188189// session_saves returns the line's saves in a session, oldest first. A save190// replayed away by a combine is off the line, and its copy stands for it.191pub fn session_saves(store &storage.Store, name string) ![]Save {192	mut saves := line(store)!.filter(it.session == name)193	saves.reverse_in_place()194	return saves195}196197// latest_checkpoint is the newest checkpoint on the line.198pub fn latest_checkpoint(store &storage.Store) ?Save {199	for save in line(store) or { return none } {200		if save.is_checkpoint {201			return save202		}203	}204	return none205}206207// files_of lists a save's files sorted by path, read from its manifest tree.208pub fn files_of(store &storage.Store, save_id string) ![]snapshot.FileEntry {209	mut stmt := store.db.prepare('SELECT manifest FROM saves WHERE id = ?')!210	defer {211		stmt.finalize()212	}213	stmt.bind_text(1, save_id)!214	if !stmt.step()! {215		return error('save ${save_id} is missing')216	}217	root := stmt.text(0)218	entries := store.manifest_files(root) or {219		return error('save ${save_id}: ${err.msg()}')220	}221	mut files := []snapshot.FileEntry{cap: entries.len}222	for entry in entries {223		files << snapshot.FileEntry{224			path:       entry.path225			hash:       entry.hash226			size:       entry.size227			executable: entry.executable228		}229	}230	return files231}232233// save_count counts every save Koh holds, replayed-away ones included, unlike `line`.234pub fn save_count(store &storage.Store) !i64 {235	return count(store, 'saves')236}237238pub fn checkpoint_count(store &storage.Store) !i64 {239	return count(store, 'saves WHERE is_checkpoint = 1')240}241242fn count(store &storage.Store, what string) !i64 {243	mut stmt := store.db.prepare('SELECT COUNT(*) FROM ${what}')!244	defer {245		stmt.finalize()246	}247	if !stmt.step()! {248		return 0249	}250	return stmt.int(0)251}