cli_test.v

47.3 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	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	view_before := run(dir, 'view').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, 'view').out == view_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, 'view')654	refuse := run(dir, 'revert')655	assert refuse.code == 1656	assert refuse.err.contains('needs --yes when not interactive')657	assert run(dir, 'view').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_view() {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, 'view').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, 'view', '--json').out.all_after('"id":"')[..12]737	before_view := run(dir, 'view', '--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, 'view', '--json').out == before_view745	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_view := run(dir, 'view', '--json').out777	refused := run(dir, 'strip', 'secret.txt')778	assert refused.code == 1779	assert refused.err.contains('needs a terminal')780	assert run(dir, 'view', '--json').out == before_view781	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'782	assert run(dir, 'view', '--json').out.contains('secret')783}784785// `koh view` is the one way into the history: the whole line by default,786// checkpoints alone with the flag, and the two lists never overlap.787fn test_view_shows_the_line_and_checkpoints_apart() {788	dir := temp_repo('view')789	defer { os.rmdir_all(dir) or {} }790	init_repo(dir)791	write(dir, 'view.txt', 'one\n')792	assert run(dir, 'save', 'plain save').code == 0793	assert run(dir, 'checkpoint', 'checkpoint save').code == 0794	line := run(dir, 'view')795	assert line.code == 0796	assert line.out.contains('plain save')797	assert line.out.contains('checkpoint save')798	checkpoints := run(dir, 'view', '--checkpoints')799	assert checkpoints.code == 0800	assert checkpoints.out.contains('checkpoint save')801	assert !checkpoints.out.contains('plain save')802	json_line := run(dir, 'view', '--json')803	assert json_line.code == 0804	assert json_line.out.contains('"is_checkpoint":false')805	assert json_line.out.contains('"is_checkpoint":true')806	json_checkpoints := run(dir, 'view', '--checkpoints', '--json')807	assert json_checkpoints.code == 0808	assert json_checkpoints.out.contains('"is_checkpoint":true')809	assert !json_checkpoints.out.contains('"is_checkpoint":false')810	// `view` takes no arguments, so a stray one is a usage error, and `log` is811	// gone rather than hidden.812	assert run(dir, 'view', 'extra').code == 2813	assert run(dir, 'log').code == 2814	assert run(dir, 'saves').code == 2815	assert run(dir, 'checkpoints').code == 2816}817818fn test_remote_configuration_is_isolated_and_atomic() {819	dir := temp_repo('remote')820	home := temp_repo('remote-home')821	defer {822		os.rmdir_all(dir) or {}823		os.rmdir_all(home) or {}824	}825	empty := run_home(dir, home, 'remote', '--json')826	assert empty.code == 0827	assert empty.out.contains('"configured":false')828	target := os.join_path(home, 'remote-store')829	set := run_home(dir, home, 'remote', 'folder', target)830	assert set.code == 0831	assert os.is_dir(target)832	state := run_home(dir, home, 'remote', '--json')833	assert state.code == 0834	assert state.out.contains('"kind":"folder"')835	assert state.out.contains(target)836	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1837	assert run_home(dir, home, 'remote', '--json').out.contains(target)838	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')839	assert run_home(dir, home, 'remote', '--forget').code == 0840	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')841}842843// The files under ~/.config/koh can be written by hand instead of by844// `koh remote`, and are then read the same way.845fn test_remote_written_by_hand() {846	dir := temp_repo('remote-by-hand')847	home := temp_repo('remote-by-hand-home')848	defer {849		os.rmdir_all(dir) or {}850		os.rmdir_all(home) or {}851	}852	config := os.join_path(home, '.config', 'koh')853	os.mkdir_all(config) or { panic(err) }854	target := os.join_path(home, 'remote-store')855	os.mkdir_all(target) or { panic(err) }856	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {857		panic(err)858	}859	assert run_home(dir, home, 'init').code == 0860	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }861	assert run_home(dir, home, 'save', 'first').code == 0862	offered := run_home(dir, home, 'offer', '--json')863	assert offered.code == 0864	assert offered.out.contains('"head"')865866	// Keys anyone else can read are refused before they are ever sent.867	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {868		panic(err)869	}870	credentials := os.join_path(config, 'credentials')871	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }872	os.chmod(credentials, 0o644) or { panic(err) }873	loose := run_home(dir, home, 'offer')874	assert loose.code == 1875	assert loose.err.contains('chmod 600')876877	// A setting koh cannot read is replaced by setting the remote again.878	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }879	unreadable := run_home(dir, home, 'offer')880	assert unreadable.code == 1881	assert unreadable.err.contains('not readable')882	assert run_home(dir, home, 'remote', 'folder', target).code == 0883	assert run_home(dir, home, 'offer').code == 0884}885886// A clone belongs to the repo it was stolen from, whatever its folder is887// called later: renaming it must not start a second repo on the remote.888fn test_a_renamed_clone_keeps_offering_to_its_repo() {889	syncroot := temp_repo('rename-clone')890	home := temp_repo('rename-clone-home')891	defer {892		os.rmdir_all(syncroot) or {}893		os.rmdir_all(home) or {}894	}895	remote := os.join_path(syncroot, 'remote')896	a := os.join_path(syncroot, 'A', 'proj')897	b_parent := os.join_path(syncroot, 'B')898	os.mkdir_all(a) or { panic(err) }899	os.mkdir_all(b_parent) or { panic(err) }900	init_repo(a)901	write(a, 'a.txt', 'from A\n')902	assert run_home(a, home, 'remote', 'folder', remote).code == 0903	assert run_home(a, home, 'save', 'A first').code == 0904	assert run_home(b_parent, home, 'steal', 'proj').code == 0905	renamed := os.join_path(b_parent, 'renamed')906	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }907	write(renamed, 'b.txt', 'from B\n')908	assert run_home(renamed, home, 'save', 'B first').code == 0909	assert !os.exists(os.join_path(remote, 'renamed'))910	assert run_home(a, home, 'steal').code == 0911	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'912}913914// A damaged object on the remote stops a clone, names the object, and leaves915// no half-made folder that would make the retry refuse.916fn test_clone_of_a_damaged_remote_leaves_nothing() {917	syncroot := temp_repo('damaged')918	home := temp_repo('damaged-home')919	defer {920		os.rmdir_all(syncroot) or {}921		os.rmdir_all(home) or {}922	}923	remote := os.join_path(syncroot, 'remote')924	a := os.join_path(syncroot, 'A', 'proj')925	b_parent := os.join_path(syncroot, 'B')926	os.mkdir_all(a) or { panic(err) }927	os.mkdir_all(b_parent) or { panic(err) }928	init_repo(a)929	write(a, 'a.txt', 'from A\n')930	assert run_home(a, home, 'remote', 'folder', remote).code == 0931	assert run_home(a, home, 'save', 'A first').code == 0932	objects := os.join_path(remote, 'proj', 'objects')933	for name in os.ls(objects) or { panic(err) } {934		os.chmod(os.join_path(objects, name), 0o644) or {}935		os.write_file(os.join_path(objects, name), 'junk') or { panic(err) }936	}937	clone := run_home(b_parent, home, 'steal', 'proj')938	assert clone.code == 1939	assert clone.err.contains('is damaged')940	assert !os.exists(os.join_path(b_parent, 'proj'))941}942943fn test_offer_steal_folder_remote() {944	syncroot := temp_repo('sync')945	home := temp_repo('sync-home')946	defer {947		os.rmdir_all(syncroot) or {}948		os.rmdir_all(home) or {}949	}950	remote := os.join_path(syncroot, 'remote')951	a := os.join_path(syncroot, 'A', 'proj')952	b_parent := os.join_path(syncroot, 'B')953	os.mkdir_all(a) or { panic(err) }954	os.mkdir_all(b_parent) or { panic(err) }955	init_repo(a)956	write(a, 'a.txt', 'from A\n')957	assert run_home(a, home, 'remote', 'folder', remote).code == 0958	assert run_home(a, home, 'save', 'A first').code == 0959	clone := run_home(b_parent, home, 'steal', 'proj')960	assert clone.code == 0961	b := os.join_path(b_parent, 'proj')962	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'963	write(b, 'b.txt', 'from B\n')964	assert run_home(b, home, 'save', 'B first').code == 0965	write(a, 'a2.txt', 'second\n')966	assert run_home(a, home, 'save', 'A second').code == 0967	assert run_home(a, home, 'steal').code == 0968	assert os.exists(os.join_path(a, 'b.txt'))969	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')970	write(a, 'clash.txt', 'base\n')971	assert run_home(a, home, 'save', 'clash base').code == 0972	assert run_home(b, home, 'steal').code == 0973	write(a, 'clash.txt', 'A version\n')974	assert run_home(a, home, 'save', 'A clash').code == 0975	write(b, 'clash.txt', 'B version\n')976	assert run_home(b, home, 'save', 'B clash').code == 0977	refused := run_home(b, home, 'steal')978	assert refused.code == 1979	assert refused.err.contains('--mine') || refused.err.contains('--theirs')980	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]981	theirs := run_home(b, home, 'steal', '--theirs', '--json')982	assert theirs.code == 0983	// The pre-combine tree is off the line now; the way back must be named,984	// or an agent without the history view cannot find it.985	assert theirs.out.contains('"previous_head":"${b_head}"')986	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'987	assert run_home(b, home, 'load', b_head, '--yes').code == 0988	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'989	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 0990	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'991	write(a, 'clash.txt', 'A second\n')992	assert run_home(a, home, 'save', 'A second clash').code == 0993	write(b, 'clash.txt', 'B second\n')994	assert run_home(b, home, 'save', 'B second clash').code == 0995	assert run_home(b, home, 'steal', '--mine').code == 0996	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'997	assert run_home(b, home, 'view').out.contains('combine: kept mine for')998}9991000// A clone brings in the whole history, flags included; both output forms must1001// say which saves came in flagged, and why.1002fn test_a_clone_reports_flagged_saves() {1003	syncroot := temp_repo('clone-flags')1004	home := temp_repo('clone-flags-home')1005	defer {1006		os.rmdir_all(syncroot) or {}1007		os.rmdir_all(home) or {}1008	}1009	a := os.join_path(syncroot, 'A', 'proj')1010	os.mkdir_all(a) or { panic(err) }1011	init_repo(a)1012	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 01013	write(a, 'a.txt', 'one\n')1014	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]1015	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 01016	assert run_home(a, home, 'offer').code == 01017	for name in ['B', 'C'] {1018		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }1019	}1020	json_clone := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')1021	assert json_clone.code == 01022	assert json_clone.out.contains('"flagged":["${id}"]')1023	text_clone := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')1024	assert text_clone.code == 01025	assert text_clone.out.contains('[${id}] came in flagged — broke the build')1026}10271028// A folder remote on a disk or share that is not mounted is simply not there.1029// Creating it would put the saves in a stand-in folder the other machine never1030// sees; the offer must say what is wrong instead.1031fn test_an_unmounted_folder_remote_is_not_recreated() {1032	syncroot := temp_repo('unmounted')1033	home := temp_repo('unmounted-home')1034	defer {1035		os.rmdir_all(syncroot) or {}1036		os.rmdir_all(home) or {}1037	}1038	mount := os.join_path(syncroot, 'nas')1039	remote := os.join_path(mount, 'koh')1040	a := os.join_path(syncroot, 'proj')1041	os.mkdir_all(a) or { panic(err) }1042	init_repo(a)1043	assert run_home(a, home, 'remote', 'folder', remote).code == 01044	write(a, 'a.txt', 'one\n')1045	assert run_home(a, home, 'save', 'first').code == 01046	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }1047	os.mkdir(mount) or { panic(err) }1048	offered := run_home(a, home, 'offer')1049	assert offered.code == 11050	assert offered.err.contains('mounted')1051	assert !os.exists(remote)1052	write(a, 'a.txt', 'two\n')1053	saved := run_home(a, home, 'save', 'second')1054	assert saved.code == 01055	assert saved.out.contains('mounted')1056	assert !os.exists(remote)1057}10581059fn test_man_and_koh2_handoff() {1060	dir := temp_repo('man')1061	home := temp_repo('man-home')1062	defer {1063		os.rmdir_all(dir) or {}1064		os.rmdir_all(home) or {}1065	}1066	whole := run_home(dir, home, 'man')1067	assert whole.code == 01068	assert whole.out.contains('NAME')1069	assert whole.out.contains('COMMANDS')1070	assert !whole.out.contains('\x1b') && !whole.out.contains('◆')1071	strip := run_home(dir, home, 'man', 'strip')1072	assert strip.code == 01073	assert strip.out.contains('strip')1074	assert !strip.out.contains('koh save ')1075	steal := run_home(dir, home, 'man', 'steal').out1076	assert steal.starts_with('    koh steal') && steal.contains('koh steal my-project')1077	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."1078	assert run_home(dir, home, 'man', 'nonsense').code == 21079	legacy := temp_repo('legacy')1080	defer { os.rmdir_all(legacy) or {} }1081	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }1082	fake := os.join_path(home, 'bin')1083	os.mkdir_all(fake) or { panic(err) }1084	fake_koh := os.join_path(fake, 'koh2')1085	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }1086	os.chmod(fake_koh, 0o755) or { panic(err) }1087	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')1088	assert handoff.code == 71089	assert handoff.out.contains('handoff:status --json')1090	// One notice line, on stderr, so koh2's own output stays as it was.1091	assert handoff.err.contains('Koh 2 repo')1092	assert handoff.err.trim_space().split_into_lines().len == 11093	assert handoff.out.trim_space() == 'handoff:status --json'1094}10951096fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {1097	stamp := '${os.getpid()}-${time.now().unix_nano()}'1098	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')1099	out_path := '${base}.out'1100	err_path := '${base}.err'1101	code_path := '${base}.code'1102	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'1103	for arg in args {1104		command += ' ${q(arg)}'1105	}1106	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'1107	result := os.execute(shell)1108	if result.exit_code != 0 {1109		panic('could not run test command: ${result.output}')1110	}1111	code := os.read_file(code_path) or { panic(err) }1112	out := os.read_file(out_path) or { '' }1113	err := os.read_file(err_path) or { '' }1114	os.rm(out_path) or {}1115	os.rm(err_path) or {}1116	os.rm(code_path) or {}1117	return Result{1118		code: code.int()1119		out:  out1120		err:  err1121	}1122}11231124// --- migration -------------------------------------------------------------11251126fn koh2_binary() string {1127	return os.find_abs_path_of_executable('koh') or { '' }1128}11291130// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under1131// test here.1132fn run_koh2(dir string, command string) {1133	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')1134}11351136fn save_ids(dir string) []string {1137	mut ids := []string{}1138	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {1139		if name.ends_with('.json') {1140			ids << name.trim_right('.json')1141		}1142	}1143	ids.sort()1144	return ids1145}11461147fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {1148	koh2 := koh2_binary()1149	if koh2 == '' {1150		println('skipping the migration tests: koh (Koh 2) is not on PATH')1151		return1152	}1153	dir := temp_repo('migrate')1154	defer { os.rmdir_all(dir) or {} }1155	home := temp_repo('migrate-home')1156	defer { os.rmdir_all(home) or {} }1157	run_koh2(dir, '${q(koh2)} init')1158	// One file large enough to be an object, one small enough to be inlined.1159	write(dir, 'code.txt', 'x'.repeat(700))1160	write(dir, 'tiny.txt', 'tiny\n')1161	run_koh2(dir, '${q(koh2)} save "first save"')1162	run_koh2(dir, '${q(koh2)} checkpoint "before something"')1163	write(dir, 'code.txt', 'y'.repeat(700))1164	run_koh2(dir, '${q(koh2)} save "second save"')1165	original := save_ids(dir)1166	assert original.len == 311671168	report := run_home(dir, home, 'migrate')1169	assert report.code == 01170	assert report.out.contains('migrated 3 saves')1171	// The swap: `.koh` is a file, the old data is archived, nothing is staging.1172	assert os.is_file(os.join_path(dir, '.koh'))1173	assert os.is_dir(os.join_path(dir, '.koh-v2'))1174	assert os.is_file(os.join_path(dir, '.kohignore'))1175	assert !os.exists(os.join_path(dir, '.koh-migrate'))11761177	// Every save kept its original ID, and the new repo is sound.1178	listed := run_home(dir, home, 'view', '--json')1179	assert listed.code == 01180	for id in original {1181		assert listed.out.contains(id)1182	}1183	assert run_home(dir, home, 'doctor').code == 01184	assert run_home(dir, home, 'status').code == 011851186	// Migrating again has nothing to convert.1187	assert run_home(dir, home, 'migrate').code == 11188}11891190fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {1191	koh2 := koh2_binary()1192	if koh2 == '' {1193		return1194	}1195	dir := temp_repo('migrate-dirty')1196	defer { os.rmdir_all(dir) or {} }1197	home := temp_repo('migrate-dirty-home')1198	defer { os.rmdir_all(home) or {} }1199	run_koh2(dir, '${q(koh2)} init')1200	write(dir, 'code.txt', 'x'.repeat(700))1201	run_koh2(dir, '${q(koh2)} save "only save"')1202	write(dir, 'code.txt', 'unsaved change\n')12031204	refused := run_home(dir, home, 'migrate')1205	assert refused.code == 11206	assert refused.err.contains('save with koh2 first')1207	// Nothing moved: still Koh 2, no archive, no staging file.1208	assert os.is_dir(os.join_path(dir, '.koh'))1209	assert !os.exists(os.join_path(dir, '.koh-v2'))1210	assert !os.exists(os.join_path(dir, '.koh-migrate'))1211}12121213// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or1214// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have1215// a `.kohconfig`; migrate must not call them unsaved work.1216fn test_migrate_passes_over_the_files_koh2_never_saved() {1217	koh2 := koh2_binary()1218	if koh2 == '' {1219		return1220	}1221	dir := temp_repo('migrate-koh2-ignores')1222	defer { os.rmdir_all(dir) or {} }1223	home := temp_repo('migrate-koh2-ignores-home')1224	defer { os.rmdir_all(home) or {} }1225	run_koh2(dir, '${q(koh2)} init')1226	write(dir, 'code.txt', 'x'.repeat(700))1227	run_koh2(dir, '${q(koh2)} save "only save"')1228	write(dir, '.kohconfig', 'stable_days = 14\n')1229	write(dir, '.kohignore.public', 'private/\n')1230	write(dir, 'lib/app.bundle', 'bundle\n')1231	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1232	// Koh 2 keeps saving a file under a folder pattern added later, where1233	// Koh 3 reads the same rule as covering the folder: the saved file is on1234	// disk and matches, so the tree is clean.1235	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1236	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1237	// Koh 2 skips *.bundle even when its rules no longer list it.1238	ignore_path := os.join_path(dir, '.koh', 'ignore')1239	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1240	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1241	// A saved file the walk skips still has to match what was saved.1242	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1243	changed := run_home(dir, home, 'migrate')1244	assert changed.code == 11245	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1246	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1247	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')12481249	migrated := run_home(dir, home, 'migrate')1250	assert migrated.code == 0, migrated.err1251	// They stay where they were, for the user to keep or delete.1252	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1253}