cli_test.v

49.4 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 help screen is commands and plain words: every flag lives in `koh man`.107// this_platform is the platform name for the machine the tests run on, so a108// build test does not depend on which machine that is.109fn this_platform() string {110	machine := os.uname().machine111	arch := if machine in ['arm64', 'aarch64'] { 'aarch64' } else { 'x86_64' }112	return '${os.user_os()}-${arch}'113}114115// `koh build` builds with `koh.build`: the version and platform fill the output116// path, and each artifact is printed with its size.117fn test_build_builds_the_named_platforms() {118	dir := temp_repo('build_ok')119	defer { os.rmdir_all(dir) or {} }120	init_repo(dir)121	host := this_platform()122	write(dir, 'VERSION', '1.2.3\n')123	write(dir, 'koh.build', 'command = mkdir -p out && printf built > out/demo-1.2.3-${host}124output = out/demo-{version}-{platform}125platforms = ${host}126')127	one := run(dir, 'build')128	assert one.code == 0, one.err129	assert one.out.contains('version 1.2.3')130	assert one.out.contains('out/demo-1.2.3-${host}')131	assert os.exists(os.join_path(dir, 'out/demo-1.2.3-${host}'))132133	// --platform picks one, --all takes every platform the file names.134	write(dir, 'koh.build', 'command = mkdir -p out && printf m > out/demo-macos-aarch64 && printf l > out/demo-linux-aarch64135output = out/demo-{platform}136platforms = macos-aarch64, linux-aarch64137')138	all := run(dir, 'build', '--all', '--json')139	assert all.code == 0, all.err140	assert all.out.contains('"platform":"macos-aarch64"')141	assert all.out.contains('"platform":"linux-aarch64"')142	assert os.exists(os.join_path(dir, 'out/demo-linux-aarch64'))143	picked := run(dir, 'build', '--platform', 'linux-aarch64')144	assert picked.code == 0, picked.err145	assert picked.out.contains('out/demo-linux-aarch64')146	assert !picked.out.contains('out/demo-macos-aarch64')147}148149// The item's exit check, as a test: `koh build` builds Koh 3 itself with the150// real toolchain, in a copy, and the binary it produces runs.151// `koh update` refuses a command line that cannot be answered: JSON cannot carry152// the question, and a stray argument is a mistake. Both are settled before any153// source is read, so no network is needed here.154fn test_update_refuses_a_command_line_it_cannot_answer() {155	dir := temp_repo('update_args')156	defer { os.rmdir_all(dir) or {} }157	init_repo(dir)158	json_without_yes := run(dir, 'update', '--json')159	assert json_without_yes.code == 2160	assert json_without_yes.err.contains('needs --yes')161	assert run(dir, 'update', 'extra').code == 2162}163164fn test_build_builds_koh_itself() {165	dir := temp_repo('selfbuild')166	defer { os.rmdir_all(dir) or {} }167	// Only what a build reads: the copy needs no history and no archive.168	for item in ['src', 'vendor', 'docs', 'v.mod', 'VERSION'] {169		os.cp_all(os.join_path(root, item), os.join_path(dir, item), true) or { panic(err) }170	}171	write(dir, 'koh.build', 'command = mkdir -p zig-out/bin && v -o zig-out/bin/koh3 src/koh3.v172output = zig-out/bin/koh3173platforms = ${this_platform()}174')175	init_repo(dir)176	built := run(dir, 'build')177	assert built.code == 0, built.err178	assert built.out.contains('zig-out/bin/koh3')179	fresh := os.join_path(dir, 'zig-out/bin/koh3')180	assert os.exists(fresh)181	version := os.read_file(os.join_path(dir, 'VERSION'))!.trim_space()182	assert os.execute('${q(fresh)} --version').output.trim_space() == 'koh ${version}'183}184185fn test_build_refuses_what_it_cannot_do() {186	dir := temp_repo('build_bad')187	defer { os.rmdir_all(dir) or {} }188	init_repo(dir)189	missing := run(dir, 'build')190	assert missing.code == 1191	assert missing.err.contains('koh.build')192193	write(dir, 'koh.build', 'command = true194output = out/demo195platforms = macos-aarch64196')197	no_version := run(dir, 'build')198	assert no_version.code == 1199	assert no_version.err.contains('VERSION')200201	write(dir, 'VERSION', '1.2.3\n')202	not_listed := run(dir, 'build', '--platform', 'linux-aarch64')203	assert not_listed.code == 1204	assert not_listed.err.contains('does not build for')205206	unknown := run(dir, 'build', '--platform', 'amiga')207	assert unknown.code == 1208	assert unknown.err.contains('amiga')209210	both := run(dir, 'build', '--all', '--platform', 'macos-aarch64')211	assert both.code == 2212	assert both.err.contains('cannot be combined')213214	write(dir, 'koh.build', 'command = true215output = out/demo216platforms = macos-aarch64, amiga217')218	bad_platform := run(dir, 'build')219	assert bad_platform.code == 1220	assert bad_platform.err.contains('amiga')221222	write(dir, 'koh.build', 'command = sh -c \'echo "no toolchain" >&2; exit 1\'223output = out/demo224platforms = ${this_platform()}225')226	failed := run(dir, 'build')227	assert failed.code == 1228	assert failed.err.contains('no toolchain')229}230231fn test_the_help_screen_lists_commands_and_no_flags() {232	dir := temp_repo('help')233	defer { os.rmdir_all(dir) or {} }234	help := run(dir, '--help')235	assert help.code == 0236	for name in ['save', 'checkpoint', 'status', 'log', 'diff', 'undo', 'revert', 'load', 'offer',237		'steal'] {238		assert help.out.contains('  ${name} '), name239	}240	assert help.out.contains('koh man <command>')241	// No flag text anywhere on the screen.242	assert !help.out.contains('--'), help.out243	for line in help.out.split_into_lines() {244		assert line.runes().len <= 80, line245	}246	// A bare `koh` keeps its stream and exit code; `-h` shows the same screen.247	bare := run(dir)248	assert bare.code == 2249	assert bare.out == ''250	assert bare.err.contains('koh man <command>')251	short := run(dir, '-h')252	assert short.code == 0253	assert short.out == help.out254}255256// Colour on the screen follows NO_COLOR, as it does everywhere else.257fn test_the_help_screen_has_no_colour_when_it_is_off() {258	dir := temp_repo('help_plain')259	defer { os.rmdir_all(dir) or {} }260	home := temp_repo('help_plain_home')261	defer { os.rmdir_all(home) or {} }262	out_path := os.join_path(os.temp_dir(), 'koh3-help-${os.getpid()}-${time.now().unix_nano()}')263	defer { os.rm(out_path) or {} }264	code := os.system('cd ${q(dir)} && HOME=${q(home)} NO_COLOR=1 ${q(binary)} --help > ${q(out_path)}')265	assert code == 0266	text := os.read_file(out_path) or { panic(err) }267	assert !text.contains('\x1b'), text268	assert text.contains('  save        snapshot your work')269}270271// The binary embeds VERSION while saves bump v.mod; they drifted once.272fn test_version_matches_the_manifest() {273	dir := temp_repo('version')274	defer { os.rmdir_all(dir) or {} }275	version := run(dir, '--version').out.trim_space().all_after('koh ')276	manifest := os.read_file(os.join_path(root, 'v.mod')) or { panic(err) }277	assert manifest.contains("version: '${version}'"), version278}279280fn test_save_checkpoint_and_status() {281	dir := temp_repo('save')282	defer { os.rmdir_all(dir) or {} }283	init_repo(dir)284	write(dir, 'tracked.txt', 'one\n')285	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')286	assert r.code == 0287	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent', 'session',288		'files', 'size_bytes'] {289		read_json_has(r.out, key)290	}291	assert r.out.contains('"message":"first message"')292	assert r.out.contains('"agent":"agent-7"')293	assert r.out.contains('"session":"session-a"')294	assert r.out.contains('"is_checkpoint":false')295	assert run(dir, 'save', 'again').code == 1296	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')297	assert run(dir, 'save').code == 2298	assert run(dir, 'save', 'x', '--bogus').code == 2299	cp := run(dir, 'checkpoint', 'still first', '--json')300	assert cp.code == 0301	assert cp.out.contains('"is_checkpoint":true')302	assert cp.out.contains('"parent":')303	clean := run(dir, 'status')304	assert clean.code == 0305	assert clean.out.contains('no changes')306	write(dir, 'tracked.txt', 'two\n')307	write(dir, 'new.txt', 'new\n')308	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }309	write(dir, '.kohignore', '*.log\n')310	status := run(dir, 'status')311	assert status.code == 0312	assert status.out.contains('+')313	assert status.out.contains('~') || status.out.contains('-')314	assert status.out.contains('added')315	js := run(dir, 'status', '--json')316	assert js.code == 0317	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed',318		'saves', 'size_bytes', 'head_flagged'] {319		read_json_has(js.out, key)320	}321	assert js.out.contains('"ignore_changed":true')322	// What the shell prompt shows: saves on the line, the .koh size, the flag.323	assert js.out.contains('"saves":2')324	assert js.out.contains('"size_bytes":${os.file_size(os.join_path(dir, '.koh'))}')325	assert js.out.contains('"head_flagged":false')326	head := js.out.all_after('"head_id":"').all_before('"')327	assert run(dir, 'flag', head, '--reason', 'bad').code == 0328	assert run(dir, 'status', '--json').out.contains('"head_flagged":true')329}330331fn test_status_requires_repo_and_ignore_rules() {332	dir := temp_repo('status')333	defer { os.rmdir_all(dir) or {} }334	assert run(dir, 'status').code == 1335	init_repo(dir)336	write(dir, '.kohignore', '*.log\nbuild/\n')337	write(dir, 'keep.txt', 'keep\n')338	write(dir, 'ignored.log', 'ignore\n')339	write(dir, 'build/output.txt', 'ignore\n')340	assert run(dir, 'save', 'keep').code == 0341	assert run(dir, 'status').out.contains('no changes')342	assert !run(dir, 'status').out.contains('ignored.log')343	assert !run(dir, 'status').out.contains('build/output.txt')344	assert !run(dir, 'status').out.contains('LOG.md')345}346347// LOG.md is a convenience written after the save commits. If it cannot be348// written, the save still happened, and an agent that retried on a failure349// would only be told nothing had changed.350fn test_a_save_succeeds_when_log_md_cannot_be_written() {351	dir := temp_repo('logmd')352	defer { os.rmdir_all(dir) or {} }353	init_repo(dir)354	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }355	write(dir, 'a.txt', 'one\n')356	r := run(dir, 'save', 'first', '--json')357	assert r.code == 0358	assert r.out.starts_with('{')359	assert r.err.contains('LOG.md')360	assert run(dir, 'log', '--json').out.contains('"message":"first"')361}362363// A folder of ignored files can sit where a restored file should go. Koh364// never touches ignored files, so the restore must stop and say so, not drop365// the file inside the folder under a temporary name.366fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {367	dir := temp_repo('dir-in-way')368	defer { os.rmdir_all(dir) or {} }369	init_repo(dir)370	write(dir, 'out', 'a file\n')371	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]372	os.rm(os.join_path(dir, 'out')) or { panic(err) }373	write(dir, 'out/build.log', 'ignored\n')374	assert run(dir, 'save', 'out is gone').code == 0375	r := run(dir, 'load', first, '--yes')376	assert r.code == 1377	assert r.err.contains('out')378	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']379}380381// Koh never follows a symlink, so a folder replaced by a link to somewhere382// else is not the repo's to write into: restoring through it would overwrite383// files outside the repo. The refusal comes before anything is recorded.384fn test_a_restore_never_writes_through_a_symlinked_folder() {385	dir := temp_repo('link-in-way')386	outside := temp_repo('link-target')387	defer {388		os.rmdir_all(dir) or {}389		os.rmdir_all(outside) or {}390	}391	init_repo(dir)392	write(dir, 'docs/a.md', 'saved\n')393	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]394	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }395	write(outside, 'a.md', 'precious\n')396	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }397	assert run(dir, 'save', 'docs is a link now').code == 0398	head := run(dir, 'status', '--json').out399	r := run(dir, 'load', first, '--yes')400	assert r.code == 1401	assert r.err.contains('docs')402	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'403	assert run(dir, 'status', '--json').out == head404}405406// A restore records its save first, then writes files. When the writing stops407// part way, the half-written tree is not somebody's work: saving it would408// record (and offer) a tree that undoes changes nobody asked to undo. Every409// command that would build on it points at revert, which finishes the job.410fn test_a_restore_cut_short_points_at_revert() {411	dir := temp_repo('cut-short')412	defer {413		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}414		os.rmdir_all(dir) or {}415	}416	init_repo(dir)417	write(dir, 'zero', '0\n')418	assert run(dir, 'save', 'zero').code == 0419	write(dir, 'a.txt', 'v1\n')420	write(dir, 'zz/f', 'v1\n')421	assert run(dir, 'save', 'first').code == 0422	write(dir, 'a.txt', 'v2\n')423	write(dir, 'zz/f', 'v2\n')424	assert run(dir, 'save', 'second').code == 0425	// a.txt is written, then the read-only folder stops the restore: the426	// tree is genuinely half one save and half the other.427	os.chmod(os.join_path(dir, 'zz'), 0o555)!428	stopped := run(dir, 'undo', '--yes')429	assert stopped.code == 1430	assert stopped.err.contains('koh revert')431	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'432	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'433	// Even a status that cannot read the tree says what happened.434	os.chmod(os.join_path(dir, 'zz'), 0o000)!435	assert run(dir, 'status').err.contains('koh revert')436	os.chmod(os.join_path(dir, 'zz'), 0o755)!437438	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')439	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {440		r := run(dir, ...args)441		assert r.code == 1442		assert r.err.contains('koh revert')443	}444	assert run(dir, 'revert', '--yes').code == 0445	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'446	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'447	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')448	write(dir, 'a.txt', 'v3\n')449	assert run(dir, 'save', 'carry on').code == 0450}451452// Doctor clears peek folders left from earlier days, never one somebody may453// be reading right now.454fn test_doctor_sweeps_only_old_peek_folders() {455	dir := temp_repo('peek-sweep')456	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in457	// the real temp directory under names no save could have.458	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')459	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')460	defer {461		os.rmdir_all(dir) or {}462		os.rmdir_all(fresh) or {}463		os.rmdir_all(old) or {}464	}465	init_repo(dir)466	write(dir, 'a.txt', 'one\n')467	assert run(dir, 'save', 'one').code == 0468	os.mkdir_all(fresh) or { panic(err) }469	os.mkdir_all(old) or { panic(err) }470	two_days_ago := time.now().unix() - 2 * 86400471	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }472	assert run(dir, 'doctor', '--json').code == 0473	assert os.exists(fresh)474	assert !os.exists(old)475}476477// A file saved long ago and ignored since holds work no save has. Loading the478// old save must not write over it; the document says a restore never touches479// ignored files.480fn test_a_restore_never_overwrites_an_ignored_file() {481	dir := temp_repo('ignored-restore')482	defer { os.rmdir_all(dir) or {} }483	init_repo(dir)484	write(dir, '.env', 'KEY=saved long ago\n')485	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]486	write(dir, '.kohignore', '.env\n')487	assert run(dir, 'save', 'ignore env').code == 0488	write(dir, '.env', 'KEY=never saved\n')489	assert run(dir, 'load', first, '--yes').code == 0490	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'491492	// Where the ignored file is missing, the restore still brings it back.493	other := temp_repo('ignored-restore-missing')494	defer { os.rmdir_all(other) or {} }495	init_repo(other)496	write(other, '.env', 'KEY=saved long ago\n')497	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]498	write(other, '.kohignore', '.env\n')499	assert run(other, 'save', 'ignore env').code == 0500	os.rm(os.join_path(other, '.env')) or { panic(err) }501	assert run(other, 'load', again, '--yes').code == 0502	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'503}504505// A going-back preview lists paths only. Running diff(1) per file to draw it506// cost 27 s for 5,000 changed files, so it must not run diff at all.507fn test_a_going_back_preview_does_not_run_diff() {508	dir := temp_repo('preview-nodiff')509	home := temp_repo('preview-nodiff-home')510	defer {511		os.rmdir_all(dir) or {}512		os.rmdir_all(home) or {}513	}514	init_repo(dir)515	write(dir, 'a.txt', 'one\n')516	assert run_home(dir, home, 'save', 'one').code == 0517	write(dir, 'a.txt', 'two\n')518	assert run_home(dir, home, 'save', 'two').code == 0519	fake := os.join_path(home, 'bin')520	os.mkdir_all(fake) or { panic(err) }521	marker := os.join_path(home, 'diff-ran')522	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {523		panic(err)524	}525	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }526	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0527	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'528	assert !os.exists(marker)529}530531// A restore rewrites only what differs. Rewriting every file resets every532// mtime, so the next status has to hash the whole tree again.533fn test_a_restore_leaves_unchanged_files_alone() {534	dir := temp_repo('restore-skip')535	defer { os.rmdir_all(dir) or {} }536	init_repo(dir)537	write(dir, 'a.txt', 'one\n')538	write(dir, 'same.txt', 'never changes\n')539	assert run(dir, 'save', 'one').code == 0540	write(dir, 'a.txt', 'two\n')541	assert run(dir, 'save', 'two').code == 0542	long_ago := i64(1700000000)543	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }544	assert run(dir, 'undo', '--yes').code == 0545	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'546	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago547}548549// `save` records the executable bit, so `status` has to see it too, or a550// chmod would be invisible until it turned up in a save.551fn test_status_sees_an_executable_bit_change() {552	dir := temp_repo('chmod')553	defer { os.rmdir_all(dir) or {} }554	init_repo(dir)555	write(dir, 'run.sh', 'echo hi\n')556	assert run(dir, 'save', 'script').code == 0557	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }558	status := run(dir, 'status', '--json')559	assert status.out.contains('"dirty":true')560	assert status.out.contains('"modified":["run.sh"]')561}562563fn test_log_and_diff() {564	dir := temp_repo('history')565	defer { os.rmdir_all(dir) or {} }566	init_repo(dir)567	write(dir, 'a.txt', 'one\n')568	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')569	id1 := first.out.all_after('"id":"')[..12]570	write(dir, 'a.txt', 'two\n')571	second := run(dir, 'save', 'two', '--session', 'beta', '--json')572	id2 := second.out.all_after('"id":"')[..12]573	cp := run(dir, 'checkpoint', 'checkpoint', '--json')574	assert cp.code == 0575	log := run(dir, 'log')576	assert log.code == 0577	assert log.out.contains('▸')578	assert log.out.contains('◐')579	lj := run(dir, 'log', '--json')580	assert lj.code == 0581	assert lj.out.contains('"head_id"')582	assert lj.out.contains('"saves"')583	assert run(dir, 'log', '--since', 'today').out.contains('two')584	session := run(dir, 'log', '--session', 'alpha')585	assert session.out.contains('one')586	assert !session.out.contains('two')587	write(dir, 'a.txt', 'three\n')588	d := run(dir, 'diff')589	assert d.code == 0590	assert d.out.contains('--- a/')591	assert d.out.contains('+++ b/')592	assert run(dir, 'diff', id1).code == 0593	assert run(dir, 'diff', id1, id2).code == 0594	dj := run(dir, 'diff', '--json')595	assert dj.code == 0596	assert dj.out.contains('"from"')597	assert dj.out.contains('"to"')598	assert dj.out.contains('"files"')599	assert dj.out.contains('"change":"modified"')600	assert run(dir, 'diff', 'not-a-real-id').code == 1601	assert run(dir, 'diff', id1, id2, 'third').code == 1602	write(dir, 'blob.bin', '\x00\x01\x02')603	diff_binary := run(dir, 'diff', '--json')604	assert diff_binary.out.contains('"binary":true')605	assert diff_binary.out.contains('Binary files differ')606}607608fn test_undo_revert_and_load() {609	dir := temp_repo('restore')610	defer { os.rmdir_all(dir) or {} }611	init_repo(dir)612	write(dir, 'a.txt', 'one\n')613	one := run(dir, 'save', 'one', '--json').out614	id1 := one.all_after('"id":"')[..12]615	write(dir, 'a.txt', 'two\n')616	write(dir, 'gone.txt', 'gone\n')617	second := run(dir, 'save', 'two', '--json').out618	id2 := second.all_after('"id":"')[..12]619	write(dir, 'a.txt', 'three\n')620	third := run(dir, 'save', 'three', '--json').out621	id3 := third.all_after('"id":"')[..12]622	// Unsaved work — here a file never saved — blocks every going-back but623	// revert, as in Koh 2: a restore must never overwrite what only the disk has.624	write(dir, 'never.txt', 'keep me\n')625	log_before := run(dir, 'log').out626	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {627		blocked := run(dir, ...args)628		assert blocked.code == 1629		assert blocked.err.contains('unsaved changes')630	}631	assert run(dir, 'log').out == log_before632	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }633	write(dir, 'a.txt', 'edited, never saved\n')634	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')635	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'636	write(dir, 'a.txt', 'three\n')637	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }638	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')639	write(dir, 'gone.txt', 'gone\n')640	undo := run(dir, 'undo', '--yes', '--json')641	assert undo.code == 0642	if !undo.out.contains(id2) {643		panic('undo JSON did not name ${id2}: ${undo.out}')644	}645	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'646	assert os.exists(os.join_path(dir, 'gone.txt'))647	assert run(dir, 'load', id3, '--yes').code == 0648	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'649	assert run(dir, 'undo', '2', '--yes').code == 0650	assert run(dir, 'load', id2, '--yes').code == 0651	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')652	write(dir, 'a.txt', 'dirty\n')653	before := run(dir, 'log')654	refuse := run(dir, 'revert')655	assert refuse.code == 1656	assert refuse.err.contains('needs --yes when not interactive')657	assert run(dir, 'log').out == before.out658	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'659	write(dir, 'untracked.txt', 'remove\n')660	rv := run(dir, 'revert', '--yes', '--json')661	assert rv.code == 0662	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'663	assert !os.exists(os.join_path(dir, 'untracked.txt'))664	// The way back to the discarded work is named, not left to be found.665	kept := rv.out.all_after('"checkpoint":"')[..12]666	assert run(dir, 'load', kept, '--yes').code == 0667	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'668	assert os.read_file(os.join_path(dir, 'untracked.txt'))! == 'remove\n'669	write(dir, 'a.txt', 'dirty again\n')670	assert run(dir, 'revert', '--yes').out.contains('koh load ')671	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')672	assert run(dir, 'load', '--checkpoint', '--yes').code == 0673	assert run(dir, 'load', id2, '--json').code == 1674	assert run(dir, 'load', id2, '--json').err.contains('error')675	assert run(dir, 'load').code == 2676	assert run(dir, 'load', 'unknown-id', '--yes').code == 1677}678679fn test_flag_and_flagged_log() {680	dir := temp_repo('flag')681	defer { os.rmdir_all(dir) or {} }682	init_repo(dir)683	write(dir, 'flag.txt', 'one\n')684	saved := run(dir, 'save', 'flag me', '--json')685	id := saved.out.all_after('"id":"')[..12]686	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')687	assert flagged.code == 0688	assert flagged.out.contains('"flagged":true')689	assert flagged.out.contains('"reason":"unsafe"')690	list := run(dir, 'flag', '--json')691	assert list.code == 0692	assert list.out.contains(id)693	assert list.out.contains('unsafe')694	assert run(dir, 'log').out.contains('⚑')695	assert run(dir, 'flag', '--clear', id).code == 0696	assert run(dir, 'flag').out.contains('nothing is flagged')697	assert run(dir, 'flag', 'unknown-id').code == 1698	assert run(dir, 'flag').code == 0699}700701fn test_pluck_forward_reverse_dry_run_and_conflict() {702	dir := temp_repo('pluck')703	defer { os.rmdir_all(dir) or {} }704	init_repo(dir)705	write(dir, 'a.txt', 'one\n')706	first := run(dir, 'save', 'one', '--json').out707	id1 := first.all_after('"id":"')[..12]708	write(dir, 'a.txt', 'two\n')709	second := run(dir, 'save', 'two', '--json').out710	id2 := second.all_after('"id":"')[..12]711	assert run(dir, 'load', id1, '--yes').code == 0712	dry := run(dir, 'pluck', id2, '--dry-run')713	assert dry.code == 0714	assert dry.out.contains('a.txt')715	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'716	assert run(dir, 'pluck', id2, '--yes').code == 0717	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'718	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0719	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'720	write(dir, 'a.txt', 'different\n')721	assert run(dir, 'pluck', id2, '--dry-run').code == 1722	assert run(dir, 'save', 'different').code == 0723	conflict := run(dir, 'pluck', id2, '--yes')724	assert conflict.code == 1725	assert conflict.err.contains('a.txt')726	assert run(dir, 'pluck').code == 2727	assert run(dir, 'pluck', 'unknown-id').code == 1728}729730fn test_peek_and_doctor() {731	dir := temp_repo('peek-doctor')732	defer { os.rmdir_all(dir) or {} }733	init_repo(dir)734	write(dir, 'peek.txt', 'peek me\n')735	assert run(dir, 'save', 'peekable').code == 0736	id := run(dir, 'log', '--json').out.all_after('"id":"')[..12]737	before_log := run(dir, 'log', '--json').out738	peek := run(dir, 'peek', id, '--json')739	assert peek.code == 0740	peek_path := peek.out.all_after('"path":"').before('"')741	assert peek.out.contains('"id":"${id}"')742	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'743	assert run(dir, 'status').out.contains('no changes')744	assert run(dir, 'log', '--json').out == before_log745	assert run(dir, 'peek').code == 2746	assert run(dir, 'peek', 'unknown-id').code == 1747	backup := os.join_path(dir, 'doctor.backup')748	healthy := run(dir, 'doctor')749	assert healthy.code == 0750	assert healthy.out.contains('is sound')751	report := run(dir, 'doctor', '--json')752	assert report.code == 0753	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',754		'backup'] {755		read_json_has(report.out, key)756	}757	backed := run(dir, 'doctor', '--backup', backup)758	assert backed.code == 0759	assert os.exists(backup)760	assert backed.out.contains(backup)761	assert run(dir, 'doctor', '--backup', backup).code == 1762	assert run(dir, 'peek', id, '--json').code == 0763	// A peek made today is left for whoever is reading it.764	kept := run(dir, 'doctor', '--json')765	assert kept.code == 0766	assert os.exists(peek_path)767	os.rmdir_all(peek_path) or {}768}769770fn test_strip_refuses_without_terminal() {771	dir := temp_repo('strip')772	defer { os.rmdir_all(dir) or {} }773	init_repo(dir)774	write(dir, 'secret.txt', 'keep\n')775	assert run(dir, 'save', 'secret').code == 0776	before_log := run(dir, 'log', '--json').out777	refused := run(dir, 'strip', 'secret.txt')778	assert refused.code == 1779	assert refused.err.contains('needs a terminal')780	assert run(dir, 'log', '--json').out == before_log781	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'782	assert run(dir, 'log', '--json').out.contains('secret')783}784785fn test_saves_and_checkpoints_aliases() {786	dir := temp_repo('aliases')787	defer { os.rmdir_all(dir) or {} }788	init_repo(dir)789	write(dir, 'alias.txt', 'one\n')790	assert run(dir, 'save', 'plain save').code == 0791	assert run(dir, 'checkpoint', 'checkpoint save').code == 0792	saves := run(dir, 'saves')793	assert saves.code == 0794	assert saves.out.contains('plain save')795	// The two lists never overlap, on a terminal or piped.796	assert !saves.out.contains('checkpoint save')797	checkpoints := run(dir, 'checkpoints')798	assert checkpoints.code == 0799	assert checkpoints.out.contains('checkpoint save')800	assert !checkpoints.out.contains('plain save')801	json_saves := run(dir, 'saves', '--json')802	assert json_saves.code == 0803	assert json_saves.out.contains('"is_checkpoint":false')804	assert !json_saves.out.contains('"is_checkpoint":true')805	json_result := run(dir, 'checkpoints', '--json')806	assert json_result.code == 0807	assert json_result.out.contains('"head_id"')808	assert json_result.out.contains('"saves"')809	assert json_result.out.contains('"is_checkpoint":true')810	assert !json_result.out.contains('"is_checkpoint":false')811	// `log` stays the whole line, checkpoints and all.812	assert run(dir, 'log').out.contains('checkpoint save')813}814815// Publishing refuses what it cannot do before it builds anything, and a real816// publish writes the layout §11.2 names. The command lines are checked first:817// a mistake there is a usage error, not a refusal.818fn test_offer_builds_refuses_bad_command_lines_and_a_dirty_tree() {819	dir := temp_repo('offer_builds')820	defer { os.rmdir_all(dir) or {} }821	init_repo(dir)822	home := temp_repo('offer_builds_home')823	defer { os.rmdir_all(home) or {} }824	name := os.base(dir)825	notes := 'a release note long enough to clear forty characters and the twelve word rule easily'826	assert run(dir, 'offer', '--notes', notes).code == 2827	assert run(dir, 'offer', '--notes', '').code == 2828	// A value-taking option with nothing after it is a usage error too.829	missing := run(dir, 'offer', '--notes')830	assert missing.code == 2831	assert missing.err.contains('needs a value')832	assert run(dir, 'offer', 'extra').code == 2833834	write(dir, 'VERSION', '1.2.3\n')835	write(dir, 'koh.build', 'command = mkdir -p out && printf x > out/demo-1.2.3-${this_platform()}836output = out/demo-{version}-{platform}837platforms = ${this_platform()}838')839	assert run(dir, 'save', 'first').code == 0840	remote := os.join_path(home, 'remote')841	assert run_home(dir, home, 'remote', 'folder', remote).code == 0842843	// A dirty tree cannot publish: the files must belong to a save.844	write(dir, 'extra.txt', 'unsaved\n')845	dirty := run_home(dir, home, 'offer', '--builds')846	assert dirty.code == 1847	assert dirty.err.contains('save or checkpoint first')848849	// Notes that say nothing are refused before anything is built or uploaded.850	assert run_home(dir, home, 'save', 'second').code == 0851	short := run_home(dir, home, 'offer', '--builds', '--notes', 'too short')852	assert short.code == 1853	assert short.err.contains('at least 40 characters')854	assert !os.exists(os.join_path(remote, name, 'releases'))855856	published := run_home(dir, home, 'offer', '--builds', '--notes', notes)857	assert published.code == 0, published.err858	artifact := 'demo-1.2.3-${this_platform()}'859	assert os.is_file(os.join_path(remote, name, 'releases/1.2.3/release.json'))860	assert os.is_file(os.join_path(remote, name, 'releases/1.2.3/${this_platform()}/${artifact}'))861	assert os.read_file(os.join_path(remote, name, 'releases/latest'))! == '1.2.3'862	record := os.read_file(os.join_path(remote, name, 'releases/1.2.3/release.json'))!863	assert record.contains('"notes":"${notes}"')864}865866fn test_remote_configuration_is_isolated_and_atomic() {867	dir := temp_repo('remote')868	home := temp_repo('remote-home')869	defer {870		os.rmdir_all(dir) or {}871		os.rmdir_all(home) or {}872	}873	empty := run_home(dir, home, 'remote', '--json')874	assert empty.code == 0875	assert empty.out.contains('"configured":false')876	target := os.join_path(home, 'remote-store')877	set := run_home(dir, home, 'remote', 'folder', target)878	assert set.code == 0879	assert os.is_dir(target)880	state := run_home(dir, home, 'remote', '--json')881	assert state.code == 0882	assert state.out.contains('"kind":"folder"')883	assert state.out.contains(target)884	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1885	assert run_home(dir, home, 'remote', '--json').out.contains(target)886	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')887	assert run_home(dir, home, 'remote', '--forget').code == 0888	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')889}890891// The files under ~/.config/koh can be written by hand instead of by892// `koh remote`, and are then read the same way.893fn test_remote_written_by_hand() {894	dir := temp_repo('remote-by-hand')895	home := temp_repo('remote-by-hand-home')896	defer {897		os.rmdir_all(dir) or {}898		os.rmdir_all(home) or {}899	}900	config := os.join_path(home, '.config', 'koh')901	os.mkdir_all(config) or { panic(err) }902	target := os.join_path(home, 'remote-store')903	os.mkdir_all(target) or { panic(err) }904	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {905		panic(err)906	}907	assert run_home(dir, home, 'init').code == 0908	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }909	assert run_home(dir, home, 'save', 'first').code == 0910	offered := run_home(dir, home, 'offer', '--json')911	assert offered.code == 0912	assert offered.out.contains('"head"')913914	// Keys anyone else can read are refused before they are ever sent.915	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {916		panic(err)917	}918	credentials := os.join_path(config, 'credentials')919	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }920	os.chmod(credentials, 0o644) or { panic(err) }921	loose := run_home(dir, home, 'offer')922	assert loose.code == 1923	assert loose.err.contains('chmod 600')924925	// A setting koh cannot read is replaced by setting the remote again.926	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }927	unreadable := run_home(dir, home, 'offer')928	assert unreadable.code == 1929	assert unreadable.err.contains('not readable')930	assert run_home(dir, home, 'remote', 'folder', target).code == 0931	assert run_home(dir, home, 'offer').code == 0932}933934// A clone belongs to the repo it was stolen from, whatever its folder is935// called later: renaming it must not start a second repo on the remote.936fn test_a_renamed_clone_keeps_offering_to_its_repo() {937	syncroot := temp_repo('rename-clone')938	home := temp_repo('rename-clone-home')939	defer {940		os.rmdir_all(syncroot) or {}941		os.rmdir_all(home) or {}942	}943	remote := os.join_path(syncroot, 'remote')944	a := os.join_path(syncroot, 'A', 'proj')945	b_parent := os.join_path(syncroot, 'B')946	os.mkdir_all(a) or { panic(err) }947	os.mkdir_all(b_parent) or { panic(err) }948	init_repo(a)949	write(a, 'a.txt', 'from A\n')950	assert run_home(a, home, 'remote', 'folder', remote).code == 0951	assert run_home(a, home, 'save', 'A first').code == 0952	assert run_home(b_parent, home, 'steal', 'proj').code == 0953	renamed := os.join_path(b_parent, 'renamed')954	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }955	write(renamed, 'b.txt', 'from B\n')956	assert run_home(renamed, home, 'save', 'B first').code == 0957	assert !os.exists(os.join_path(remote, 'renamed'))958	assert run_home(a, home, 'steal').code == 0959	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'960}961962// A damaged object on the remote stops a clone, names the object, and leaves963// no half-made folder that would make the retry refuse.964fn test_clone_of_a_damaged_remote_leaves_nothing() {965	syncroot := temp_repo('damaged')966	home := temp_repo('damaged-home')967	defer {968		os.rmdir_all(syncroot) or {}969		os.rmdir_all(home) or {}970	}971	remote := os.join_path(syncroot, 'remote')972	a := os.join_path(syncroot, 'A', 'proj')973	b_parent := os.join_path(syncroot, 'B')974	os.mkdir_all(a) or { panic(err) }975	os.mkdir_all(b_parent) or { panic(err) }976	init_repo(a)977	write(a, 'a.txt', 'from A\n')978	assert run_home(a, home, 'remote', 'folder', remote).code == 0979	assert run_home(a, home, 'save', 'A first').code == 0980	objects := os.join_path(remote, 'proj', 'objects')981	for name in os.ls(objects) or { panic(err) } {982		os.chmod(os.join_path(objects, name), 0o644) or {}983		os.write_file(os.join_path(objects, name), 'junk') or { panic(err) }984	}985	clone := run_home(b_parent, home, 'steal', 'proj')986	assert clone.code == 1987	assert clone.err.contains('is damaged')988	assert !os.exists(os.join_path(b_parent, 'proj'))989}990991fn test_offer_steal_folder_remote() {992	syncroot := temp_repo('sync')993	home := temp_repo('sync-home')994	defer {995		os.rmdir_all(syncroot) or {}996		os.rmdir_all(home) or {}997	}998	remote := os.join_path(syncroot, 'remote')999	a := os.join_path(syncroot, 'A', 'proj')1000	b_parent := os.join_path(syncroot, 'B')1001	os.mkdir_all(a) or { panic(err) }1002	os.mkdir_all(b_parent) or { panic(err) }1003	init_repo(a)1004	write(a, 'a.txt', 'from A\n')1005	assert run_home(a, home, 'remote', 'folder', remote).code == 01006	assert run_home(a, home, 'save', 'A first').code == 01007	clone := run_home(b_parent, home, 'steal', 'proj')1008	assert clone.code == 01009	b := os.join_path(b_parent, 'proj')1010	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'1011	write(b, 'b.txt', 'from B\n')1012	assert run_home(b, home, 'save', 'B first').code == 01013	write(a, 'a2.txt', 'second\n')1014	assert run_home(a, home, 'save', 'A second').code == 01015	assert run_home(a, home, 'steal').code == 01016	assert os.exists(os.join_path(a, 'b.txt'))1017	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')1018	write(a, 'clash.txt', 'base\n')1019	assert run_home(a, home, 'save', 'clash base').code == 01020	assert run_home(b, home, 'steal').code == 01021	write(a, 'clash.txt', 'A version\n')1022	assert run_home(a, home, 'save', 'A clash').code == 01023	write(b, 'clash.txt', 'B version\n')1024	assert run_home(b, home, 'save', 'B clash').code == 01025	refused := run_home(b, home, 'steal')1026	assert refused.code == 11027	assert refused.err.contains('--mine') || refused.err.contains('--theirs')1028	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1029	theirs := run_home(b, home, 'steal', '--theirs', '--json')1030	assert theirs.code == 01031	// The pre-combine tree is off the line now; the way back must be named,1032	// or an agent without the history view cannot find it.1033	assert theirs.out.contains('"previous_head":"${b_head}"')1034	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1035	assert run_home(b, home, 'load', b_head, '--yes').code == 01036	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'1037	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 01038	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1039	write(a, 'clash.txt', 'A second\n')1040	assert run_home(a, home, 'save', 'A second clash').code == 01041	write(b, 'clash.txt', 'B second\n')1042	assert run_home(b, home, 'save', 'B second clash').code == 01043	assert run_home(b, home, 'steal', '--mine').code == 01044	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'1045	assert run_home(b, home, 'log').out.contains('combine: kept mine for')1046}10471048// A clone brings in the whole history, flags included; both output forms must1049// say which saves came in flagged, and why.1050fn test_a_clone_reports_flagged_saves() {1051	syncroot := temp_repo('clone-flags')1052	home := temp_repo('clone-flags-home')1053	defer {1054		os.rmdir_all(syncroot) or {}1055		os.rmdir_all(home) or {}1056	}1057	a := os.join_path(syncroot, 'A', 'proj')1058	os.mkdir_all(a) or { panic(err) }1059	init_repo(a)1060	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 01061	write(a, 'a.txt', 'one\n')1062	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]1063	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 01064	assert run_home(a, home, 'offer').code == 01065	for name in ['B', 'C'] {1066		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }1067	}1068	json_clone := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')1069	assert json_clone.code == 01070	assert json_clone.out.contains('"flagged":["${id}"]')1071	text_clone := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')1072	assert text_clone.code == 01073	assert text_clone.out.contains('[${id}] came in flagged — broke the build')1074}10751076// A folder remote on a disk or share that is not mounted is simply not there.1077// Creating it would put the saves in a stand-in folder the other machine never1078// sees; the offer must say what is wrong instead.1079fn test_an_unmounted_folder_remote_is_not_recreated() {1080	syncroot := temp_repo('unmounted')1081	home := temp_repo('unmounted-home')1082	defer {1083		os.rmdir_all(syncroot) or {}1084		os.rmdir_all(home) or {}1085	}1086	mount := os.join_path(syncroot, 'nas')1087	remote := os.join_path(mount, 'koh')1088	a := os.join_path(syncroot, 'proj')1089	os.mkdir_all(a) or { panic(err) }1090	init_repo(a)1091	assert run_home(a, home, 'remote', 'folder', remote).code == 01092	write(a, 'a.txt', 'one\n')1093	assert run_home(a, home, 'save', 'first').code == 01094	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }1095	os.mkdir(mount) or { panic(err) }1096	offered := run_home(a, home, 'offer')1097	assert offered.code == 11098	assert offered.err.contains('mounted')1099	assert !os.exists(remote)1100	write(a, 'a.txt', 'two\n')1101	saved := run_home(a, home, 'save', 'second')1102	assert saved.code == 01103	assert saved.out.contains('mounted')1104	assert !os.exists(remote)1105}11061107fn test_man_and_koh2_handoff() {1108	dir := temp_repo('man')1109	home := temp_repo('man-home')1110	defer {1111		os.rmdir_all(dir) or {}1112		os.rmdir_all(home) or {}1113	}1114	whole := run_home(dir, home, 'man')1115	assert whole.code == 01116	assert whole.out.contains('NAME')1117	assert whole.out.contains('COMMANDS')1118	assert !whole.out.contains('\x1b') && !whole.out.contains('◆')1119	strip := run_home(dir, home, 'man', 'strip')1120	assert strip.code == 01121	assert strip.out.contains('strip')1122	assert !strip.out.contains('koh save ')1123	steal := run_home(dir, home, 'man', 'steal').out1124	assert steal.starts_with('    koh steal') && steal.contains('koh steal my-project')1125	assert run_home(dir, home, 'man', 'init').out.trim_space() == "koh init\n        Create `.koh` here, and a starter `.kohignore` if there isn't one."1126	assert run_home(dir, home, 'man', 'nonsense').code == 21127	legacy := temp_repo('legacy')1128	defer { os.rmdir_all(legacy) or {} }1129	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }1130	fake := os.join_path(home, 'bin')1131	os.mkdir_all(fake) or { panic(err) }1132	fake_koh := os.join_path(fake, 'koh2')1133	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }1134	os.chmod(fake_koh, 0o755) or { panic(err) }1135	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')1136	assert handoff.code == 71137	assert handoff.out.contains('handoff:status --json')1138	// One notice line, on stderr, so koh2's own output stays as it was.1139	assert handoff.err.contains('Koh 2 repo')1140	assert handoff.err.trim_space().split_into_lines().len == 11141	assert handoff.out.trim_space() == 'handoff:status --json'1142}11431144fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {1145	stamp := '${os.getpid()}-${time.now().unix_nano()}'1146	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')1147	out_path := '${base}.out'1148	err_path := '${base}.err'1149	code_path := '${base}.code'1150	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'1151	for arg in args {1152		command += ' ${q(arg)}'1153	}1154	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'1155	result := os.execute(shell)1156	if result.exit_code != 0 {1157		panic('could not run test command: ${result.output}')1158	}1159	code := os.read_file(code_path) or { panic(err) }1160	out := os.read_file(out_path) or { '' }1161	err := os.read_file(err_path) or { '' }1162	os.rm(out_path) or {}1163	os.rm(err_path) or {}1164	os.rm(code_path) or {}1165	return Result{1166		code: code.int()1167		out:  out1168		err:  err1169	}1170}11711172// --- migration -------------------------------------------------------------11731174fn koh2_binary() string {1175	return os.find_abs_path_of_executable('koh') or { '' }1176}11771178// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under1179// test here.1180fn run_koh2(dir string, command string) {1181	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')1182}11831184fn save_ids(dir string) []string {1185	mut ids := []string{}1186	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {1187		if name.ends_with('.json') {1188			ids << name.trim_right('.json')1189		}1190	}1191	ids.sort()1192	return ids1193}11941195fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {1196	koh2 := koh2_binary()1197	if koh2 == '' {1198		println('skipping the migration tests: koh (Koh 2) is not on PATH')1199		return1200	}1201	dir := temp_repo('migrate')1202	defer { os.rmdir_all(dir) or {} }1203	home := temp_repo('migrate-home')1204	defer { os.rmdir_all(home) or {} }1205	run_koh2(dir, '${q(koh2)} init')1206	// One file large enough to be an object, one small enough to be inlined.1207	write(dir, 'code.txt', 'x'.repeat(700))1208	write(dir, 'tiny.txt', 'tiny\n')1209	run_koh2(dir, '${q(koh2)} save "first save"')1210	run_koh2(dir, '${q(koh2)} checkpoint "before something"')1211	write(dir, 'code.txt', 'y'.repeat(700))1212	run_koh2(dir, '${q(koh2)} save "second save"')1213	original := save_ids(dir)1214	assert original.len == 312151216	report := run_home(dir, home, 'migrate')1217	assert report.code == 01218	assert report.out.contains('migrated 3 saves')1219	// The swap: `.koh` is a file, the old data is archived, nothing is staging.1220	assert os.is_file(os.join_path(dir, '.koh'))1221	assert os.is_dir(os.join_path(dir, '.koh-v2'))1222	assert os.is_file(os.join_path(dir, '.kohignore'))1223	assert !os.exists(os.join_path(dir, '.koh-migrate'))12241225	// Every save kept its original ID, and the new repo is sound.1226	logged := run_home(dir, home, 'log', '--json')1227	assert logged.code == 01228	for id in original {1229		assert logged.out.contains(id)1230	}1231	assert run_home(dir, home, 'doctor').code == 01232	assert run_home(dir, home, 'status').code == 012331234	// Migrating again has nothing to convert.1235	assert run_home(dir, home, 'migrate').code == 11236}12371238fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {1239	koh2 := koh2_binary()1240	if koh2 == '' {1241		return1242	}1243	dir := temp_repo('migrate-dirty')1244	defer { os.rmdir_all(dir) or {} }1245	home := temp_repo('migrate-dirty-home')1246	defer { os.rmdir_all(home) or {} }1247	run_koh2(dir, '${q(koh2)} init')1248	write(dir, 'code.txt', 'x'.repeat(700))1249	run_koh2(dir, '${q(koh2)} save "only save"')1250	write(dir, 'code.txt', 'unsaved change\n')12511252	refused := run_home(dir, home, 'migrate')1253	assert refused.code == 11254	assert refused.err.contains('save with koh2 first')1255	// Nothing moved: still Koh 2, no archive, no staging file.1256	assert os.is_dir(os.join_path(dir, '.koh'))1257	assert !os.exists(os.join_path(dir, '.koh-v2'))1258	assert !os.exists(os.join_path(dir, '.koh-migrate'))1259}12601261// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or1262// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have1263// a `.kohconfig`; migrate must not call them unsaved work.1264fn test_migrate_passes_over_the_files_koh2_never_saved() {1265	koh2 := koh2_binary()1266	if koh2 == '' {1267		return1268	}1269	dir := temp_repo('migrate-koh2-ignores')1270	defer { os.rmdir_all(dir) or {} }1271	home := temp_repo('migrate-koh2-ignores-home')1272	defer { os.rmdir_all(home) or {} }1273	run_koh2(dir, '${q(koh2)} init')1274	write(dir, 'code.txt', 'x'.repeat(700))1275	run_koh2(dir, '${q(koh2)} save "only save"')1276	write(dir, '.kohconfig', 'stable_days = 14\n')1277	write(dir, '.kohignore.public', 'private/\n')1278	write(dir, 'lib/app.bundle', 'bundle\n')1279	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1280	// Koh 2 keeps saving a file under a folder pattern added later, where1281	// Koh 3 reads the same rule as covering the folder: the saved file is on1282	// disk and matches, so the tree is clean.1283	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1284	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1285	// Koh 2 skips *.bundle even when its rules no longer list it.1286	ignore_path := os.join_path(dir, '.koh', 'ignore')1287	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1288	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1289	// A saved file the walk skips still has to match what was saved.1290	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1291	changed := run_home(dir, home, 'migrate')1292	assert changed.code == 11293	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1294	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1295	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')12961297	migrated := run_home(dir, home, 'migrate')1298	assert migrated.code == 0, migrated.err1299	// They stay where they were, for the user to keep or delete.1300	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1301}