commit.v

5.5 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	save := commit_files(store, root, files, input)!43	write_log_md(store, root)!44	return save45}4647// commit_files records an already-known tree. `root` is '' when the objects are48// already in the store — a replay during a steal, for instance.49pub fn commit_files(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {50	store.begin()!51	save := write_save(store, root, files, input) or {52		store.rollback()53		return err54	}55	store.commit()!56	return save57}5859fn write_save(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {60	if root != '' {61		snapshot.store_objects(store, root, files)!62	}63	created_at := if input.created_at > 0 { input.created_at } else { time.now().unix() }64	mut save := Save{65		parent:        head_id(store)66		message:       input.message67		created_at:    created_at68		machine:       if input.machine != '' { input.machine } else { machine.name() }69		is_checkpoint: input.is_checkpoint70		size_bytes:    tree_size(store, files)71		agent:         input.agent72		session:       input.session73		restores:      input.restores74		replayed_from: input.replayed_from75	}76	// Two saves made in the same second with the same record would collide.77	// Bumping the clock keeps one line of history and keeps the ID unique.78	for {79		save.id = save_id(save, files)80		if by_id(store, save.id) == none {81			break82		}83		save.created_at++84	}85	insert_save(store, save, files)!86	store.set_state(storage.head_key, save.id)!87	return save88}8990fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {91	mut stmt := store.db.prepare('INSERT INTO saves (id, parent, message, created_at, machine,92		is_checkpoint, size_bytes, agent, session, restores, replayed_from)93		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!94	stmt.bind_text(1, save.id)!95	if save.parent == '' {96		stmt.bind_null(2)!97	} else {98		stmt.bind_text(2, save.parent)!99	}100	stmt.bind_text(3, save.message)!101	stmt.bind_int(4, save.created_at)!102	stmt.bind_text(5, save.machine)!103	stmt.bind_int(6, if save.is_checkpoint { 1 } else { 0 })!104	stmt.bind_int(7, save.size_bytes)!105	bind_optional(stmt, 8, save.agent)!106	bind_optional(stmt, 9, save.session)!107	bind_optional(stmt, 10, save.restores)!108	bind_optional(stmt, 11, save.replayed_from)!109	stmt.step()!110	stmt.finalize()111112	mut files_stmt :=113		store.db.prepare('INSERT INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)')!114	defer {115		files_stmt.finalize()116	}117	for file in files {118		files_stmt.bind_text(1, save.id)!119		files_stmt.bind_text(2, file.path)!120		files_stmt.bind_text(3, file.hash)!121		files_stmt.bind_int(4, if file.executable { 1 } else { 0 })!122		files_stmt.step()!123		// A statement that has returned DONE must be reset before rebinding.124		files_stmt.reset()125	}126}127128fn bind_optional(stmt &storage.Stmt, index int, value string) ! {129	if value == '' {130		stmt.bind_null(index)!131	} else {132		stmt.bind_text(index, value)!133	}134}135136// save_id is the first 12 hex characters of the Blake3 hash of the canonical137// record: parent, message, time, machine, checkpoint mark, agent, session and138// the sorted file list.139pub fn save_id(save Save, files []snapshot.FileEntry) string {140	return storage.hash_hex(canonical(save, files).bytes())[..12]141}142143fn canonical(save Save, files []snapshot.FileEntry) string {144	mut sb := strings.Builder{}145	sb.write_string('koh3-save-v1\n')146	put_field(mut sb, 'parent', save.parent)147	put_field(mut sb, 'message', save.message)148	put_field(mut sb, 'created', save.created_at.str())149	put_field(mut sb, 'machine', save.machine)150	put_field(mut sb, 'checkpoint', if save.is_checkpoint { '1' } else { '0' })151	put_field(mut sb, 'agent', save.agent)152	put_field(mut sb, 'session', save.session)153	put_field(mut sb, 'files', files.len.str())154	for file in files {155		mark := if file.executable { 'x' } else { '-' }156		put_field(mut sb, 'file', '${mark}${file.hash} ${file.path}')157	}158	return sb.str()159}160161// Length-prefixed fields keep the record unambiguous whatever a message or a162// path contains.163fn put_field(mut sb strings.Builder, name string, value string) {164	sb.write_string('${name}:${value.len}:')165	sb.write_string(value)166	sb.write_string('\n')167}168169fn tree_size(store &storage.Store, files []snapshot.FileEntry) i64 {170	mut total := i64(0)171	for file in files {172		total += store.object_size(file.hash) or { 0 }173	}174	return total175}