commit.v

5.4 KB · raw

1//! Creating saves.2//!3//! A save is a full snapshot: every tracked path with its object hash and4//! executable bit, plus the message, time, machine and optional agent and5//! session. Its ID is the first 12 hex characters of the Blake3 hash of the6//! canonical record, computed once, at creation, and never recomputed — which7//! is why `strip` can change a save's files and keep its ID.89module history1011import strings12import time13import src.machine14import src.snapshot15import src.storage1617pub struct SaveInput {18pub mut:19	message       string20	agent         string21	session       string22	is_checkpoint bool23	restores      string24	replayed_from string25	created_at    i6426	machine       string27}2829pub const nothing_changed = 'nothing has changed since the last save'3031// commit_worktree walks the working tree and records it. A plain save refuses32// when the tree matches head; a checkpoint always records.33pub fn commit_worktree(store &storage.Store, root string, ig snapshot.Ignore, input SaveInput) !Save {34	files := snapshot.walk(store, root, ig)!35	if input.restores == '' && !input.is_checkpoint {36		if previous := head(store) {37			if snapshot.same_tree(files, files_of(store, previous.id)!) {38				return error(nothing_changed)39			}40		}41	}42	return commit_files(store, root, files, input)!43}4445// commit_files records an already-known tree. `root` is '' when the objects are46// already in the store — a restore, or a replay during a steal.47pub fn commit_files(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {48	store.begin()!49	save := write_save(store, root, files, input) or {50		store.rollback()51		return err52	}53	store.commit()!54	write_log_md(store)!55	return save56}5758fn write_save(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {59	if root != '' {60		snapshot.store_objects(store, root, files)!61	}62	created_at := if input.created_at > 0 { input.created_at } else { time.now().unix() }63	mut save := Save{64		parent:        head_id(store)65		message:       input.message66		created_at:    created_at67		machine:       if input.machine != '' { input.machine } else { machine.name() }68		is_checkpoint: input.is_checkpoint69		size_bytes:    tree_size(store, files)70		agent:         input.agent71		session:       input.session72		restores:      input.restores73		replayed_from: input.replayed_from74	}75	// Two saves made in the same second with the same record would collide.76	// Bumping the clock keeps one line of history and keeps the ID unique.77	for {78		save.id = save_id(save, files)79		if by_id(store, save.id) == none {80			break81		}82		save.created_at++83	}84	insert_save(store, save, files)!85	store.set_state(storage.head_key, save.id)!86	return save87}8889fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {90	mut stmt := store.db.prepare('INSERT INTO saves (id, parent, message, created_at, machine,91		is_checkpoint, size_bytes, agent, session, restores, replayed_from)92		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!93	stmt.bind_text(1, save.id)!94	if save.parent == '' {95		stmt.bind_null(2)!96	} else {97		stmt.bind_text(2, save.parent)!98	}99	stmt.bind_text(3, save.message)!100	stmt.bind_int(4, save.created_at)!101	stmt.bind_text(5, save.machine)!102	stmt.bind_int(6, if save.is_checkpoint { 1 } else { 0 })!103	stmt.bind_int(7, save.size_bytes)!104	bind_optional(stmt, 8, save.agent)!105	bind_optional(stmt, 9, save.session)!106	bind_optional(stmt, 10, save.restores)!107	bind_optional(stmt, 11, save.replayed_from)!108	stmt.step()!109	stmt.finalize()110111	mut files_stmt :=112		store.db.prepare('INSERT INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)')!113	defer {114		files_stmt.finalize()115	}116	for file in files {117		files_stmt.bind_text(1, save.id)!118		files_stmt.bind_text(2, file.path)!119		files_stmt.bind_text(3, file.hash)!120		files_stmt.bind_int(4, if file.executable { 1 } else { 0 })!121		files_stmt.step()!122		// A statement that has returned DONE must be reset before rebinding.123		files_stmt.reset()124	}125}126127fn bind_optional(stmt &storage.Stmt, index int, value string) ! {128	if value == '' {129		stmt.bind_null(index)!130	} else {131		stmt.bind_text(index, value)!132	}133}134135// save_id is the first 12 hex characters of the Blake3 hash of the canonical136// record: parent, message, time, machine, checkpoint mark, agent, session and137// the sorted file list.138pub fn save_id(save Save, files []snapshot.FileEntry) string {139	return storage.hash_hex(canonical(save, files).bytes())[..12]140}141142fn canonical(save Save, files []snapshot.FileEntry) string {143	mut sb := strings.Builder{}144	sb.write_string('koh3-save-v1\n')145	put_field(mut sb, 'parent', save.parent)146	put_field(mut sb, 'message', save.message)147	put_field(mut sb, 'created', save.created_at.str())148	put_field(mut sb, 'machine', save.machine)149	put_field(mut sb, 'checkpoint', if save.is_checkpoint { '1' } else { '0' })150	put_field(mut sb, 'agent', save.agent)151	put_field(mut sb, 'session', save.session)152	put_field(mut sb, 'files', files.len.str())153	for file in files {154		mark := if file.executable { 'x' } else { '-' }155		put_field(mut sb, 'file', '${mark}${file.hash} ${file.path}')156	}157	return sb.str()158}159160// Length-prefixed fields keep the record unambiguous whatever a message or a161// path contains.162fn put_field(mut sb strings.Builder, name string, value string) {163	sb.write_string('${name}:${value.len}:')164	sb.write_string(value)165	sb.write_string('\n')166}167168fn tree_size(store &storage.Store, files []snapshot.FileEntry) i64 {169	mut total := i64(0)170	for file in files {171		total += store.object_size(file.hash) or { 0 }172	}173	return total174}