snapshot_test.v

9.8 KB · raw

1module snapshot23import os4import time5import src.storage67fn temp_root(name string) !string {8	dir := os.join_path(os.temp_dir(), 'koh3_snap_${os.getpid()}_${name}')9	os.rmdir_all(dir) or {}10	os.mkdir_all(dir, os.MkdirParams{})!11	return dir12}1314fn put(root string, rel string, text string) ! {15	full := os.join_path(root, rel)16	os.mkdir_all(os.dir(full), os.MkdirParams{})!17	os.write_file(full, text)!18}1920fn test_ignore_matches_the_documented_shapes() {21	ig := parse('22# a comment23*.log24build/25/anchored.txt26out/**27docs/*.md28')29	assert ig.matches('error.log', false)30	assert ig.matches('deep/nested/error.log', false)31	assert !ig.matches('error.txt', false)32	// A trailing slash names a directory: the directory itself and everything33	// below it, but not a file that shares the name.34	assert ig.matches('build', true)35	assert ig.matches('build/thing.o', false)36	assert ig.matches('src/build/nested.o', false)37	assert !ig.matches('build', false)38	assert ig.matches('anchored.txt', false)39	assert !ig.matches('sub/anchored.txt', false)40	assert ig.matches('out/anything/at/all', false)41	assert ig.matches('docs/readme.md', false)42	assert !ig.matches('docs/readme.txt', false)43	assert !ig.matches('src/main.v', false)44}4546// A stripped path is banned as itself: its `*` and `?` must not become47// wildcards, in `.kohignore` or in the walk's ban.48fn test_a_stripped_path_with_wildcard_characters_bans_only_itself() {49	root := temp_root('literal_ban')!50	defer {51		os.rmdir_all(root) or {}52	}53	assert add_ignore(root, 'keys/a*b?.env')!54	assert os.read_file(os.join_path(root, ignore_file))! == '/keys/a\\*b\\?.env\n'55	for ig in [load(root), Ignore{}.banning(['keys/a*b?.env'])] {56		assert ig.matches('keys/a*b?.env', false)57		assert !ig.matches('keys/axxbz.env', false)58		assert !ig.matches('keys/a*b?.env.bak', false)59	}60	assert parse('\\\\x').matches('\\x', false)61}6263fn test_hard_ignores_are_not_overridable() {64	for path in ['.koh', '.koh-wal', '.koh-shm', '.koh-v2', '.koh-v2/snapshots/x.json', '.git',65		'.git/config', 'LOG.md'] {66		assert hard_ignored(path), '${path} should be hard ignored'67	}68	assert !hard_ignored('.kohignore')69	assert !hard_ignored('src/log.md')70	// A repo inside the repo keeps its own history: restoring an old copy of71	// its .koh or .git would roll that history back.72	for path in ['inner/.koh', 'inner/.koh-wal', 'inner/.koh-shm', 'a/b/.git', 'vendored/.git/HEAD',73		'old/.koh-v2/snapshots/x.json', 'koh2repo/.koh/objects/ab/cd'] {74		assert hard_ignored(path), '${path} should be hard ignored'75	}76	assert !hard_ignored('inner/.kohignore')77	assert !hard_ignored('docs/.github/workflow.yml')78	assert !hard_ignored('notes/.koh.md')79	// A pattern list cannot un-ignore them, and `.kohignore` itself is content.80	ig := parse('')81	assert ig.matches('.koh', false)82	assert !ig.matches('.kohignore', false)83}8485fn test_walk_skips_ignored_files_directories_and_symlinks() {86	mut store := storage.create(temp_root('walk')!)!87	root := store.root88	defer {89		store.close()90		os.rmdir_all(root) or {}91	}92	put(root, 'keep.txt', 'keep\n')!93	put(root, 'nested/deep/file.txt', 'deep\n')!94	put(root, 'skip.log', 'noise\n')!95	put(root, 'build/output.o', 'binary\n')!96	put(root, '.kohignore', '*.log\nbuild/\n')!97	os.symlink('keep.txt', os.join_path(root, 'link.txt')) or {}9899	entries := walk(store, root, load(root))!100	mut paths := []string{}101	for entry in entries {102		paths << entry.path103	}104	assert paths == ['.kohignore', 'keep.txt', 'nested/deep/file.txt']105}106107fn test_walk_records_the_executable_bit() {108	mut store := storage.create(temp_root('exec')!)!109	root := store.root110	defer {111		store.close()112		os.rmdir_all(root) or {}113	}114	put(root, 'run.sh', '#!/bin/sh\necho hi\n')!115	put(root, 'plain.txt', 'hello\n')!116	os.chmod(os.join_path(root, 'run.sh'), 0o755)!117118	mut executable := false119	mut plain_executable := true120	for entry in walk(store, root, Ignore{})! {121		if entry.path == 'run.sh' {122			executable = entry.executable123		}124		if entry.path == 'plain.txt' {125			plain_executable = entry.executable126		}127	}128	assert executable129	assert !plain_executable130}131132// The point of nanosecond timestamps: a file rewritten inside the same second133// with the same size must not reuse the cached hash, or a save would record134// content that is no longer on disk.135fn test_cache_does_not_reuse_a_same_size_same_second_edit() {136	mut store := storage.create(temp_root('cache')!)!137	root := store.root138	defer {139		store.close()140		os.rmdir_all(root) or {}141	}142	put(root, 'file.txt', 'aaaa\n')!143	first := walk(store, root, Ignore{})!144	assert first[0].hash == storage.hash_hex('aaaa\n'.bytes())145146	put(root, 'file.txt', 'bbbb\n')!147	second := walk(store, root, Ignore{})!148	assert second[0].hash == storage.hash_hex('bbbb\n'.bytes())149	assert second[0].hash != first[0].hash150}151152// Linux stamps files from a clock that ticks every few milliseconds, so a153// same-size rewrite in the tick the file was hashed in leaves size, mtime and154// ctime unchanged. A hash taken that close to the last change is never cached;155// the next walk hashes again. Tools such as `cp -p` keep an old mtime while156// rewriting, so the newer of the two times decides.157fn test_cache_skips_a_file_changed_moments_ago() {158	second := i64(1_000_000_000)159	now := 100 * second160	old := now - 10 * second161	assert cacheable(Stat{ mtime_ns: old, ctime_ns: old }, now)162	assert !cacheable(Stat{ mtime_ns: now - second, ctime_ns: now - second }, now)163	assert !cacheable(Stat{ mtime_ns: old, ctime_ns: now - second }, now)164165	mut store := storage.create(temp_root('racy')!)!166	root := store.root167	defer {168		store.close()169		os.rmdir_all(root) or {}170	}171	put(root, 'fresh.txt', 'new\n')!172	put(root, 'copied.txt', 'kept mtime\n')!173	hour_ago := time.now().unix() - 3600174	os.utime(os.join_path(root, 'copied.txt'), hour_ago, hour_ago)!175	walk(store, root, Ignore{})!176	assert store.load_cache()!.len == 0177}178179// `status` must work while another agent's save holds the write lock: the180// cache only saves time, so a busy repo hashes without caching, at once.181fn test_a_walk_does_not_wait_for_another_writer() {182	mut store := storage.create(temp_root('busy_walk')!)!183	root := store.root184	defer {185		store.close()186		os.rmdir_all(root) or {}187	}188	put(root, 'a.txt', 'a\n')!189	// Only a file whose last change is older than the racy window is cached,190	// and ctime cannot be set back, so the test waits it out.191	time.sleep(racy_window_ns * time.nanosecond + 100 * time.millisecond)192	writer := storage.open(root)!193	defer {194		writer.close()195	}196	writer.begin()!197	started := time.now()198	files := walk(store, root, Ignore{})!199	assert files.len == 1200	assert time.since(started) < time.second201	writer.rollback()202}203204fn test_restore_writes_removes_and_leaves_ignored_files_alone() {205	mut store := storage.create(temp_root('restore')!)!206	root := store.root207	defer {208		store.close()209		os.rmdir_all(root) or {}210	}211	put(root, 'keep.txt', 'recorded\n')!212	put(root, 'gone/inside.txt', 'also recorded\n')!213	put(root, 'noise.log', 'ignored, must survive\n')!214	put(root, '.kohignore', '*.log\n')!215	target := walk(store, root, load(root))!216	store_objects(store, root, target)!217218	// Drift the working tree: clobber one file, delete another, and add a file219	// the recorded tree has never seen.220	os.write_file(os.join_path(root, 'keep.txt'), 'clobbered\n')!221	os.rm(full_path(root, 'gone/inside.txt'))!222	put(root, 'extra.txt', 'never saved\n')!223224	// The removal list names an ignored file (which survives), a file the225	// target still has (rewritten, not removed), and one genuinely extra file.226	report := restore_files(store, root, load(root), target,227		['extra.txt', '.kohignore', 'noise.log'])!228229	// The clobbered and the deleted file are written; the unchanged230	// .kohignore is left as it is.231	assert report.written == 2232	assert report.removed == 1233	assert os.read_file(full_path(root, 'keep.txt'))! == 'recorded\n'234	assert os.read_file(full_path(root, 'gone/inside.txt'))! == 'also recorded\n'235	assert !os.exists(full_path(root, 'extra.txt'))236	assert os.read_file(full_path(root, 'noise.log'))! == 'ignored, must survive\n'237	assert os.read_file(full_path(root, '.kohignore'))! == '*.log\n'238}239240fn test_restore_keeps_the_executable_bit() {241	mut store := storage.create(temp_root('restore_exec')!)!242	root := store.root243	defer {244		store.close()245		os.rmdir_all(root) or {}246	}247	put(root, 'run.sh', '#!/bin/sh\necho hi\n')!248	os.chmod(os.join_path(root, 'run.sh'), 0o755)!249	target := walk(store, root, Ignore{})!250	store_objects(store, root, target)!251	os.chmod(os.join_path(root, 'run.sh'), 0o644)!252253	restore_files(store, root, Ignore{}, target, [])!254	mode := (lstat(os.join_path(root, 'run.sh')) or { panic('missing') }).mode255	assert is_executable(mode)256}257258fn test_diff_reports_kinds_counts_and_binary_files() {259	mut store := storage.create(temp_root('diff')!)!260	root := store.root261	defer {262		store.close()263		os.rmdir_all(root) or {}264	}265	put(root, 'text.txt', 'one\ntwo\n')!266	put(root, 'same.txt', 'unchanged\n')!267	put(root, 'gone.txt', 'bye\n')!268	before := walk(store, root, Ignore{})!269	store_objects(store, root, before)!270271	os.write_file(os.join_path(root, 'text.txt'), 'one\nthree\nfour\n')!272	os.rm(full_path(root, 'gone.txt'))!273	os.write_file(os.join_path(root, 'added.txt'), 'new\n')!274	os.write_bytes(os.join_path(root, 'blob.bin'), [u8(0), 0x01, 0x02])!275	after := walk(store, root, Ignore{})!276277	// A save's side of a diff is bytes from the object store; only the side278	// that is the working tree reads from disk.279	deltas := diff_trees(store, Tree{280		files: before281	}, Tree{282		root:  root283		files: after284	})!285	mut by_path := map[string]Delta{}286	for delta in deltas {287		by_path[delta.path] = delta288	}289	assert deltas.len == 4290	assert by_path['text.txt'].kind == 'modified'291	assert by_path['text.txt'].added == 2292	assert by_path['text.txt'].removed == 1293	assert by_path['added.txt'].kind == 'added'294	assert by_path['gone.txt'].kind == 'removed'295	assert by_path['blob.bin'].binary296	assert by_path['blob.bin'].patch == binary_notice297	assert 'same.txt' !in by_path298}299300fn full_path(root string, rel string) string {301	return os.join_path(root, rel)302}