cli_test.v

39.0 KB · raw

1module tests23import os4import time56const root = @VMODROOT7const binary = os.join_path(root, 'build', 'koh3')89struct Result {10mut:11	code int12	out  string13	err  string14}1516fn testsuite_begin() {17	os.mkdir_all(os.join_path(root, 'build')) or { panic(err) }18	build := os.execute('v -o ${q(binary)} ${q(os.join_path(root, 'src', 'koh3.v'))}')19	if build.exit_code != 0 {20		panic('could not build koh3: ${build.output}')21	}22}2324fn q(s string) string {25	return "'${s.replace("'", "'\\''")}'"26}2728fn temp_repo(name string) string {29	dir := os.join_path(os.temp_dir(), 'koh3-cli-${name}-${time.now().unix_nano()}')30	os.mkdir_all(dir) or { panic(err) }31	return dir32}3334fn run(repo string, args ...string) Result {35	home := temp_repo('home')36	defer { os.rmdir_all(home) or {} }37	return run_home(repo, home, ...args)38}3940fn run_home(repo string, home string, args ...string) Result {41	stamp := '${os.getpid()}-${time.now().unix_nano()}'42	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')43	out_path := '${base}.out'44	err_path := '${base}.err'45	code_path := '${base}.code'46	mut command := 'HOME=${q(home)} ${q(binary)}'47	for arg in args {48		command += ' ${q(arg)}'49	}50	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'51	result := os.execute(shell)52	if result.exit_code != 0 {53		panic('could not run test command: ${result.output}')54	}55	code := os.read_file(code_path) or { panic(err) }56	out := os.read_file(out_path) or { '' }57	err := os.read_file(err_path) or { '' }58	os.rm(out_path) or {}59	os.rm(err_path) or {}60	os.rm(code_path) or {}61	return Result{62		code: code.int()63		out:  out64		err:  err65	}66}6768fn init_repo(repo string) {69	r := run(repo, 'init')70	assert r.code == 071	assert os.exists(os.join_path(repo, '.koh'))72	assert os.exists(os.join_path(repo, '.kohignore'))73}7475fn write(repo string, path string, text string) {76	full := os.join_path(repo, path)77	os.mkdir_all(os.dir(full)) or { panic(err) }78	os.write_file(full, text) or { panic(err) }79}8081fn read_json_has(text string, key string) {82	if !text.contains(key) {83		panic('missing JSON key ${key}: ${text}')84	}85}8687fn test_init_and_usage() {88	dir := temp_repo('init')89	defer { os.rmdir_all(dir) or {} }90	r := run(dir, 'init', '--json')91	assert r.code == 092	read_json_has(r.out, 'repo')93	read_json_has(r.out, 'ignore_created')94	assert run(dir, 'init').code == 195	assert run(dir, 'unknown-command').code == 296	assert run(dir, 'unknown-command').err.contains('unknown command')97	// An agent asking for JSON gets JSON for a usage mistake too, exit 2.98	for args in [['unknown-command', '--json'], ['save', '--json'], ['save', 'x', '--nope', '--json']] {99		r2 := run(dir, ...args)100		assert r2.code == 2101		assert r2.out == ''102		assert r2.err.starts_with('{"error":'), r2.err103	}104}105106// The binary embeds VERSION while saves bump v.mod; they drifted once.107fn test_version_matches_the_manifest() {108	dir := temp_repo('version')109	defer { os.rmdir_all(dir) or {} }110	version := run(dir, '--version').out.trim_space().all_after('koh ')111	manifest := os.read_file(os.join_path(root, 'v.mod')) or { panic(err) }112	assert manifest.contains("version: '${version}'"), version113}114115fn test_save_checkpoint_and_status() {116	dir := temp_repo('save')117	defer { os.rmdir_all(dir) or {} }118	init_repo(dir)119	write(dir, 'tracked.txt', 'one\n')120	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')121	assert r.code == 0122	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent', 'session',123		'files', 'size_bytes'] {124		read_json_has(r.out, key)125	}126	assert r.out.contains('"message":"first message"')127	assert r.out.contains('"agent":"agent-7"')128	assert r.out.contains('"session":"session-a"')129	assert r.out.contains('"is_checkpoint":false')130	assert run(dir, 'save', 'again').code == 1131	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')132	assert run(dir, 'save').code == 2133	assert run(dir, 'save', 'x', '--bogus').code == 2134	cp := run(dir, 'checkpoint', 'still first', '--json')135	assert cp.code == 0136	assert cp.out.contains('"is_checkpoint":true')137	assert cp.out.contains('"parent":')138	clean := run(dir, 'status')139	assert clean.code == 0140	assert clean.out.contains('no changes')141	write(dir, 'tracked.txt', 'two\n')142	write(dir, 'new.txt', 'new\n')143	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }144	write(dir, '.kohignore', '*.log\n')145	status := run(dir, 'status')146	assert status.code == 0147	assert status.out.contains('+')148	assert status.out.contains('~') || status.out.contains('-')149	assert status.out.contains('added')150	js := run(dir, 'status', '--json')151	assert js.code == 0152	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed'] {153		read_json_has(js.out, key)154	}155	assert js.out.contains('"ignore_changed":true')156}157158fn test_status_requires_repo_and_ignore_rules() {159	dir := temp_repo('status')160	defer { os.rmdir_all(dir) or {} }161	assert run(dir, 'status').code == 1162	init_repo(dir)163	write(dir, '.kohignore', '*.log\nbuild/\n')164	write(dir, 'keep.txt', 'keep\n')165	write(dir, 'ignored.log', 'ignore\n')166	write(dir, 'build/output.txt', 'ignore\n')167	assert run(dir, 'save', 'keep').code == 0168	assert run(dir, 'status').out.contains('no changes')169	assert !run(dir, 'status').out.contains('ignored.log')170	assert !run(dir, 'status').out.contains('build/output.txt')171	assert !run(dir, 'status').out.contains('LOG.md')172}173174// LOG.md is a convenience written after the save commits. If it cannot be175// written, the save still happened, and an agent that retried on a failure176// would only be told nothing had changed.177fn test_a_save_succeeds_when_log_md_cannot_be_written() {178	dir := temp_repo('logmd')179	defer { os.rmdir_all(dir) or {} }180	init_repo(dir)181	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }182	write(dir, 'a.txt', 'one\n')183	r := run(dir, 'save', 'first', '--json')184	assert r.code == 0185	assert r.out.starts_with('{')186	assert r.err.contains('LOG.md')187	assert run(dir, 'log', '--json').out.contains('"message":"first"')188}189190// A folder of ignored files can sit where a restored file should go. Koh191// never touches ignored files, so the restore must stop and say so, not drop192// the file inside the folder under a temporary name.193fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {194	dir := temp_repo('dir-in-way')195	defer { os.rmdir_all(dir) or {} }196	init_repo(dir)197	write(dir, 'out', 'a file\n')198	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]199	os.rm(os.join_path(dir, 'out')) or { panic(err) }200	write(dir, 'out/build.log', 'ignored\n')201	assert run(dir, 'save', 'out is gone').code == 0202	r := run(dir, 'load', first, '--yes')203	assert r.code == 1204	assert r.err.contains('out')205	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']206}207208// Koh never follows a symlink, so a folder replaced by a link to somewhere209// else is not the repo's to write into: restoring through it would overwrite210// files outside the repo. The refusal comes before anything is recorded.211fn test_a_restore_never_writes_through_a_symlinked_folder() {212	dir := temp_repo('link-in-way')213	outside := temp_repo('link-target')214	defer {215		os.rmdir_all(dir) or {}216		os.rmdir_all(outside) or {}217	}218	init_repo(dir)219	write(dir, 'docs/a.md', 'saved\n')220	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]221	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }222	write(outside, 'a.md', 'precious\n')223	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }224	assert run(dir, 'save', 'docs is a link now').code == 0225	head := run(dir, 'status', '--json').out226	r := run(dir, 'load', first, '--yes')227	assert r.code == 1228	assert r.err.contains('docs')229	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'230	assert run(dir, 'status', '--json').out == head231}232233// A restore records its save first, then writes files. When the writing stops234// part way, the half-written tree is not somebody's work: saving it would235// record (and offer) a tree that undoes changes nobody asked to undo. Every236// command that would build on it points at revert, which finishes the job.237fn test_a_restore_cut_short_points_at_revert() {238	dir := temp_repo('cut-short')239	defer {240		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}241		os.rmdir_all(dir) or {}242	}243	init_repo(dir)244	write(dir, 'zero', '0\n')245	assert run(dir, 'save', 'zero').code == 0246	write(dir, 'a.txt', 'v1\n')247	write(dir, 'zz/f', 'v1\n')248	assert run(dir, 'save', 'first').code == 0249	write(dir, 'a.txt', 'v2\n')250	write(dir, 'zz/f', 'v2\n')251	assert run(dir, 'save', 'second').code == 0252	// a.txt is written, then the read-only folder stops the restore: the253	// tree is genuinely half one save and half the other.254	os.chmod(os.join_path(dir, 'zz'), 0o555)!255	stopped := run(dir, 'undo', '--yes')256	assert stopped.code == 1257	assert stopped.err.contains('koh revert')258	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'259	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'260	// Even a status that cannot read the tree says what happened.261	os.chmod(os.join_path(dir, 'zz'), 0o000)!262	assert run(dir, 'status').err.contains('koh revert')263	os.chmod(os.join_path(dir, 'zz'), 0o755)!264265	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')266	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {267		r := run(dir, ...args)268		assert r.code == 1269		assert r.err.contains('koh revert')270	}271	assert run(dir, 'revert', '--yes').code == 0272	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'273	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'274	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')275	write(dir, 'a.txt', 'v3\n')276	assert run(dir, 'save', 'carry on').code == 0277}278279// Doctor clears peek folders left from earlier days, never one somebody may280// be reading right now.281fn test_doctor_sweeps_only_old_peek_folders() {282	dir := temp_repo('peek-sweep')283	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in284	// the real temp directory under names no save could have.285	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')286	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')287	defer {288		os.rmdir_all(dir) or {}289		os.rmdir_all(fresh) or {}290		os.rmdir_all(old) or {}291	}292	init_repo(dir)293	write(dir, 'a.txt', 'one\n')294	assert run(dir, 'save', 'one').code == 0295	os.mkdir_all(fresh) or { panic(err) }296	os.mkdir_all(old) or { panic(err) }297	two_days_ago := time.now().unix() - 2 * 86400298	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }299	assert run(dir, 'doctor', '--json').code == 0300	assert os.exists(fresh)301	assert !os.exists(old)302}303304// A file saved long ago and ignored since holds work no save has. Loading the305// old save must not write over it; the document says a restore never touches306// ignored files.307fn test_a_restore_never_overwrites_an_ignored_file() {308	dir := temp_repo('ignored-restore')309	defer { os.rmdir_all(dir) or {} }310	init_repo(dir)311	write(dir, '.env', 'KEY=saved long ago\n')312	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]313	write(dir, '.kohignore', '.env\n')314	assert run(dir, 'save', 'ignore env').code == 0315	write(dir, '.env', 'KEY=never saved\n')316	assert run(dir, 'load', first, '--yes').code == 0317	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'318319	// Where the ignored file is missing, the restore still brings it back.320	other := temp_repo('ignored-restore-missing')321	defer { os.rmdir_all(other) or {} }322	init_repo(other)323	write(other, '.env', 'KEY=saved long ago\n')324	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]325	write(other, '.kohignore', '.env\n')326	assert run(other, 'save', 'ignore env').code == 0327	os.rm(os.join_path(other, '.env')) or { panic(err) }328	assert run(other, 'load', again, '--yes').code == 0329	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'330}331332// A going-back preview lists paths only. Running diff(1) per file to draw it333// cost 27 s for 5,000 changed files, so it must not run diff at all.334fn test_a_going_back_preview_does_not_run_diff() {335	dir := temp_repo('preview-nodiff')336	home := temp_repo('preview-nodiff-home')337	defer {338		os.rmdir_all(dir) or {}339		os.rmdir_all(home) or {}340	}341	init_repo(dir)342	write(dir, 'a.txt', 'one\n')343	assert run_home(dir, home, 'save', 'one').code == 0344	write(dir, 'a.txt', 'two\n')345	assert run_home(dir, home, 'save', 'two').code == 0346	fake := os.join_path(home, 'bin')347	os.mkdir_all(fake) or { panic(err) }348	marker := os.join_path(home, 'diff-ran')349	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {350		panic(err)351	}352	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }353	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0354	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'355	assert !os.exists(marker)356}357358// A restore rewrites only what differs. Rewriting every file resets every359// mtime, so the next status has to hash the whole tree again.360fn test_a_restore_leaves_unchanged_files_alone() {361	dir := temp_repo('restore-skip')362	defer { os.rmdir_all(dir) or {} }363	init_repo(dir)364	write(dir, 'a.txt', 'one\n')365	write(dir, 'same.txt', 'never changes\n')366	assert run(dir, 'save', 'one').code == 0367	write(dir, 'a.txt', 'two\n')368	assert run(dir, 'save', 'two').code == 0369	long_ago := i64(1700000000)370	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }371	assert run(dir, 'undo', '--yes').code == 0372	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'373	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago374}375376// `save` records the executable bit, so `status` has to see it too, or a377// chmod would be invisible until it turned up in a save.378fn test_status_sees_an_executable_bit_change() {379	dir := temp_repo('chmod')380	defer { os.rmdir_all(dir) or {} }381	init_repo(dir)382	write(dir, 'run.sh', 'echo hi\n')383	assert run(dir, 'save', 'script').code == 0384	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }385	status := run(dir, 'status', '--json')386	assert status.out.contains('"dirty":true')387	assert status.out.contains('"modified":["run.sh"]')388}389390fn test_log_and_diff() {391	dir := temp_repo('history')392	defer { os.rmdir_all(dir) or {} }393	init_repo(dir)394	write(dir, 'a.txt', 'one\n')395	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')396	id1 := first.out.all_after('"id":"')[..12]397	write(dir, 'a.txt', 'two\n')398	second := run(dir, 'save', 'two', '--session', 'beta', '--json')399	id2 := second.out.all_after('"id":"')[..12]400	cp := run(dir, 'checkpoint', 'checkpoint', '--json')401	assert cp.code == 0402	log := run(dir, 'log')403	assert log.code == 0404	assert log.out.contains('▸')405	assert log.out.contains('◐')406	lj := run(dir, 'log', '--json')407	assert lj.code == 0408	assert lj.out.contains('"head_id"')409	assert lj.out.contains('"saves"')410	assert run(dir, 'log', '--since', 'today').out.contains('two')411	session := run(dir, 'log', '--session', 'alpha')412	assert session.out.contains('one')413	assert !session.out.contains('two')414	write(dir, 'a.txt', 'three\n')415	d := run(dir, 'diff')416	assert d.code == 0417	assert d.out.contains('--- a/')418	assert d.out.contains('+++ b/')419	assert run(dir, 'diff', id1).code == 0420	assert run(dir, 'diff', id1, id2).code == 0421	dj := run(dir, 'diff', '--json')422	assert dj.code == 0423	assert dj.out.contains('"from"')424	assert dj.out.contains('"to"')425	assert dj.out.contains('"files"')426	assert dj.out.contains('"change":"modified"')427	assert run(dir, 'diff', 'not-a-real-id').code == 1428	assert run(dir, 'diff', id1, id2, 'third').code == 1429	write(dir, 'blob.bin', '\x00\x01\x02')430	diff_binary := run(dir, 'diff', '--json')431	assert diff_binary.out.contains('"binary":true')432	assert diff_binary.out.contains('Binary files differ')433}434435fn test_undo_revert_and_load() {436	dir := temp_repo('restore')437	defer { os.rmdir_all(dir) or {} }438	init_repo(dir)439	write(dir, 'a.txt', 'one\n')440	one := run(dir, 'save', 'one', '--json').out441	id1 := one.all_after('"id":"')[..12]442	write(dir, 'a.txt', 'two\n')443	write(dir, 'gone.txt', 'gone\n')444	second := run(dir, 'save', 'two', '--json').out445	id2 := second.all_after('"id":"')[..12]446	write(dir, 'a.txt', 'three\n')447	third := run(dir, 'save', 'three', '--json').out448	id3 := third.all_after('"id":"')[..12]449	// Unsaved work — here a file never saved — blocks every going-back but450	// revert, as in Koh 2: a restore must never overwrite what only the disk has.451	write(dir, 'never.txt', 'keep me\n')452	log_before := run(dir, 'log').out453	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {454		blocked := run(dir, ...args)455		assert blocked.code == 1456		assert blocked.err.contains('unsaved changes')457	}458	assert run(dir, 'log').out == log_before459	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }460	write(dir, 'a.txt', 'edited, never saved\n')461	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')462	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'463	write(dir, 'a.txt', 'three\n')464	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }465	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')466	write(dir, 'gone.txt', 'gone\n')467	undo := run(dir, 'undo', '--yes', '--json')468	assert undo.code == 0469	if !undo.out.contains(id2) {470		panic('undo JSON did not name ${id2}: ${undo.out}')471	}472	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'473	assert os.exists(os.join_path(dir, 'gone.txt'))474	assert run(dir, 'load', id3, '--yes').code == 0475	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'476	assert run(dir, 'undo', '2', '--yes').code == 0477	assert run(dir, 'load', id2, '--yes').code == 0478	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')479	write(dir, 'a.txt', 'dirty\n')480	before := run(dir, 'log')481	refuse := run(dir, 'revert')482	assert refuse.code == 1483	assert refuse.err.contains('needs --yes when not interactive')484	assert run(dir, 'log').out == before.out485	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'486	write(dir, 'untracked.txt', 'remove\n')487	rv := run(dir, 'revert', '--yes', '--json')488	assert rv.code == 0489	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'490	assert !os.exists(os.join_path(dir, 'untracked.txt'))491	// The way back to the discarded work is named, not left to be found.492	kept := rv.out.all_after('"checkpoint":"')[..12]493	assert run(dir, 'load', kept, '--yes').code == 0494	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'495	assert os.read_file(os.join_path(dir, 'untracked.txt'))! == 'remove\n'496	write(dir, 'a.txt', 'dirty again\n')497	assert run(dir, 'revert', '--yes').out.contains('koh load ')498	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')499	assert run(dir, 'load', '--checkpoint', '--yes').code == 0500	assert run(dir, 'load', id2, '--json').code == 1501	assert run(dir, 'load', id2, '--json').err.contains('error')502	assert run(dir, 'load').code == 2503	assert run(dir, 'load', 'unknown-id', '--yes').code == 1504}505506fn test_flag_and_flagged_log() {507	dir := temp_repo('flag')508	defer { os.rmdir_all(dir) or {} }509	init_repo(dir)510	write(dir, 'flag.txt', 'one\n')511	saved := run(dir, 'save', 'flag me', '--json')512	id := saved.out.all_after('"id":"')[..12]513	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')514	assert flagged.code == 0515	assert flagged.out.contains('"flagged":true')516	assert flagged.out.contains('"reason":"unsafe"')517	list := run(dir, 'flag', '--json')518	assert list.code == 0519	assert list.out.contains(id)520	assert list.out.contains('unsafe')521	assert run(dir, 'log').out.contains('⚑')522	assert run(dir, 'flag', '--clear', id).code == 0523	assert run(dir, 'flag').out.contains('nothing is flagged')524	assert run(dir, 'flag', 'unknown-id').code == 1525	assert run(dir, 'flag').code == 0526}527528fn test_pluck_forward_reverse_dry_run_and_conflict() {529	dir := temp_repo('pluck')530	defer { os.rmdir_all(dir) or {} }531	init_repo(dir)532	write(dir, 'a.txt', 'one\n')533	first := run(dir, 'save', 'one', '--json').out534	id1 := first.all_after('"id":"')[..12]535	write(dir, 'a.txt', 'two\n')536	second := run(dir, 'save', 'two', '--json').out537	id2 := second.all_after('"id":"')[..12]538	assert run(dir, 'load', id1, '--yes').code == 0539	dry := run(dir, 'pluck', id2, '--dry-run')540	assert dry.code == 0541	assert dry.out.contains('a.txt')542	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'543	assert run(dir, 'pluck', id2, '--yes').code == 0544	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'545	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0546	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'547	write(dir, 'a.txt', 'different\n')548	assert run(dir, 'pluck', id2, '--dry-run').code == 1549	assert run(dir, 'save', 'different').code == 0550	conflict := run(dir, 'pluck', id2, '--yes')551	assert conflict.code == 1552	assert conflict.err.contains('a.txt')553	assert run(dir, 'pluck').code == 2554	assert run(dir, 'pluck', 'unknown-id').code == 1555}556557fn test_peek_and_doctor() {558	dir := temp_repo('peek-doctor')559	defer { os.rmdir_all(dir) or {} }560	init_repo(dir)561	write(dir, 'peek.txt', 'peek me\n')562	assert run(dir, 'save', 'peekable').code == 0563	id := run(dir, 'log', '--json').out.all_after('"id":"')[..12]564	before_log := run(dir, 'log', '--json').out565	peek := run(dir, 'peek', id, '--json')566	assert peek.code == 0567	peek_path := peek.out.all_after('"path":"').before('"')568	assert peek.out.contains('"id":"${id}"')569	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'570	assert run(dir, 'status').out.contains('no changes')571	assert run(dir, 'log', '--json').out == before_log572	assert run(dir, 'peek').code == 2573	assert run(dir, 'peek', 'unknown-id').code == 1574	backup := os.join_path(dir, 'doctor.backup')575	healthy := run(dir, 'doctor')576	assert healthy.code == 0577	assert healthy.out.contains('is sound')578	report := run(dir, 'doctor', '--json')579	assert report.code == 0580	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',581		'backup'] {582		read_json_has(report.out, key)583	}584	backed := run(dir, 'doctor', '--backup', backup)585	assert backed.code == 0586	assert os.exists(backup)587	assert backed.out.contains(backup)588	assert run(dir, 'doctor', '--backup', backup).code == 1589	assert run(dir, 'peek', id, '--json').code == 0590	// A peek made today is left for whoever is reading it.591	kept := run(dir, 'doctor', '--json')592	assert kept.code == 0593	assert os.exists(peek_path)594	os.rmdir_all(peek_path) or {}595}596597fn test_strip_refuses_without_terminal() {598	dir := temp_repo('strip')599	defer { os.rmdir_all(dir) or {} }600	init_repo(dir)601	write(dir, 'secret.txt', 'keep\n')602	assert run(dir, 'save', 'secret').code == 0603	before_log := run(dir, 'log', '--json').out604	refused := run(dir, 'strip', 'secret.txt')605	assert refused.code == 1606	assert refused.err.contains('needs a terminal')607	assert run(dir, 'log', '--json').out == before_log608	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'609	assert run(dir, 'log', '--json').out.contains('secret')610}611612fn test_saves_and_checkpoints_aliases() {613	dir := temp_repo('aliases')614	defer { os.rmdir_all(dir) or {} }615	init_repo(dir)616	write(dir, 'alias.txt', 'one\n')617	assert run(dir, 'save', 'plain save').code == 0618	assert run(dir, 'checkpoint', 'checkpoint save').code == 0619	saves := run(dir, 'saves')620	assert saves.code == 0621	assert saves.out.contains('plain save')622	assert saves.out.contains('checkpoint save')623	checkpoints := run(dir, 'checkpoints')624	assert checkpoints.code == 0625	assert checkpoints.out.contains('checkpoint save')626	assert !checkpoints.out.contains('plain save')627	json_result := run(dir, 'checkpoints', '--json')628	assert json_result.code == 0629	assert json_result.out.contains('"head_id"')630	assert json_result.out.contains('"saves"')631	assert json_result.out.contains('"is_checkpoint":true')632	assert !json_result.out.contains('"is_checkpoint":false')633}634635fn test_remote_configuration_is_isolated_and_atomic() {636	dir := temp_repo('remote')637	home := temp_repo('remote-home')638	defer {639		os.rmdir_all(dir) or {}640		os.rmdir_all(home) or {}641	}642	empty := run_home(dir, home, 'remote', '--json')643	assert empty.code == 0644	assert empty.out.contains('"configured":false')645	target := os.join_path(home, 'remote-store')646	set := run_home(dir, home, 'remote', 'folder', target)647	assert set.code == 0648	assert os.is_dir(target)649	state := run_home(dir, home, 'remote', '--json')650	assert state.code == 0651	assert state.out.contains('"kind":"folder"')652	assert state.out.contains(target)653	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1654	assert run_home(dir, home, 'remote', '--json').out.contains(target)655	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')656	assert run_home(dir, home, 'remote', '--forget').code == 0657	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')658}659660// The files under ~/.config/koh can be written by hand instead of by661// `koh remote`, and are then read the same way.662fn test_remote_written_by_hand() {663	dir := temp_repo('remote-by-hand')664	home := temp_repo('remote-by-hand-home')665	defer {666		os.rmdir_all(dir) or {}667		os.rmdir_all(home) or {}668	}669	config := os.join_path(home, '.config', 'koh')670	os.mkdir_all(config) or { panic(err) }671	target := os.join_path(home, 'remote-store')672	os.mkdir_all(target) or { panic(err) }673	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {674		panic(err)675	}676	assert run_home(dir, home, 'init').code == 0677	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }678	assert run_home(dir, home, 'save', 'first').code == 0679	offered := run_home(dir, home, 'offer', '--json')680	assert offered.code == 0681	assert offered.out.contains('"head"')682683	// Keys anyone else can read are refused before they are ever sent.684	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {685		panic(err)686	}687	credentials := os.join_path(config, 'credentials')688	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }689	os.chmod(credentials, 0o644) or { panic(err) }690	loose := run_home(dir, home, 'offer')691	assert loose.code == 1692	assert loose.err.contains('chmod 600')693694	// A setting koh cannot read is replaced by setting the remote again.695	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }696	unreadable := run_home(dir, home, 'offer')697	assert unreadable.code == 1698	assert unreadable.err.contains('not readable')699	assert run_home(dir, home, 'remote', 'folder', target).code == 0700	assert run_home(dir, home, 'offer').code == 0701}702703// A clone belongs to the repo it was stolen from, whatever its folder is704// called later: renaming it must not start a second repo on the remote.705fn test_a_renamed_clone_keeps_offering_to_its_repo() {706	syncroot := temp_repo('rename-clone')707	home := temp_repo('rename-clone-home')708	defer {709		os.rmdir_all(syncroot) or {}710		os.rmdir_all(home) or {}711	}712	remote := os.join_path(syncroot, 'remote')713	a := os.join_path(syncroot, 'A', 'proj')714	b_parent := os.join_path(syncroot, 'B')715	os.mkdir_all(a) or { panic(err) }716	os.mkdir_all(b_parent) or { panic(err) }717	init_repo(a)718	write(a, 'a.txt', 'from A\n')719	assert run_home(a, home, 'remote', 'folder', remote).code == 0720	assert run_home(a, home, 'save', 'A first').code == 0721	assert run_home(b_parent, home, 'steal', 'proj').code == 0722	renamed := os.join_path(b_parent, 'renamed')723	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }724	write(renamed, 'b.txt', 'from B\n')725	assert run_home(renamed, home, 'save', 'B first').code == 0726	assert !os.exists(os.join_path(remote, 'renamed'))727	assert run_home(a, home, 'steal').code == 0728	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'729}730731fn test_offer_steal_folder_remote() {732	syncroot := temp_repo('sync')733	home := temp_repo('sync-home')734	defer {735		os.rmdir_all(syncroot) or {}736		os.rmdir_all(home) or {}737	}738	remote := os.join_path(syncroot, 'remote')739	a := os.join_path(syncroot, 'A', 'proj')740	b_parent := os.join_path(syncroot, 'B')741	os.mkdir_all(a) or { panic(err) }742	os.mkdir_all(b_parent) or { panic(err) }743	init_repo(a)744	write(a, 'a.txt', 'from A\n')745	assert run_home(a, home, 'remote', 'folder', remote).code == 0746	assert run_home(a, home, 'save', 'A first').code == 0747	clone := run_home(b_parent, home, 'steal', 'proj')748	assert clone.code == 0749	b := os.join_path(b_parent, 'proj')750	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'751	write(b, 'b.txt', 'from B\n')752	assert run_home(b, home, 'save', 'B first').code == 0753	write(a, 'a2.txt', 'second\n')754	assert run_home(a, home, 'save', 'A second').code == 0755	assert run_home(a, home, 'steal').code == 0756	assert os.exists(os.join_path(a, 'b.txt'))757	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')758	write(a, 'clash.txt', 'base\n')759	assert run_home(a, home, 'save', 'clash base').code == 0760	assert run_home(b, home, 'steal').code == 0761	write(a, 'clash.txt', 'A version\n')762	assert run_home(a, home, 'save', 'A clash').code == 0763	write(b, 'clash.txt', 'B version\n')764	assert run_home(b, home, 'save', 'B clash').code == 0765	refused := run_home(b, home, 'steal')766	assert refused.code == 1767	assert refused.err.contains('--mine') || refused.err.contains('--theirs')768	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]769	theirs := run_home(b, home, 'steal', '--theirs', '--json')770	assert theirs.code == 0771	// The pre-combine tree is off the line now; the way back must be named,772	// or an agent without the history view cannot find it.773	assert theirs.out.contains('"previous_head":"${b_head}"')774	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'775	assert run_home(b, home, 'load', b_head, '--yes').code == 0776	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'777	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 0778	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'779	write(a, 'clash.txt', 'A second\n')780	assert run_home(a, home, 'save', 'A second clash').code == 0781	write(b, 'clash.txt', 'B second\n')782	assert run_home(b, home, 'save', 'B second clash').code == 0783	assert run_home(b, home, 'steal', '--mine').code == 0784	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'785	assert run_home(b, home, 'log').out.contains('combine: kept mine for')786}787788// A clone brings in the whole history, flags included; both output forms must789// say which saves came in flagged, and why.790fn test_a_clone_reports_flagged_saves() {791	syncroot := temp_repo('clone-flags')792	home := temp_repo('clone-flags-home')793	defer {794		os.rmdir_all(syncroot) or {}795		os.rmdir_all(home) or {}796	}797	a := os.join_path(syncroot, 'A', 'proj')798	os.mkdir_all(a) or { panic(err) }799	init_repo(a)800	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 0801	write(a, 'a.txt', 'one\n')802	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]803	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 0804	assert run_home(a, home, 'offer').code == 0805	for name in ['B', 'C'] {806		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }807	}808	json_clone := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')809	assert json_clone.code == 0810	assert json_clone.out.contains('"flagged":["${id}"]')811	text_clone := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')812	assert text_clone.code == 0813	assert text_clone.out.contains('[${id}] came in flagged — broke the build')814}815816// A folder remote on a disk or share that is not mounted is simply not there.817// Creating it would put the saves in a stand-in folder the other machine never818// sees; the offer must say what is wrong instead.819fn test_an_unmounted_folder_remote_is_not_recreated() {820	syncroot := temp_repo('unmounted')821	home := temp_repo('unmounted-home')822	defer {823		os.rmdir_all(syncroot) or {}824		os.rmdir_all(home) or {}825	}826	mount := os.join_path(syncroot, 'nas')827	remote := os.join_path(mount, 'koh')828	a := os.join_path(syncroot, 'proj')829	os.mkdir_all(a) or { panic(err) }830	init_repo(a)831	assert run_home(a, home, 'remote', 'folder', remote).code == 0832	write(a, 'a.txt', 'one\n')833	assert run_home(a, home, 'save', 'first').code == 0834	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }835	os.mkdir(mount) or { panic(err) }836	offered := run_home(a, home, 'offer')837	assert offered.code == 1838	assert offered.err.contains('mounted')839	assert !os.exists(remote)840	write(a, 'a.txt', 'two\n')841	saved := run_home(a, home, 'save', 'second')842	assert saved.code == 0843	assert saved.out.contains('mounted')844	assert !os.exists(remote)845}846847fn test_man_and_koh2_handoff() {848	dir := temp_repo('man')849	home := temp_repo('man-home')850	defer {851		os.rmdir_all(dir) or {}852		os.rmdir_all(home) or {}853	}854	whole := run_home(dir, home, 'man')855	assert whole.code == 0856	assert whole.out.contains('NAME')857	assert whole.out.contains('COMMANDS')858	strip := run_home(dir, home, 'man', 'strip')859	assert strip.code == 0860	assert strip.out.contains('strip')861	assert !strip.out.contains('koh save ')862	assert run_home(dir, home, 'man', 'nonsense').code == 2863	legacy := temp_repo('legacy')864	defer { os.rmdir_all(legacy) or {} }865	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }866	fake := os.join_path(home, 'bin')867	os.mkdir_all(fake) or { panic(err) }868	fake_koh := os.join_path(fake, 'koh2')869	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }870	os.chmod(fake_koh, 0o755) or { panic(err) }871	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')872	assert handoff.code == 7873	assert handoff.out.contains('handoff:status --json')874	// One notice line, on stderr, so koh2's own output stays as it was.875	assert handoff.err.contains('Koh 2 repo')876	assert handoff.err.trim_space().split_into_lines().len == 1877	assert handoff.out.trim_space() == 'handoff:status --json'878}879880fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {881	stamp := '${os.getpid()}-${time.now().unix_nano()}'882	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')883	out_path := '${base}.out'884	err_path := '${base}.err'885	code_path := '${base}.code'886	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'887	for arg in args {888		command += ' ${q(arg)}'889	}890	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'891	result := os.execute(shell)892	if result.exit_code != 0 {893		panic('could not run test command: ${result.output}')894	}895	code := os.read_file(code_path) or { panic(err) }896	out := os.read_file(out_path) or { '' }897	err := os.read_file(err_path) or { '' }898	os.rm(out_path) or {}899	os.rm(err_path) or {}900	os.rm(code_path) or {}901	return Result{902		code: code.int()903		out:  out904		err:  err905	}906}907908// --- migration -------------------------------------------------------------909910fn koh2_binary() string {911	return os.find_abs_path_of_executable('koh') or { '' }912}913914// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under915// test here.916fn run_koh2(dir string, command string) {917	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')918}919920fn save_ids(dir string) []string {921	mut ids := []string{}922	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {923		if name.ends_with('.json') {924			ids << name.trim_right('.json')925		}926	}927	ids.sort()928	return ids929}930931fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {932	koh2 := koh2_binary()933	if koh2 == '' {934		println('skipping the migration tests: koh (Koh 2) is not on PATH')935		return936	}937	dir := temp_repo('migrate')938	defer { os.rmdir_all(dir) or {} }939	home := temp_repo('migrate-home')940	defer { os.rmdir_all(home) or {} }941	run_koh2(dir, '${q(koh2)} init')942	// One file large enough to be an object, one small enough to be inlined.943	write(dir, 'code.txt', 'x'.repeat(700))944	write(dir, 'tiny.txt', 'tiny\n')945	run_koh2(dir, '${q(koh2)} save "first save"')946	run_koh2(dir, '${q(koh2)} checkpoint "before something"')947	write(dir, 'code.txt', 'y'.repeat(700))948	run_koh2(dir, '${q(koh2)} save "second save"')949	original := save_ids(dir)950	assert original.len == 3951952	report := run_home(dir, home, 'migrate')953	assert report.code == 0954	assert report.out.contains('migrated 3 saves')955	// The swap: `.koh` is a file, the old data is archived, nothing is staging.956	assert os.is_file(os.join_path(dir, '.koh'))957	assert os.is_dir(os.join_path(dir, '.koh-v2'))958	assert os.is_file(os.join_path(dir, '.kohignore'))959	assert !os.exists(os.join_path(dir, '.koh-migrate'))960961	// Every save kept its original ID, and the new repo is sound.962	logged := run_home(dir, home, 'log', '--json')963	assert logged.code == 0964	for id in original {965		assert logged.out.contains(id)966	}967	assert run_home(dir, home, 'doctor').code == 0968	assert run_home(dir, home, 'status').code == 0969970	// Migrating again has nothing to convert.971	assert run_home(dir, home, 'migrate').code == 1972}973974fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {975	koh2 := koh2_binary()976	if koh2 == '' {977		return978	}979	dir := temp_repo('migrate-dirty')980	defer { os.rmdir_all(dir) or {} }981	home := temp_repo('migrate-dirty-home')982	defer { os.rmdir_all(home) or {} }983	run_koh2(dir, '${q(koh2)} init')984	write(dir, 'code.txt', 'x'.repeat(700))985	run_koh2(dir, '${q(koh2)} save "only save"')986	write(dir, 'code.txt', 'unsaved change\n')987988	refused := run_home(dir, home, 'migrate')989	assert refused.code == 1990	assert refused.err.contains('save with koh2 first')991	// Nothing moved: still Koh 2, no archive, no staging file.992	assert os.is_dir(os.join_path(dir, '.koh'))993	assert !os.exists(os.join_path(dir, '.koh-v2'))994	assert !os.exists(os.join_path(dir, '.koh-migrate'))995}996997// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or998// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have999// a `.kohconfig`; migrate must not call them unsaved work.1000fn test_migrate_passes_over_the_files_koh2_never_saved() {1001	koh2 := koh2_binary()1002	if koh2 == '' {1003		return1004	}1005	dir := temp_repo('migrate-koh2-ignores')1006	defer { os.rmdir_all(dir) or {} }1007	home := temp_repo('migrate-koh2-ignores-home')1008	defer { os.rmdir_all(home) or {} }1009	run_koh2(dir, '${q(koh2)} init')1010	write(dir, 'code.txt', 'x'.repeat(700))1011	run_koh2(dir, '${q(koh2)} save "only save"')1012	write(dir, '.kohconfig', 'stable_days = 14\n')1013	write(dir, '.kohignore.public', 'private/\n')1014	write(dir, 'lib/app.bundle', 'bundle\n')1015	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1016	// Koh 2 keeps saving a file under a folder pattern added later, where1017	// Koh 3 reads the same rule as covering the folder: the saved file is on1018	// disk and matches, so the tree is clean.1019	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1020	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1021	// Koh 2 skips *.bundle even when its rules no longer list it.1022	ignore_path := os.join_path(dir, '.koh', 'ignore')1023	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1024	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1025	// A saved file the walk skips still has to match what was saved.1026	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1027	changed := run_home(dir, home, 'migrate')1028	assert changed.code == 11029	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1030	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1031	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')10321033	migrated := run_home(dir, home, 'migrate')1034	assert migrated.code == 0, migrated.err1035	// They stay where they were, for the user to keep or delete.1036	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1037}