cli_test.v

47.7 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', 'view', '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, 'view', '--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_view_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	printed := run(dir, 'view')576	assert printed.code == 0577	assert printed.out.contains('▸')578	assert printed.out.contains('◐')579	lj := run(dir, 'view', '--json')580	assert lj.code == 0581	assert lj.out.contains('"head_id"')582	assert lj.out.contains('"saves"')583	assert run(dir, 'view', '--since', 'today').out.contains('two')584	session := run(dir, 'view', '--session', 'alpha')585	assert session.out.contains('one')586	assert !session.out.contains('two')587	assert run(dir, 'view', '--since', '9999-01-01').out.contains('no saves in that range')588	write(dir, 'a.txt', 'three\n')589	d := run(dir, 'diff')590	assert d.code == 0591	assert d.out.contains('--- a/')592	assert d.out.contains('+++ b/')593	assert run(dir, 'diff', id1).code == 0594	assert run(dir, 'diff', id1, id2).code == 0595	dj := run(dir, 'diff', '--json')596	assert dj.code == 0597	assert dj.out.contains('"from"')598	assert dj.out.contains('"to"')599	assert dj.out.contains('"files"')600	assert dj.out.contains('"change":"modified"')601	assert run(dir, 'diff', 'not-a-real-id').code == 1602	assert run(dir, 'diff', id1, id2, 'third').code == 1603	write(dir, 'blob.bin', '\x00\x01\x02')604	diff_binary := run(dir, 'diff', '--json')605	assert diff_binary.out.contains('"binary":true')606	assert diff_binary.out.contains('Binary files differ')607}608609fn test_undo_revert_and_load() {610	dir := temp_repo('restore')611	defer { os.rmdir_all(dir) or {} }612	init_repo(dir)613	write(dir, 'a.txt', 'one\n')614	one := run(dir, 'save', 'one', '--json').out615	id1 := one.all_after('"id":"')[..12]616	write(dir, 'a.txt', 'two\n')617	write(dir, 'gone.txt', 'gone\n')618	second := run(dir, 'save', 'two', '--json').out619	id2 := second.all_after('"id":"')[..12]620	write(dir, 'a.txt', 'three\n')621	third := run(dir, 'save', 'three', '--json').out622	id3 := third.all_after('"id":"')[..12]623	// Unsaved work — here a file never saved — blocks every going-back but624	// revert, as in Koh 2: a restore must never overwrite what only the disk has.625	write(dir, 'never.txt', 'keep me\n')626	view_before := run(dir, 'view').out627	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {628		blocked := run(dir, ...args)629		assert blocked.code == 1630		assert blocked.err.contains('unsaved changes')631	}632	assert run(dir, 'view').out == view_before633	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }634	write(dir, 'a.txt', 'edited, never saved\n')635	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')636	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'637	write(dir, 'a.txt', 'three\n')638	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }639	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')640	write(dir, 'gone.txt', 'gone\n')641	undo := run(dir, 'undo', '--yes', '--json')642	assert undo.code == 0643	if !undo.out.contains(id2) {644		panic('undo JSON did not name ${id2}: ${undo.out}')645	}646	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'647	assert os.exists(os.join_path(dir, 'gone.txt'))648	assert run(dir, 'load', id3, '--yes').code == 0649	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'650	assert run(dir, 'undo', '2', '--yes').code == 0651	assert run(dir, 'load', id2, '--yes').code == 0652	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')653	write(dir, 'a.txt', 'dirty\n')654	before := run(dir, 'view')655	refuse := run(dir, 'revert')656	assert refuse.code == 1657	assert refuse.err.contains('needs --yes when not interactive')658	assert run(dir, 'view').out == before.out659	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'660	write(dir, 'untracked.txt', 'remove\n')661	rv := run(dir, 'revert', '--yes', '--json')662	assert rv.code == 0663	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'664	assert !os.exists(os.join_path(dir, 'untracked.txt'))665	// The way back to the discarded work is named, not left to be found.666	kept := rv.out.all_after('"checkpoint":"')[..12]667	assert run(dir, 'load', kept, '--yes').code == 0668	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'669	assert os.read_file(os.join_path(dir, 'untracked.txt'))! == 'remove\n'670	write(dir, 'a.txt', 'dirty again\n')671	assert run(dir, 'revert', '--yes').out.contains('koh load ')672	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')673	assert run(dir, 'load', '--checkpoint', '--yes').code == 0674	assert run(dir, 'load', id2, '--json').code == 1675	assert run(dir, 'load', id2, '--json').err.contains('error')676	assert run(dir, 'load').code == 2677	assert run(dir, 'load', 'unknown-id', '--yes').code == 1678}679680fn test_flag_and_flagged_view() {681	dir := temp_repo('flag')682	defer { os.rmdir_all(dir) or {} }683	init_repo(dir)684	write(dir, 'flag.txt', 'one\n')685	saved := run(dir, 'save', 'flag me', '--json')686	id := saved.out.all_after('"id":"')[..12]687	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')688	assert flagged.code == 0689	assert flagged.out.contains('"flagged":true')690	assert flagged.out.contains('"reason":"unsafe"')691	list := run(dir, 'flag', '--json')692	assert list.code == 0693	assert list.out.contains(id)694	assert list.out.contains('unsafe')695	assert run(dir, 'view').out.contains('⚑')696	assert run(dir, 'flag', '--clear', id).code == 0697	assert run(dir, 'flag').out.contains('nothing is flagged')698	assert run(dir, 'flag', 'unknown-id').code == 1699	assert run(dir, 'flag').code == 0700}701702fn test_pluck_forward_reverse_dry_run_and_conflict() {703	dir := temp_repo('pluck')704	defer { os.rmdir_all(dir) or {} }705	init_repo(dir)706	write(dir, 'a.txt', 'one\n')707	first := run(dir, 'save', 'one', '--json').out708	id1 := first.all_after('"id":"')[..12]709	write(dir, 'a.txt', 'two\n')710	second := run(dir, 'save', 'two', '--json').out711	id2 := second.all_after('"id":"')[..12]712	assert run(dir, 'load', id1, '--yes').code == 0713	dry := run(dir, 'pluck', id2, '--dry-run')714	assert dry.code == 0715	assert dry.out.contains('a.txt')716	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'717	assert run(dir, 'pluck', id2, '--yes').code == 0718	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'719	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0720	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'721	write(dir, 'a.txt', 'different\n')722	assert run(dir, 'pluck', id2, '--dry-run').code == 1723	assert run(dir, 'save', 'different').code == 0724	conflict := run(dir, 'pluck', id2, '--yes')725	assert conflict.code == 1726	assert conflict.err.contains('a.txt')727	assert run(dir, 'pluck').code == 2728	assert run(dir, 'pluck', 'unknown-id').code == 1729}730731fn test_peek_and_doctor() {732	dir := temp_repo('peek-doctor')733	defer { os.rmdir_all(dir) or {} }734	init_repo(dir)735	write(dir, 'peek.txt', 'peek me\n')736	assert run(dir, 'save', 'peekable').code == 0737	id := run(dir, 'view', '--json').out.all_after('"id":"')[..12]738	before_view := run(dir, 'view', '--json').out739	peek := run(dir, 'peek', id, '--json')740	assert peek.code == 0741	peek_path := peek.out.all_after('"path":"').before('"')742	assert peek.out.contains('"id":"${id}"')743	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'744	assert run(dir, 'status').out.contains('no changes')745	assert run(dir, 'view', '--json').out == before_view746	assert run(dir, 'peek').code == 2747	assert run(dir, 'peek', 'unknown-id').code == 1748	backup := os.join_path(dir, 'doctor.backup')749	healthy := run(dir, 'doctor')750	assert healthy.code == 0751	assert healthy.out.contains('is sound')752	report := run(dir, 'doctor', '--json')753	assert report.code == 0754	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',755		'backup'] {756		read_json_has(report.out, key)757	}758	backed := run(dir, 'doctor', '--backup', backup)759	assert backed.code == 0760	assert os.exists(backup)761	assert backed.out.contains(backup)762	assert run(dir, 'doctor', '--backup', backup).code == 1763	assert run(dir, 'peek', id, '--json').code == 0764	// A peek made today is left for whoever is reading it.765	kept := run(dir, 'doctor', '--json')766	assert kept.code == 0767	assert os.exists(peek_path)768	os.rmdir_all(peek_path) or {}769}770771fn test_strip_refuses_without_terminal() {772	dir := temp_repo('strip')773	defer { os.rmdir_all(dir) or {} }774	init_repo(dir)775	write(dir, 'secret.txt', 'keep\n')776	assert run(dir, 'save', 'secret').code == 0777	before_view := run(dir, 'view', '--json').out778	refused := run(dir, 'strip', 'secret.txt')779	assert refused.code == 1780	assert refused.err.contains('needs a terminal')781	assert run(dir, 'view', '--json').out == before_view782	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'783	assert run(dir, 'view', '--json').out.contains('secret')784}785786// `koh view` is the one way into the history: the whole line by default,787// checkpoints alone with the flag, and the two lists never overlap.788fn test_view_shows_the_line_and_checkpoints_apart() {789	dir := temp_repo('view')790	defer { os.rmdir_all(dir) or {} }791	init_repo(dir)792	write(dir, 'view.txt', 'one\n')793	assert run(dir, 'save', 'plain save').code == 0794	assert run(dir, 'checkpoint', 'checkpoint save').code == 0795	line := run(dir, 'view')796	assert line.code == 0797	assert line.out.contains('plain save')798	assert line.out.contains('checkpoint save')799	checkpoints := run(dir, 'view', '--checkpoints')800	assert checkpoints.code == 0801	assert checkpoints.out.contains('checkpoint save')802	assert !checkpoints.out.contains('plain save')803	json_line := run(dir, 'view', '--json')804	assert json_line.code == 0805	assert json_line.out.contains('"is_checkpoint":false')806	assert json_line.out.contains('"is_checkpoint":true')807	json_checkpoints := run(dir, 'view', '--checkpoints', '--json')808	assert json_checkpoints.code == 0809	assert json_checkpoints.out.contains('"is_checkpoint":true')810	assert !json_checkpoints.out.contains('"is_checkpoint":false')811	// `view` takes no arguments, so a stray one is a usage error, and the names812	// it replaced are gone rather than hidden: the diagnostic says which.813	assert run(dir, 'view', 'extra').code == 2814	for gone in ['log', 'saves', 'checkpoints'] {815		refused := run(dir, gone)816		assert refused.code == 2817		assert refused.err.contains('unknown command "${gone}"')818	}819	// Every save is on the whole line exactly once, as the JSON says.820	assert line.out.split_into_lines().len == json_line.out.count('"id":"')821}822823fn test_remote_configuration_is_isolated_and_atomic() {824	dir := temp_repo('remote')825	home := temp_repo('remote-home')826	defer {827		os.rmdir_all(dir) or {}828		os.rmdir_all(home) or {}829	}830	empty := run_home(dir, home, 'remote', '--json')831	assert empty.code == 0832	assert empty.out.contains('"configured":false')833	target := os.join_path(home, 'remote-store')834	set := run_home(dir, home, 'remote', 'folder', target)835	assert set.code == 0836	assert os.is_dir(target)837	state := run_home(dir, home, 'remote', '--json')838	assert state.code == 0839	assert state.out.contains('"kind":"folder"')840	assert state.out.contains(target)841	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1842	assert run_home(dir, home, 'remote', '--json').out.contains(target)843	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')844	assert run_home(dir, home, 'remote', '--forget').code == 0845	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')846}847848// The files under ~/.config/koh can be written by hand instead of by849// `koh remote`, and are then read the same way.850fn test_remote_written_by_hand() {851	dir := temp_repo('remote-by-hand')852	home := temp_repo('remote-by-hand-home')853	defer {854		os.rmdir_all(dir) or {}855		os.rmdir_all(home) or {}856	}857	config := os.join_path(home, '.config', 'koh')858	os.mkdir_all(config) or { panic(err) }859	target := os.join_path(home, 'remote-store')860	os.mkdir_all(target) or { panic(err) }861	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {862		panic(err)863	}864	assert run_home(dir, home, 'init').code == 0865	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }866	assert run_home(dir, home, 'save', 'first').code == 0867	offered := run_home(dir, home, 'offer', '--json')868	assert offered.code == 0869	assert offered.out.contains('"head"')870871	// Keys anyone else can read are refused before they are ever sent.872	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {873		panic(err)874	}875	credentials := os.join_path(config, 'credentials')876	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }877	os.chmod(credentials, 0o644) or { panic(err) }878	loose := run_home(dir, home, 'offer')879	assert loose.code == 1880	assert loose.err.contains('chmod 600')881882	// A setting koh cannot read is replaced by setting the remote again.883	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }884	unreadable := run_home(dir, home, 'offer')885	assert unreadable.code == 1886	assert unreadable.err.contains('not readable')887	assert run_home(dir, home, 'remote', 'folder', target).code == 0888	assert run_home(dir, home, 'offer').code == 0889}890891// A clone belongs to the repo it was stolen from, whatever its folder is892// called later: renaming it must not start a second repo on the remote.893fn test_a_renamed_clone_keeps_offering_to_its_repo() {894	syncroot := temp_repo('rename-clone')895	home := temp_repo('rename-clone-home')896	defer {897		os.rmdir_all(syncroot) or {}898		os.rmdir_all(home) or {}899	}900	remote := os.join_path(syncroot, 'remote')901	a := os.join_path(syncroot, 'A', 'proj')902	b_parent := os.join_path(syncroot, 'B')903	os.mkdir_all(a) or { panic(err) }904	os.mkdir_all(b_parent) or { panic(err) }905	init_repo(a)906	write(a, 'a.txt', 'from A\n')907	assert run_home(a, home, 'remote', 'folder', remote).code == 0908	assert run_home(a, home, 'save', 'A first').code == 0909	assert run_home(b_parent, home, 'steal', 'proj').code == 0910	renamed := os.join_path(b_parent, 'renamed')911	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }912	write(renamed, 'b.txt', 'from B\n')913	assert run_home(renamed, home, 'save', 'B first').code == 0914	assert !os.exists(os.join_path(remote, 'renamed'))915	assert run_home(a, home, 'steal').code == 0916	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'917}918919// A damaged object on the remote stops a clone, names the object, and leaves920// no half-made folder that would make the retry refuse.921fn test_clone_of_a_damaged_remote_leaves_nothing() {922	syncroot := temp_repo('damaged')923	home := temp_repo('damaged-home')924	defer {925		os.rmdir_all(syncroot) or {}926		os.rmdir_all(home) or {}927	}928	remote := os.join_path(syncroot, 'remote')929	a := os.join_path(syncroot, 'A', 'proj')930	b_parent := os.join_path(syncroot, 'B')931	os.mkdir_all(a) or { panic(err) }932	os.mkdir_all(b_parent) or { panic(err) }933	init_repo(a)934	write(a, 'a.txt', 'from A\n')935	assert run_home(a, home, 'remote', 'folder', remote).code == 0936	assert run_home(a, home, 'save', 'A first').code == 0937	objects := os.join_path(remote, 'proj', 'objects')938	for name in os.ls(objects) or { panic(err) } {939		os.chmod(os.join_path(objects, name), 0o644) or {}940		os.write_file(os.join_path(objects, name), 'junk') or { panic(err) }941	}942	clone := run_home(b_parent, home, 'steal', 'proj')943	assert clone.code == 1944	assert clone.err.contains('is damaged')945	assert !os.exists(os.join_path(b_parent, 'proj'))946}947948fn test_offer_steal_folder_remote() {949	syncroot := temp_repo('sync')950	home := temp_repo('sync-home')951	defer {952		os.rmdir_all(syncroot) or {}953		os.rmdir_all(home) or {}954	}955	remote := os.join_path(syncroot, 'remote')956	a := os.join_path(syncroot, 'A', 'proj')957	b_parent := os.join_path(syncroot, 'B')958	os.mkdir_all(a) or { panic(err) }959	os.mkdir_all(b_parent) or { panic(err) }960	init_repo(a)961	write(a, 'a.txt', 'from A\n')962	assert run_home(a, home, 'remote', 'folder', remote).code == 0963	assert run_home(a, home, 'save', 'A first').code == 0964	clone := run_home(b_parent, home, 'steal', 'proj')965	assert clone.code == 0966	b := os.join_path(b_parent, 'proj')967	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'968	write(b, 'b.txt', 'from B\n')969	assert run_home(b, home, 'save', 'B first').code == 0970	write(a, 'a2.txt', 'second\n')971	assert run_home(a, home, 'save', 'A second').code == 0972	assert run_home(a, home, 'steal').code == 0973	assert os.exists(os.join_path(a, 'b.txt'))974	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')975	write(a, 'clash.txt', 'base\n')976	assert run_home(a, home, 'save', 'clash base').code == 0977	assert run_home(b, home, 'steal').code == 0978	write(a, 'clash.txt', 'A version\n')979	assert run_home(a, home, 'save', 'A clash').code == 0980	write(b, 'clash.txt', 'B version\n')981	assert run_home(b, home, 'save', 'B clash').code == 0982	refused := run_home(b, home, 'steal')983	assert refused.code == 1984	assert refused.err.contains('--mine') || refused.err.contains('--theirs')985	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]986	theirs := run_home(b, home, 'steal', '--theirs', '--json')987	assert theirs.code == 0988	// The pre-combine tree is off the line now; the way back must be named,989	// or an agent without the history view cannot find it.990	assert theirs.out.contains('"previous_head":"${b_head}"')991	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'992	assert run_home(b, home, 'load', b_head, '--yes').code == 0993	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'994	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 0995	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'996	write(a, 'clash.txt', 'A second\n')997	assert run_home(a, home, 'save', 'A second clash').code == 0998	write(b, 'clash.txt', 'B second\n')999	assert run_home(b, home, 'save', 'B second clash').code == 01000	assert run_home(b, home, 'steal', '--mine').code == 01001	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'1002	assert run_home(b, home, 'view').out.contains('combine: kept mine for')1003}10041005// A clone brings in the whole history, flags included; both output forms must1006// say which saves came in flagged, and why.1007fn test_a_clone_reports_flagged_saves() {1008	syncroot := temp_repo('clone-flags')1009	home := temp_repo('clone-flags-home')1010	defer {1011		os.rmdir_all(syncroot) or {}1012		os.rmdir_all(home) or {}1013	}1014	a := os.join_path(syncroot, 'A', 'proj')1015	os.mkdir_all(a) or { panic(err) }1016	init_repo(a)1017	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 01018	write(a, 'a.txt', 'one\n')1019	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]1020	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 01021	assert run_home(a, home, 'offer').code == 01022	for name in ['B', 'C'] {1023		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }1024	}1025	json_clone := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')1026	assert json_clone.code == 01027	assert json_clone.out.contains('"flagged":["${id}"]')1028	text_clone := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')1029	assert text_clone.code == 01030	assert text_clone.out.contains('[${id}] came in flagged — broke the build')1031}10321033// A folder remote on a disk or share that is not mounted is simply not there.1034// Creating it would put the saves in a stand-in folder the other machine never1035// sees; the offer must say what is wrong instead.1036fn test_an_unmounted_folder_remote_is_not_recreated() {1037	syncroot := temp_repo('unmounted')1038	home := temp_repo('unmounted-home')1039	defer {1040		os.rmdir_all(syncroot) or {}1041		os.rmdir_all(home) or {}1042	}1043	mount := os.join_path(syncroot, 'nas')1044	remote := os.join_path(mount, 'koh')1045	a := os.join_path(syncroot, 'proj')1046	os.mkdir_all(a) or { panic(err) }1047	init_repo(a)1048	assert run_home(a, home, 'remote', 'folder', remote).code == 01049	write(a, 'a.txt', 'one\n')1050	assert run_home(a, home, 'save', 'first').code == 01051	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }1052	os.mkdir(mount) or { panic(err) }1053	offered := run_home(a, home, 'offer')1054	assert offered.code == 11055	assert offered.err.contains('mounted')1056	assert !os.exists(remote)1057	write(a, 'a.txt', 'two\n')1058	saved := run_home(a, home, 'save', 'second')1059	assert saved.code == 01060	assert saved.out.contains('mounted')1061	assert !os.exists(remote)1062}10631064fn test_man_and_koh2_handoff() {1065	dir := temp_repo('man')1066	home := temp_repo('man-home')1067	defer {1068		os.rmdir_all(dir) or {}1069		os.rmdir_all(home) or {}1070	}1071	whole := run_home(dir, home, 'man')1072	assert whole.code == 01073	assert whole.out.contains('NAME')1074	assert whole.out.contains('COMMANDS')1075	assert !whole.out.contains('\x1b') && !whole.out.contains('◆')1076	strip := run_home(dir, home, 'man', 'strip')1077	assert strip.code == 01078	assert strip.out.contains('strip')1079	assert !strip.out.contains('koh save ')1080	steal := run_home(dir, home, 'man', 'steal').out1081	assert steal.starts_with('    koh steal') && steal.contains('koh steal my-project')1082	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."1083	assert run_home(dir, home, 'man', 'nonsense').code == 21084	legacy := temp_repo('legacy')1085	defer { os.rmdir_all(legacy) or {} }1086	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }1087	fake := os.join_path(home, 'bin')1088	os.mkdir_all(fake) or { panic(err) }1089	fake_koh := os.join_path(fake, 'koh2')1090	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }1091	os.chmod(fake_koh, 0o755) or { panic(err) }1092	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')1093	assert handoff.code == 71094	assert handoff.out.contains('handoff:status --json')1095	// One notice line, on stderr, so koh2's own output stays as it was.1096	assert handoff.err.contains('Koh 2 repo')1097	assert handoff.err.trim_space().split_into_lines().len == 11098	assert handoff.out.trim_space() == 'handoff:status --json'1099}11001101fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {1102	stamp := '${os.getpid()}-${time.now().unix_nano()}'1103	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')1104	out_path := '${base}.out'1105	err_path := '${base}.err'1106	code_path := '${base}.code'1107	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'1108	for arg in args {1109		command += ' ${q(arg)}'1110	}1111	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'1112	result := os.execute(shell)1113	if result.exit_code != 0 {1114		panic('could not run test command: ${result.output}')1115	}1116	code := os.read_file(code_path) or { panic(err) }1117	out := os.read_file(out_path) or { '' }1118	err := os.read_file(err_path) or { '' }1119	os.rm(out_path) or {}1120	os.rm(err_path) or {}1121	os.rm(code_path) or {}1122	return Result{1123		code: code.int()1124		out:  out1125		err:  err1126	}1127}11281129// --- migration -------------------------------------------------------------11301131fn koh2_binary() string {1132	return os.find_abs_path_of_executable('koh') or { '' }1133}11341135// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under1136// test here.1137fn run_koh2(dir string, command string) {1138	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')1139}11401141fn save_ids(dir string) []string {1142	mut ids := []string{}1143	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {1144		if name.ends_with('.json') {1145			ids << name.trim_right('.json')1146		}1147	}1148	ids.sort()1149	return ids1150}11511152fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {1153	koh2 := koh2_binary()1154	if koh2 == '' {1155		println('skipping the migration tests: koh (Koh 2) is not on PATH')1156		return1157	}1158	dir := temp_repo('migrate')1159	defer { os.rmdir_all(dir) or {} }1160	home := temp_repo('migrate-home')1161	defer { os.rmdir_all(home) or {} }1162	run_koh2(dir, '${q(koh2)} init')1163	// One file large enough to be an object, one small enough to be inlined.1164	write(dir, 'code.txt', 'x'.repeat(700))1165	write(dir, 'tiny.txt', 'tiny\n')1166	run_koh2(dir, '${q(koh2)} save "first save"')1167	run_koh2(dir, '${q(koh2)} checkpoint "before something"')1168	write(dir, 'code.txt', 'y'.repeat(700))1169	run_koh2(dir, '${q(koh2)} save "second save"')1170	original := save_ids(dir)1171	assert original.len == 311721173	report := run_home(dir, home, 'migrate')1174	assert report.code == 01175	assert report.out.contains('migrated 3 saves')1176	// The swap: `.koh` is a file, the old data is archived, nothing is staging.1177	assert os.is_file(os.join_path(dir, '.koh'))1178	assert os.is_dir(os.join_path(dir, '.koh-v2'))1179	assert os.is_file(os.join_path(dir, '.kohignore'))1180	assert !os.exists(os.join_path(dir, '.koh-migrate'))11811182	// Every save kept its original ID, and the new repo is sound.1183	listed := run_home(dir, home, 'view', '--json')1184	assert listed.code == 01185	for id in original {1186		assert listed.out.contains(id)1187	}1188	assert run_home(dir, home, 'doctor').code == 01189	assert run_home(dir, home, 'status').code == 011901191	// Migrating again has nothing to convert.1192	assert run_home(dir, home, 'migrate').code == 11193}11941195fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {1196	koh2 := koh2_binary()1197	if koh2 == '' {1198		return1199	}1200	dir := temp_repo('migrate-dirty')1201	defer { os.rmdir_all(dir) or {} }1202	home := temp_repo('migrate-dirty-home')1203	defer { os.rmdir_all(home) or {} }1204	run_koh2(dir, '${q(koh2)} init')1205	write(dir, 'code.txt', 'x'.repeat(700))1206	run_koh2(dir, '${q(koh2)} save "only save"')1207	write(dir, 'code.txt', 'unsaved change\n')12081209	refused := run_home(dir, home, 'migrate')1210	assert refused.code == 11211	assert refused.err.contains('save with koh2 first')1212	// Nothing moved: still Koh 2, no archive, no staging file.1213	assert os.is_dir(os.join_path(dir, '.koh'))1214	assert !os.exists(os.join_path(dir, '.koh-v2'))1215	assert !os.exists(os.join_path(dir, '.koh-migrate'))1216}12171218// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or1219// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have1220// a `.kohconfig`; migrate must not call them unsaved work.1221fn test_migrate_passes_over_the_files_koh2_never_saved() {1222	koh2 := koh2_binary()1223	if koh2 == '' {1224		return1225	}1226	dir := temp_repo('migrate-koh2-ignores')1227	defer { os.rmdir_all(dir) or {} }1228	home := temp_repo('migrate-koh2-ignores-home')1229	defer { os.rmdir_all(home) or {} }1230	run_koh2(dir, '${q(koh2)} init')1231	write(dir, 'code.txt', 'x'.repeat(700))1232	run_koh2(dir, '${q(koh2)} save "only save"')1233	write(dir, '.kohconfig', 'stable_days = 14\n')1234	write(dir, '.kohignore.public', 'private/\n')1235	write(dir, 'lib/app.bundle', 'bundle\n')1236	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1237	// Koh 2 keeps saving a file under a folder pattern added later, where1238	// Koh 3 reads the same rule as covering the folder: the saved file is on1239	// disk and matches, so the tree is clean.1240	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1241	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1242	// Koh 2 skips *.bundle even when its rules no longer list it.1243	ignore_path := os.join_path(dir, '.koh', 'ignore')1244	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1245	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1246	// A saved file the walk skips still has to match what was saved.1247	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1248	changed := run_home(dir, home, 'migrate')1249	assert changed.code == 11250	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1251	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1252	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')12531254	migrated := run_home(dir, home, 'migrate')1255	assert migrated.code == 0, migrated.err1256	// They stay where they were, for the user to keep or delete.1257	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1258}