cli_test.v

66.4 KB · raw

1module tests23import net4import net.http5import os6import time78const root = @VMODROOT9const binary = os.join_path(root, 'build', 'koh3')1011struct Result {12mut:13	code int14	out  string15	err  string16}1718fn testsuite_begin() {19	os.mkdir_all(os.join_path(root, 'build')) or { panic(err) }20	build := os.execute('v -o ${q(binary)} ${q(os.join_path(root, 'src', 'koh3.v'))}')21	if build.exit_code != 0 {22		panic('could not build koh3: ${build.output}')23	}24}2526fn q(s string) string {27	return "'${s.replace("'", "'\\''")}'"28}2930fn temp_repo(name string) string {31	dir := os.join_path(os.temp_dir(), 'koh3-cli-${name}-${time.now().unix_nano()}')32	os.mkdir_all(dir) or { panic(err) }33	return dir34}3536fn run(repo string, args ...string) Result {37	home := temp_repo('home')38	defer { os.rmdir_all(home) or {} }39	return run_home(repo, home, ...args)40}4142fn run_home(repo string, home string, args ...string) Result {43	stamp := '${os.getpid()}-${time.now().unix_nano()}'44	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')45	out_path := '${base}.out'46	err_path := '${base}.err'47	code_path := '${base}.code'48	mut command := 'HOME=${q(home)} ${q(binary)}'49	for arg in args {50		command += ' ${q(arg)}'51	}52	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'53	result := os.execute(shell)54	if result.exit_code != 0 {55		panic('could not run test command: ${result.output}')56	}57	code := os.read_file(code_path) or { panic(err) }58	out := os.read_file(out_path) or { '' }59	err := os.read_file(err_path) or { '' }60	os.rm(out_path) or {}61	os.rm(err_path) or {}62	os.rm(code_path) or {}63	return Result{64		code: code.int()65		out:  out66		err:  err67	}68}6970fn run_pty_home(repo string, home string, answers []string, args ...string) Result {71	stamp := '${os.getpid()}-${time.now().unix_nano()}'72	transcript := os.join_path(os.temp_dir(), 'koh3-pty-${stamp}.txt')73	script_path := os.join_path(os.temp_dir(), 'koh3-pty-${stamp}.exp')74	defer {75		os.rm(transcript) or {}76		os.rm(script_path) or {}77	}78	mut script := 'log_file -noappend {${transcript}}\nset timeout 20\nspawn -noecho env {HOME=${home}} NO_COLOR=1 {${binary}}'79	for arg in args {80		script += ' {${arg}}'81	}82	script += '\n'83	// Each answer waits for its prompt: typed ahead, it would be flushed when the pager takes the84	// terminal raw. `close` ends a run that is still asking, so `wait` can never hang the suite.85	for answer in answers {86		script += 'expect -re {› \$|message: \$|confirm: \$|\\[y/N\\] \$|q quit}\nsend -- "${answer}\\r"\n'87	}88	script += 'expect eof\ncatch close\nset status [wait]\nexit [lindex $status 3]\n'89	os.write_file(script_path, script) or { panic(err) }90	result := os.execute('cd ${q(repo)} && expect -f ${q(script_path)}')91	return Result{92		code: result.exit_code93		out:  os.read_file(transcript) or { '' }94		err:  result.output95	}96}9798fn init_repo(repo string) {99	r := run(repo, 'init')100	assert r.code == 0101	assert os.exists(os.join_path(repo, '.koh'))102	assert os.exists(os.join_path(repo, '.kohignore'))103}104105fn write(repo string, path string, text string) {106	full := os.join_path(repo, path)107	os.mkdir_all(os.dir(full)) or { panic(err) }108	os.write_file(full, text) or { panic(err) }109}110111fn read_json_has(text string, key string) {112	if !text.contains(key) {113		panic('missing JSON key ${key}: ${text}')114	}115}116117fn test_init_and_usage() {118	dir := temp_repo('init')119	defer { os.rmdir_all(dir) or {} }120	r := run(dir, 'init', '--json')121	assert r.code == 0122	read_json_has(r.out, 'repo')123	read_json_has(r.out, 'ignore_created')124	assert run(dir, 'init').code == 1125	assert run(dir, 'unknown-command').code == 2126	assert run(dir, 'unknown-command').err.contains('unknown command')127	// An agent asking for JSON gets JSON for a usage mistake too, exit 2.128	for args in [['unknown-command', '--json'], ['save', '--json'], ['save', 'x', '--nope', '--json']] {129		r2 := run(dir, ...args)130		assert r2.code == 2131		assert r2.out == ''132		assert r2.err.starts_with('{"error":'), r2.err133	}134}135136// The help screen is commands and plain words: every flag lives in `koh man`.137// this_platform is the platform name for the machine the tests run on, so a138// build test does not depend on which machine that is.139fn this_platform() string {140	machine := os.uname().machine141	arch := if machine in ['arm64', 'aarch64'] { 'aarch64' } else { 'x86_64' }142	return '${os.user_os()}-${arch}'143}144145// `koh build` builds with `koh.build`: the version and platform fill the output146// path, and each artifact is printed with its size.147fn test_build_builds_the_named_platforms() {148	dir := temp_repo('build_ok')149	defer { os.rmdir_all(dir) or {} }150	init_repo(dir)151	host := this_platform()152	write(dir, 'VERSION', '1.2.3\n')153	write(dir, 'koh.build', 'command = mkdir -p out && printf built > out/demo-1.2.3-${host}154output = out/demo-{version}-{platform}155platforms = ${host}156')157	one := run(dir, 'build')158	assert one.code == 0, one.err159	assert one.out.contains('version 1.2.3')160	assert one.out.contains('out/demo-1.2.3-${host}')161	assert os.exists(os.join_path(dir, 'out/demo-1.2.3-${host}'))162163	// --platform picks one, --all takes every platform the file names.164	write(dir, 'koh.build', 'command = mkdir -p out && printf m > out/demo-macos-aarch64 && printf l > out/demo-linux-aarch64165output = out/demo-{platform}166platforms = macos-aarch64, linux-aarch64167')168	all := run(dir, 'build', '--all', '--json')169	assert all.code == 0, all.err170	assert all.out.contains('"platform":"macos-aarch64"')171	assert all.out.contains('"platform":"linux-aarch64"')172	assert os.exists(os.join_path(dir, 'out/demo-linux-aarch64'))173	picked := run(dir, 'build', '--platform', 'linux-aarch64')174	assert picked.code == 0, picked.err175	assert picked.out.contains('out/demo-linux-aarch64')176	assert !picked.out.contains('out/demo-macos-aarch64')177}178179// The item's exit check, as a test: `koh build` builds Koh 3 itself with the180// real toolchain, in a copy, and the binary it produces runs.181// `koh update` refuses a command line that cannot be answered: JSON cannot carry182// the question, and a stray argument is a mistake. Both are settled before any183// source is read, so no network is needed here.184fn test_update_refuses_a_command_line_it_cannot_answer() {185	dir := temp_repo('update_args')186	defer { os.rmdir_all(dir) or {} }187	init_repo(dir)188	json_without_yes := run(dir, 'update', '--json')189	assert json_without_yes.code == 2190	assert json_without_yes.err.contains('needs --yes')191	assert run(dir, 'update', 'extra').code == 2192}193194fn test_build_builds_koh_itself() {195	dir := temp_repo('selfbuild')196	defer { os.rmdir_all(dir) or {} }197	// Only what a build reads: the copy needs no history and no archive.198	for item in ['src', 'vendor', 'docs', 'v.mod', 'VERSION'] {199		os.cp_all(os.join_path(root, item), os.join_path(dir, item), true) or { panic(err) }200	}201	write(dir, 'koh.build', 'command = mkdir -p zig-out/bin && v -o zig-out/bin/koh3 src/koh3.v202output = zig-out/bin/koh3203platforms = ${this_platform()}204')205	init_repo(dir)206	built := run(dir, 'build')207	assert built.code == 0, built.err208	assert built.out.contains('zig-out/bin/koh3')209	fresh := os.join_path(dir, 'zig-out/bin/koh3')210	assert os.exists(fresh)211	version := os.read_file(os.join_path(dir, 'VERSION'))!.trim_space()212	assert os.execute('${q(fresh)} --version').output.trim_space() == 'koh ${version}'213}214215fn test_build_refuses_what_it_cannot_do() {216	dir := temp_repo('build_bad')217	defer { os.rmdir_all(dir) or {} }218	init_repo(dir)219	missing := run(dir, 'build')220	assert missing.code == 1221	assert missing.err.contains('koh.build')222223	write(dir, 'koh.build', 'command = true224output = out/demo225platforms = macos-aarch64226')227	no_version := run(dir, 'build')228	assert no_version.code == 1229	assert no_version.err.contains('VERSION')230231	write(dir, 'VERSION', '1.2.3\n')232	not_listed := run(dir, 'build', '--platform', 'linux-aarch64')233	assert not_listed.code == 1234	assert not_listed.err.contains('does not build for')235236	unknown := run(dir, 'build', '--platform', 'amiga')237	assert unknown.code == 1238	assert unknown.err.contains('amiga')239240	both := run(dir, 'build', '--all', '--platform', 'macos-aarch64')241	assert both.code == 2242	assert both.err.contains('cannot be combined')243244	write(dir, 'koh.build', 'command = true245output = out/demo246platforms = macos-aarch64, amiga247')248	bad_platform := run(dir, 'build')249	assert bad_platform.code == 1250	assert bad_platform.err.contains('amiga')251252	write(dir, 'koh.build', 'command = sh -c \'echo "no toolchain" >&2; exit 1\'253output = out/demo254platforms = ${this_platform()}255')256	failed := run(dir, 'build')257	assert failed.code == 1258	assert failed.err.contains('no toolchain')259}260261fn test_the_help_screen_lists_commands_and_no_flags() {262	dir := temp_repo('help')263	defer { os.rmdir_all(dir) or {} }264	help := run(dir, '--help')265	assert help.code == 0266	names := ['save', 'checkpoint', 'status', 'view', 'diff', 'undo', 'revert', 'load', 'offer',267		'steal']268	for name in names {269		assert help.out.contains('  ${name} '), name270	}271	assert help.out.contains('koh man <command>')272	// No flag text anywhere on the screen.273	assert !help.out.contains('--'), help.out274	lines := help.out.split_into_lines()275	for line in lines {276		assert line.runes().len <= 80, line277	}278	// Each command has its own paragraph, a blank line above it.279	for name in names {280		for i, line in lines {281			if line.starts_with('  ${name} ') {282				assert i > 0 && lines[i - 1] == '', line283			}284		}285	}286	// A bare `koh` keeps its stream and exit code; `-h` shows the same screen.287	bare := run(dir)288	assert bare.code == 2289	assert bare.out == ''290	assert bare.err.contains('koh man <command>')291	short := run(dir, '-h')292	assert short.code == 0293	assert short.out == help.out294}295296// Colour on the screen follows NO_COLOR, as it does everywhere else.297fn test_the_help_screen_has_no_colour_when_it_is_off() {298	dir := temp_repo('help_plain')299	defer { os.rmdir_all(dir) or {} }300	home := temp_repo('help_plain_home')301	defer { os.rmdir_all(home) or {} }302	out_path := os.join_path(os.temp_dir(), 'koh3-help-${os.getpid()}-${time.now().unix_nano()}')303	defer { os.rm(out_path) or {} }304	code := os.system('cd ${q(dir)} && HOME=${q(home)} NO_COLOR=1 ${q(binary)} --help > ${q(out_path)}')305	assert code == 0306	text := os.read_file(out_path) or { panic(err) }307	assert !text.contains('\x1b'), text308	assert text.contains('  save        snapshot your work')309}310311// The binary embeds VERSION while saves bump v.mod; they drifted once.312fn test_version_matches_the_manifest() {313	dir := temp_repo('version')314	defer { os.rmdir_all(dir) or {} }315	version := run(dir, '--version').out.trim_space().all_after('koh ')316	manifest := os.read_file(os.join_path(root, 'v.mod')) or { panic(err) }317	assert manifest.contains("version: '${version}'"), version318}319320fn test_save_checkpoint_and_status() {321	dir := temp_repo('save')322	defer { os.rmdir_all(dir) or {} }323	init_repo(dir)324	write(dir, 'tracked.txt', 'one\n')325	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')326	assert r.code == 0327	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent', 'session',328		'files', 'size_bytes'] {329		read_json_has(r.out, key)330	}331	assert r.out.contains('"message":"first message"')332	assert r.out.contains('"agent":"agent-7"')333	assert r.out.contains('"session":"session-a"')334	assert r.out.contains('"is_checkpoint":false')335	assert run(dir, 'save', 'again').code == 1336	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')337	assert run(dir, 'save').code == 2338	assert run(dir, 'save', 'x', '--bogus').code == 2339	cp := run(dir, 'checkpoint', 'still first', '--json')340	assert cp.code == 0341	assert cp.out.contains('"is_checkpoint":true')342	assert cp.out.contains('"parent":')343	clean := run(dir, 'status')344	assert clean.code == 0345	assert clean.out.contains('no changes')346	write(dir, 'tracked.txt', 'two\n')347	write(dir, 'new.txt', 'new\n')348	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }349	write(dir, '.kohignore', '*.log\n')350	status := run(dir, 'status')351	assert status.code == 0352	assert status.out.contains('+')353	assert status.out.contains('~') || status.out.contains('-')354	assert status.out.contains('added')355	js := run(dir, 'status', '--json')356	assert js.code == 0357	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed',358		'saves', 'size_bytes', 'head_flagged'] {359		read_json_has(js.out, key)360	}361	assert js.out.contains('"ignore_changed":true')362	// What the shell prompt shows: saves on the line, the .koh size, the flag.363	assert js.out.contains('"saves":2')364	assert js.out.contains('"size_bytes":${os.file_size(os.join_path(dir, '.koh'))}')365	assert js.out.contains('"head_flagged":false')366	head := js.out.all_after('"head_id":"').all_before('"')367	assert run(dir, 'flag', head, '--reason', 'bad').code == 0368	assert run(dir, 'status', '--json').out.contains('"head_flagged":true')369}370371fn test_status_requires_repo_and_ignore_rules() {372	dir := temp_repo('status')373	defer { os.rmdir_all(dir) or {} }374	assert run(dir, 'status').code == 1375	init_repo(dir)376	write(dir, '.kohignore', '*.log\nbuild/\n')377	write(dir, 'keep.txt', 'keep\n')378	write(dir, 'ignored.log', 'ignore\n')379	write(dir, 'build/output.txt', 'ignore\n')380	assert run(dir, 'save', 'keep').code == 0381	assert run(dir, 'status').out.contains('no changes')382	assert !run(dir, 'status').out.contains('ignored.log')383	assert !run(dir, 'status').out.contains('build/output.txt')384	assert !run(dir, 'status').out.contains('LOG.md')385}386387fn test_status_and_save_report_unsafe_names_without_refusing_the_save() {388	dir := temp_repo('unsafe-names')389	defer { os.rmdir_all(dir) or {} }390	init_repo(dir)391	write(dir, 'safe.txt', 'safe\n')392	assert run(dir, 'save', 'safe').code == 0393	os.write_file('${dir}/bad\\name.txt', 'bad\n') or { panic(err) }394	os.write_file('${dir}/Icon\r', 'icon\n') or { panic(err) }395396	status := run(dir, 'status', '--json')397	assert status.code == 0398	assert status.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), status.out399	saved := run(dir, 'checkpoint', 'unsafe names', '--json')400	assert saved.code == 0401	assert saved.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), saved.out402}403404// LOG.md is a convenience written after the save lands. If it cannot be405// written, the save still happened, and an agent that retried on a failure406// would only be told nothing had changed.407fn test_a_save_succeeds_when_log_md_cannot_be_written() {408	dir := temp_repo('logmd')409	defer { os.rmdir_all(dir) or {} }410	init_repo(dir)411	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }412	write(dir, 'a.txt', 'one\n')413	r := run(dir, 'save', 'first', '--json')414	assert r.code == 0415	assert r.out.starts_with('{')416	assert r.err.contains('LOG.md')417	assert run(dir, 'view', '--json').out.contains('"message":"first"')418}419420// A folder of ignored files can sit where a restored file should go. Koh421// never touches ignored files, so the restore must stop and say so, not drop422// the file inside the folder under a temporary name.423fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {424	dir := temp_repo('dir-in-way')425	defer { os.rmdir_all(dir) or {} }426	init_repo(dir)427	write(dir, 'out', 'a file\n')428	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]429	os.rm(os.join_path(dir, 'out')) or { panic(err) }430	write(dir, 'out/build.log', 'ignored\n')431	assert run(dir, 'save', 'out is gone').code == 0432	r := run(dir, 'load', first, '--yes')433	assert r.code == 1434	assert r.err.contains('out')435	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']436}437438// Koh never follows a symlink, so a folder replaced by a link to somewhere439// else is not the repo's to write into: restoring through it would overwrite440// files outside the repo. The refusal comes before anything is recorded.441fn test_a_restore_never_writes_through_a_symlinked_folder() {442	dir := temp_repo('link-in-way')443	outside := temp_repo('link-target')444	defer {445		os.rmdir_all(dir) or {}446		os.rmdir_all(outside) or {}447	}448	init_repo(dir)449	write(dir, 'docs/a.md', 'saved\n')450	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]451	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }452	write(outside, 'a.md', 'precious\n')453	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }454	assert run(dir, 'save', 'docs is a link now').code == 0455	head := run(dir, 'status', '--json').out456	r := run(dir, 'load', first, '--yes')457	assert r.code == 1458	assert r.err.contains('docs')459	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'460	assert run(dir, 'status', '--json').out == head461}462463// A restore records its save first, then writes files. When the writing stops464// part way, the half-written tree is not somebody's work: saving it would465// record (and offer) a tree that undoes changes nobody asked to undo. Every466// command that would build on it points at revert, which finishes the job.467fn test_a_restore_cut_short_points_at_revert() {468	dir := temp_repo('cut-short')469	defer {470		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}471		os.rmdir_all(dir) or {}472	}473	init_repo(dir)474	write(dir, 'zero', '0\n')475	assert run(dir, 'save', 'zero').code == 0476	write(dir, 'a.txt', 'v1\n')477	write(dir, 'zz/f', 'v1\n')478	assert run(dir, 'save', 'first').code == 0479	write(dir, 'a.txt', 'v2\n')480	write(dir, 'zz/f', 'v2\n')481	assert run(dir, 'save', 'second').code == 0482	// a.txt is written, then the read-only folder stops the restore: the483	// tree is genuinely half one save and half the other.484	os.chmod(os.join_path(dir, 'zz'), 0o555)!485	stopped := run(dir, 'undo', '--yes')486	assert stopped.code == 1487	assert stopped.err.contains('koh revert')488	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'489	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'490	// Even a status that cannot read the tree says what happened.491	os.chmod(os.join_path(dir, 'zz'), 0o000)!492	assert run(dir, 'status').err.contains('koh revert')493	os.chmod(os.join_path(dir, 'zz'), 0o755)!494495	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')496	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {497		r := run(dir, ...args)498		assert r.code == 1499		assert r.err.contains('koh revert')500	}501	assert run(dir, 'revert', '--yes').code == 0502	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'503	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'504	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')505	write(dir, 'a.txt', 'v3\n')506	assert run(dir, 'save', 'carry on').code == 0507}508509// Doctor clears peek folders left from earlier days, never one somebody may510// be reading right now.511fn test_doctor_sweeps_only_old_peek_folders() {512	dir := temp_repo('peek-sweep')513	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in514	// the real temp directory under names no save could have.515	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')516	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')517	defer {518		os.rmdir_all(dir) or {}519		os.rmdir_all(fresh) or {}520		os.rmdir_all(old) or {}521	}522	init_repo(dir)523	write(dir, 'a.txt', 'one\n')524	assert run(dir, 'save', 'one').code == 0525	os.mkdir_all(fresh) or { panic(err) }526	os.mkdir_all(old) or { panic(err) }527	two_days_ago := time.now().unix() - 2 * 86400528	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }529	assert run(dir, 'doctor', '--json').code == 0530	assert os.exists(fresh)531	assert !os.exists(old)532}533534// A file saved long ago and ignored since holds work no save has. Loading the535// old save must not write over it; the document says a restore never touches536// ignored files.537fn test_a_restore_never_overwrites_an_ignored_file() {538	dir := temp_repo('ignored-restore')539	defer { os.rmdir_all(dir) or {} }540	init_repo(dir)541	write(dir, '.env', 'KEY=saved long ago\n')542	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]543	write(dir, '.kohignore', '.env\n')544	assert run(dir, 'save', 'ignore env').code == 0545	write(dir, '.env', 'KEY=never saved\n')546	assert run(dir, 'load', first, '--yes').code == 0547	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'548549	// Where the ignored file is missing, the restore still brings it back.550	other := temp_repo('ignored-restore-missing')551	defer { os.rmdir_all(other) or {} }552	init_repo(other)553	write(other, '.env', 'KEY=saved long ago\n')554	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]555	write(other, '.kohignore', '.env\n')556	assert run(other, 'save', 'ignore env').code == 0557	os.rm(os.join_path(other, '.env')) or { panic(err) }558	assert run(other, 'load', again, '--yes').code == 0559	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'560}561562// A going-back preview lists paths only. Running diff(1) per file to draw it563// cost 27 s for 5,000 changed files, so it must not run diff at all.564fn test_a_going_back_preview_does_not_run_diff() {565	dir := temp_repo('preview-nodiff')566	home := temp_repo('preview-nodiff-home')567	defer {568		os.rmdir_all(dir) or {}569		os.rmdir_all(home) or {}570	}571	init_repo(dir)572	write(dir, 'a.txt', 'one\n')573	assert run_home(dir, home, 'save', 'one').code == 0574	write(dir, 'a.txt', 'two\n')575	assert run_home(dir, home, 'save', 'two').code == 0576	fake := os.join_path(home, 'bin')577	os.mkdir_all(fake) or { panic(err) }578	marker := os.join_path(home, 'diff-ran')579	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {580		panic(err)581	}582	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }583	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0584	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'585	assert !os.exists(marker)586}587588// A restore rewrites only what differs. Rewriting every file resets every589// mtime, so the next status has to hash the whole tree again.590fn test_a_restore_leaves_unchanged_files_alone() {591	dir := temp_repo('restore-skip')592	defer { os.rmdir_all(dir) or {} }593	init_repo(dir)594	write(dir, 'a.txt', 'one\n')595	write(dir, 'same.txt', 'never changes\n')596	assert run(dir, 'save', 'one').code == 0597	write(dir, 'a.txt', 'two\n')598	assert run(dir, 'save', 'two').code == 0599	long_ago := i64(1700000000)600	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }601	assert run(dir, 'undo', '--yes').code == 0602	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'603	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago604}605606// `save` records the executable bit, so `status` has to see it too, or a607// chmod would be invisible until it turned up in a save.608fn test_status_sees_an_executable_bit_change() {609	dir := temp_repo('chmod')610	defer { os.rmdir_all(dir) or {} }611	init_repo(dir)612	write(dir, 'run.sh', 'echo hi\n')613	assert run(dir, 'save', 'script').code == 0614	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }615	status := run(dir, 'status', '--json')616	assert status.out.contains('"dirty":true')617	assert status.out.contains('"modified":["run.sh"]')618}619620fn test_view_and_diff() {621	dir := temp_repo('history')622	defer { os.rmdir_all(dir) or {} }623	init_repo(dir)624	write(dir, 'a.txt', 'one\n')625	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')626	id1 := first.out.all_after('"id":"')[..12]627	write(dir, 'a.txt', 'two\n')628	second := run(dir, 'save', 'two', '--session', 'beta', '--json')629	id2 := second.out.all_after('"id":"')[..12]630	cp := run(dir, 'checkpoint', 'checkpoint', '--json')631	assert cp.code == 0632	printed := run(dir, 'view')633	assert printed.code == 0634	assert printed.out.contains('▸')635	assert printed.out.contains('◐')636	lj := run(dir, 'view', '--json')637	assert lj.code == 0638	assert lj.out.contains('"head_id"')639	assert lj.out.contains('"saves"')640	assert run(dir, 'view', '--since', 'today').out.contains('two')641	session := run(dir, 'view', '--session', 'alpha')642	assert session.out.contains('one')643	assert !session.out.contains('two')644	assert run(dir, 'view', '--since', '9999-01-01').out.contains('no saves in that range')645	write(dir, 'a.txt', 'three\n')646	d := run(dir, 'diff')647	assert d.code == 0648	assert d.out.contains('--- a/')649	assert d.out.contains('+++ b/')650	assert run(dir, 'diff', id1).code == 0651	assert run(dir, 'diff', id1, id2).code == 0652	dj := run(dir, 'diff', '--json')653	assert dj.code == 0654	assert dj.out.contains('"from"')655	assert dj.out.contains('"to"')656	assert dj.out.contains('"files"')657	assert dj.out.contains('"change":"modified"')658	assert run(dir, 'diff', 'not-a-real-id').code == 1659	assert run(dir, 'diff', id1, id2, 'third').code == 1660	write(dir, 'blob.bin', '\x00\x01\x02')661	diff_binary := run(dir, 'diff', '--json')662	assert diff_binary.out.contains('"binary":true')663	assert diff_binary.out.contains('Binary files differ')664}665666fn test_undo_revert_and_load() {667	dir := temp_repo('restore')668	defer { os.rmdir_all(dir) or {} }669	init_repo(dir)670	write(dir, 'a.txt', 'one\n')671	one := run(dir, 'save', 'one', '--json').out672	id1 := one.all_after('"id":"')[..12]673	write(dir, 'a.txt', 'two\n')674	write(dir, 'gone.txt', 'gone\n')675	second := run(dir, 'save', 'two', '--json').out676	id2 := second.all_after('"id":"')[..12]677	write(dir, 'a.txt', 'three\n')678	third := run(dir, 'save', 'three', '--json').out679	id3 := third.all_after('"id":"')[..12]680	// Unsaved work — here a file never saved — blocks every going-back but681	// revert, as in Koh 2: a restore must never overwrite what only the disk has.682	write(dir, 'never.txt', 'keep me\n')683	view_before := run(dir, 'view').out684	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {685		blocked := run(dir, ...args)686		assert blocked.code == 1687		assert blocked.err.contains('unsaved changes')688	}689	assert run(dir, 'view').out == view_before690	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }691	write(dir, 'a.txt', 'edited, never saved\n')692	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')693	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'694	write(dir, 'a.txt', 'three\n')695	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }696	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')697	write(dir, 'gone.txt', 'gone\n')698	undo := run(dir, 'undo', '--yes', '--json')699	assert undo.code == 0700	if !undo.out.contains(id2) {701		panic('undo JSON did not name ${id2}: ${undo.out}')702	}703	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'704	assert os.exists(os.join_path(dir, 'gone.txt'))705	assert run(dir, 'load', id3, '--yes').code == 0706	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'707	assert run(dir, 'undo', '2', '--yes').code == 0708	assert run(dir, 'load', id2, '--yes').code == 0709	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')710	write(dir, 'a.txt', 'dirty\n')711	before := run(dir, 'view')712	refuse := run(dir, 'revert')713	assert refuse.code == 1714	assert refuse.err.contains('needs --yes when not interactive')715	assert run(dir, 'view').out == before.out716	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'717	write(dir, 'untracked.txt', 'remove\n')718	rv := run(dir, 'revert', '--yes', '--json')719	assert rv.code == 0720	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'721	assert !os.exists(os.join_path(dir, 'untracked.txt'))722	// The way back to the discarded work is named, not left to be found.723	kept := rv.out.all_after('"checkpoint":"')[..12]724	assert run(dir, 'load', kept, '--yes').code == 0725	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'726	assert os.read_file(os.join_path(dir, 'untracked.txt'))! == 'remove\n'727	write(dir, 'a.txt', 'dirty again\n')728	assert run(dir, 'revert', '--yes').out.contains('koh load ')729	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')730	assert run(dir, 'load', '--checkpoint', '--yes').code == 0731	assert run(dir, 'load', id2, '--json').code == 1732	assert run(dir, 'load', id2, '--json').err.contains('error')733	assert run(dir, 'load').code == 2734	assert run(dir, 'load', 'unknown-id', '--yes').code == 1735}736737fn test_flag_and_flagged_view() {738	dir := temp_repo('flag')739	defer { os.rmdir_all(dir) or {} }740	init_repo(dir)741	write(dir, 'flag.txt', 'one\n')742	saved := run(dir, 'save', 'flag me', '--json')743	id := saved.out.all_after('"id":"')[..12]744	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')745	assert flagged.code == 0746	assert flagged.out.contains('"flagged":true')747	assert flagged.out.contains('"reason":"unsafe"')748	list := run(dir, 'flag', '--json')749	assert list.code == 0750	assert list.out.contains(id)751	assert list.out.contains('unsafe')752	assert run(dir, 'view').out.contains('⚑')753	assert run(dir, 'flag', '--clear', id).code == 0754	assert run(dir, 'flag').out.contains('nothing is flagged')755	assert run(dir, 'flag', 'unknown-id').code == 1756	assert run(dir, 'flag').code == 0757}758759fn test_pluck_forward_reverse_dry_run_and_conflict() {760	dir := temp_repo('pluck')761	defer { os.rmdir_all(dir) or {} }762	init_repo(dir)763	write(dir, 'a.txt', 'one\n')764	first := run(dir, 'save', 'one', '--json').out765	id1 := first.all_after('"id":"')[..12]766	write(dir, 'a.txt', 'two\n')767	second := run(dir, 'save', 'two', '--json').out768	id2 := second.all_after('"id":"')[..12]769	assert run(dir, 'load', id1, '--yes').code == 0770	dry := run(dir, 'pluck', id2, '--dry-run')771	assert dry.code == 0772	assert dry.out.contains('a.txt')773	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'774	assert run(dir, 'pluck', id2, '--yes').code == 0775	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'776	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0777	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'778	write(dir, 'a.txt', 'different\n')779	assert run(dir, 'pluck', id2, '--dry-run').code == 1780	assert run(dir, 'save', 'different').code == 0781	conflict := run(dir, 'pluck', id2, '--yes')782	assert conflict.code == 1783	assert conflict.err.contains('a.txt')784	assert run(dir, 'pluck').code == 2785	assert run(dir, 'pluck', 'unknown-id').code == 1786}787788fn test_peek_and_doctor() {789	dir := temp_repo('peek-doctor')790	defer { os.rmdir_all(dir) or {} }791	init_repo(dir)792	write(dir, 'peek.txt', 'peek me\n')793	assert run(dir, 'save', 'peekable').code == 0794	id := run(dir, 'view', '--json').out.all_after('"id":"')[..12]795	before_view := run(dir, 'view', '--json').out796	peek := run(dir, 'peek', id, '--json')797	assert peek.code == 0798	peek_path := peek.out.all_after('"path":"').before('"')799	assert peek.out.contains('"id":"${id}"')800	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'801	assert run(dir, 'status').out.contains('no changes')802	assert run(dir, 'view', '--json').out == before_view803	assert run(dir, 'peek').code == 2804	assert run(dir, 'peek', 'unknown-id').code == 1805	backup := os.join_path(dir, 'doctor.backup')806	healthy := run(dir, 'doctor')807	assert healthy.code == 0808	assert healthy.out.contains('is sound')809	report := run(dir, 'doctor', '--json')810	assert report.code == 0811	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',812		'backup'] {813		read_json_has(report.out, key)814	}815	backed := run(dir, 'doctor', '--backup', backup)816	assert backed.code == 0817	assert os.exists(backup)818	assert backed.out.contains(backup)819	assert run(dir, 'doctor', '--backup', backup).code == 1820	assert run(dir, 'peek', id, '--json').code == 0821	// A peek made today is left for whoever is reading it.822	kept := run(dir, 'doctor', '--json')823	assert kept.code == 0824	assert os.exists(peek_path)825	os.rmdir_all(peek_path) or {}826}827828fn test_strip_refuses_without_terminal() {829	dir := temp_repo('strip')830	defer { os.rmdir_all(dir) or {} }831	init_repo(dir)832	write(dir, 'secret.txt', 'keep\n')833	assert run(dir, 'save', 'secret').code == 0834	before_view := run(dir, 'view', '--json').out835	refused := run(dir, 'strip', 'secret.txt')836	assert refused.code == 1837	assert refused.err.contains('needs a terminal')838	assert run(dir, 'view', '--json').out == before_view839	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'840	assert run(dir, 'view', '--json').out.contains('secret')841}842843// A whole-history strip bans the path: `.kohignore` names it, once, and the file left on disk844// is never unsaved work or part of a save again.845fn test_strip_adds_the_path_to_kohignore_and_it_stays_out() {846	dir := temp_repo('strip-ignore')847	home := temp_repo('strip-ignore-home')848	defer { os.rmdir_all(dir) or {} }849	defer { os.rmdir_all(home) or {} }850	init_repo(dir)851	write(dir, 'secret.txt', 'leaked\n')852	write(dir, 'keep.txt', 'fine\n')853	assert run_home(dir, home, 'save', 'leak').code == 0854	stripped := run_pty_home(dir, home, ['y', 'secret.txt'], 'strip', 'secret.txt')855	assert stripped.code == 0, stripped.out856	assert stripped.out.contains('added /secret.txt to .kohignore')857	ignore_path := os.join_path(dir, '.kohignore')858	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1859	assert run_home(dir, home, 'save', 'ignore the stripped secret').code == 0860	write(dir, 'secret.txt', 'leaked again\n')861	assert run_home(dir, home, 'status', '--json').out.contains('"dirty":false')862	// Running the strip again (with no remote, it stays pending) adds no second line.863	again := run_pty_home(dir, home, [], 'strip', 'secret.txt')864	assert again.code == 0, again.out865	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1866}867868// `koh view` is the one way into the history: the whole line by default,869// checkpoints alone with the flag, and the two lists never overlap.870fn test_view_shows_the_line_and_checkpoints_apart() {871	dir := temp_repo('view')872	defer { os.rmdir_all(dir) or {} }873	init_repo(dir)874	write(dir, 'view.txt', 'one\n')875	assert run(dir, 'save', 'plain save').code == 0876	assert run(dir, 'checkpoint', 'checkpoint save').code == 0877	line := run(dir, 'view')878	assert line.code == 0879	assert line.out.contains('plain save')880	assert line.out.contains('checkpoint save')881	checkpoints := run(dir, 'view', '--checkpoints')882	assert checkpoints.code == 0883	assert checkpoints.out.contains('checkpoint save')884	assert !checkpoints.out.contains('plain save')885	json_line := run(dir, 'view', '--json')886	assert json_line.code == 0887	assert json_line.out.contains('"is_checkpoint":false')888	assert json_line.out.contains('"is_checkpoint":true')889	json_checkpoints := run(dir, 'view', '--checkpoints', '--json')890	assert json_checkpoints.code == 0891	assert json_checkpoints.out.contains('"is_checkpoint":true')892	assert !json_checkpoints.out.contains('"is_checkpoint":false')893	// `view` takes no arguments, so a stray one is a usage error, and the names894	// it replaced are gone rather than hidden: the diagnostic says which.895	assert run(dir, 'view', 'extra').code == 2896	for gone in ['log', 'saves', 'checkpoints'] {897		refused := run(dir, gone)898		assert refused.code == 2899		assert refused.err.contains('unknown command "${gone}"')900	}901	// Every save is on the whole line exactly once, as the JSON says.902	assert line.out.split_into_lines().len == json_line.out.count('"id":"')903}904905fn test_remote_configuration_is_isolated_and_atomic() {906	dir := temp_repo('remote')907	home := temp_repo('remote-home')908	defer {909		os.rmdir_all(dir) or {}910		os.rmdir_all(home) or {}911	}912	empty := run_home(dir, home, 'remote', '--json')913	assert empty.code == 0914	assert empty.out.contains('"configured":false')915	target := os.join_path(home, 'remote-store')916	set := run_home(dir, home, 'remote', 'folder', target)917	assert set.code == 0918	assert os.is_dir(target)919	state := run_home(dir, home, 'remote', '--json')920	assert state.code == 0921	assert state.out.contains('"kind":"folder"')922	assert state.out.contains(target)923	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1924	assert run_home(dir, home, 'remote', '--json').out.contains(target)925	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')926	assert run_home(dir, home, 'remote', '--forget').code == 0927	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')928}929930// The files under ~/.config/koh can be written by hand instead of by931// `koh remote`, and are then read the same way.932fn test_remote_written_by_hand() {933	dir := temp_repo('remote-by-hand')934	home := temp_repo('remote-by-hand-home')935	defer {936		os.rmdir_all(dir) or {}937		os.rmdir_all(home) or {}938	}939	config := os.join_path(home, '.config', 'koh')940	os.mkdir_all(config) or { panic(err) }941	target := os.join_path(home, 'remote-store')942	os.mkdir_all(target) or { panic(err) }943	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {944		panic(err)945	}946	assert run_home(dir, home, 'init').code == 0947	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }948	assert run_home(dir, home, 'save', 'first').code == 0949	offered := run_home(dir, home, 'offer', '--json')950	assert offered.code == 0951	assert offered.out.contains('"head"')952953	// Keys anyone else can read are refused before they are ever sent.954	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {955		panic(err)956	}957	credentials := os.join_path(config, 'credentials')958	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }959	os.chmod(credentials, 0o644) or { panic(err) }960	loose := run_home(dir, home, 'offer')961	assert loose.code == 1962	assert loose.err.contains('chmod 600')963964	// A setting koh cannot read is replaced by setting the remote again.965	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }966	unreadable := run_home(dir, home, 'offer')967	assert unreadable.code == 1968	assert unreadable.err.contains('not readable')969	assert run_home(dir, home, 'remote', 'folder', target).code == 0970	assert run_home(dir, home, 'offer').code == 0971}972973// A stolen repo belongs to the repo it was stolen from, whatever its folder is974// called later: renaming it must not start a second repo on the remote.975fn test_a_renamed_stolen_repo_keeps_offering_to_its_repo() {976	syncroot := temp_repo('rename-steal')977	home := temp_repo('rename-steal-home')978	defer {979		os.rmdir_all(syncroot) or {}980		os.rmdir_all(home) or {}981	}982	remote := os.join_path(syncroot, 'remote')983	a := os.join_path(syncroot, 'A', 'proj')984	b_parent := os.join_path(syncroot, 'B')985	os.mkdir_all(a) or { panic(err) }986	os.mkdir_all(b_parent) or { panic(err) }987	init_repo(a)988	write(a, 'a.txt', 'from A\n')989	assert run_home(a, home, 'remote', 'folder', remote).code == 0990	assert run_home(a, home, 'save', 'A first').code == 0991	assert run_home(b_parent, home, 'steal', 'proj').code == 0992	renamed := os.join_path(b_parent, 'renamed')993	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }994	write(renamed, 'b.txt', 'from B\n')995	assert run_home(renamed, home, 'save', 'B first').code == 0996	assert !os.exists(os.join_path(remote, 'renamed'))997	assert run_home(a, home, 'steal').code == 0998	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'999}10001001// A damaged object on the remote stops a steal, names the object, and leaves1002// no half-made folder that would make the retry refuse.1003fn test_steal_of_a_damaged_remote_leaves_nothing() {1004	syncroot := temp_repo('damaged')1005	home := temp_repo('damaged-home')1006	defer {1007		os.rmdir_all(syncroot) or {}1008		os.rmdir_all(home) or {}1009	}1010	remote := os.join_path(syncroot, 'remote')1011	a := os.join_path(syncroot, 'A', 'proj')1012	b_parent := os.join_path(syncroot, 'B')1013	os.mkdir_all(a) or { panic(err) }1014	os.mkdir_all(b_parent) or { panic(err) }1015	init_repo(a)1016	write(a, 'a.txt', 'from A\n')1017	assert run_home(a, home, 'remote', 'folder', remote).code == 01018	assert run_home(a, home, 'save', 'A first').code == 01019	objects := os.join_path(remote, 'proj', 'objects')1020	for name in os.ls(objects) or { panic(err) } {1021		os.chmod(os.join_path(objects, name), 0o644) or {}1022		os.write_file(os.join_path(objects, name), 'junk') or { panic(err) }1023	}1024	stolen := run_home(b_parent, home, 'steal', 'proj')1025	assert stolen.code == 11026	assert stolen.err.contains('is damaged')1027	assert !os.exists(os.join_path(b_parent, 'proj'))1028}10291030fn test_steal_drops_crafted_unsafe_paths_and_lands_the_rest() {1031	syncroot := temp_repo('unsafe-remote')1032	home := temp_repo('unsafe-remote-home')1033	defer {1034		os.rmdir_all(syncroot) or {}1035		os.rmdir_all(home) or {}1036	}1037	remote := os.join_path(syncroot, 'remote')1038	a := os.join_path(syncroot, 'A', 'proj')1039	b_parent := os.join_path(syncroot, 'B')1040	os.mkdir_all(a) or { panic(err) }1041	os.mkdir_all(b_parent) or { panic(err) }1042	init_repo(a)1043	write(a, 'safe.txt', 'safe\n')1044	assert run_home(a, home, 'remote', 'folder', remote).code == 01045	id := run_home(a, home, 'save', 'crafted', '--json').out.all_after('"id":"')[..12]1046	assert run_home(a, home, 'offer').code == 01047	record_path := os.join_path(remote, 'proj', 'saves', id)1048	record := os.read_file(record_path) or { panic(err) }1049	path_at := record.index('"path":"safe.txt"') or { panic('safe path missing from ${record}') }1050	file_start := record[..path_at].last_index('{') or { panic('safe file start missing') }1051	file_end := path_at + (record[path_at..].index('}') or { panic('safe file end missing') }) + 11052	file := record[file_start..file_end]1053	mut files := [file]1054	for path in ['../outside.txt', '/etc/koh-test', 'a/../../outside.txt', 'bad\\\\name',1055		'control\\rname'] {1056		files << file.replace('safe.txt', path)1057	}1058	os.write_file(record_path, record[..file_start] + files.join(',') + record[file_end..]) or {1059		panic(err)1060	}10611062	stolen := run_home(b_parent, home, 'steal', 'proj')1063	assert stolen.code == 0, stolen.err1064	assert os.read_file(os.join_path(b_parent, 'proj', 'safe.txt'))! == 'safe\n'1065	assert !os.exists(os.join_path(b_parent, 'outside.txt'))1066	assert !os.exists(os.join_path(b_parent, 'proj', 'bad', 'name'))1067	assert !os.exists('${b_parent}/proj/control\rname')1068}10691070fn test_offer_steal_folder_remote() {1071	syncroot := temp_repo('sync')1072	home := temp_repo('sync-home')1073	defer {1074		os.rmdir_all(syncroot) or {}1075		os.rmdir_all(home) or {}1076	}1077	remote := os.join_path(syncroot, 'remote')1078	a := os.join_path(syncroot, 'A', 'proj')1079	b_parent := os.join_path(syncroot, 'B')1080	os.mkdir_all(a) or { panic(err) }1081	os.mkdir_all(b_parent) or { panic(err) }1082	init_repo(a)1083	write(a, 'a.txt', 'from A\n')1084	assert run_home(a, home, 'remote', 'folder', remote).code == 01085	assert run_home(a, home, 'save', 'A first').code == 01086	stolen := run_home(b_parent, home, 'steal', 'proj')1087	assert stolen.code == 01088	b := os.join_path(b_parent, 'proj')1089	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'1090	write(b, 'b.txt', 'from B\n')1091	assert run_home(b, home, 'save', 'B first').code == 01092	write(a, 'a2.txt', 'second\n')1093	assert run_home(a, home, 'save', 'A second').code == 01094	assert run_home(a, home, 'steal').code == 01095	assert os.exists(os.join_path(a, 'b.txt'))1096	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')1097	write(a, 'clash.txt', 'base\n')1098	assert run_home(a, home, 'save', 'clash base').code == 01099	assert run_home(b, home, 'steal').code == 01100	write(a, 'clash.txt', 'A version\n')1101	assert run_home(a, home, 'save', 'A clash').code == 01102	write(b, 'clash.txt', 'B version\n')1103	assert run_home(b, home, 'save', 'B clash').code == 01104	refused := run_home(b, home, 'steal')1105	assert refused.code == 11106	assert refused.err.contains('--mine') || refused.err.contains('--theirs')1107	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1108	theirs := run_home(b, home, 'steal', '--theirs', '--json')1109	assert theirs.code == 01110	// The pre-combine tree is off the line now; the way back must be named,1111	// or an agent without the history view cannot find it.1112	assert theirs.out.contains('"previous_head":"${b_head}"')1113	assert theirs.out.contains('"kept_versions":["clash.txt:${b_head}"]')1114	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1115	assert run_home(b, home, 'load', b_head, '--yes').code == 01116	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'1117	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 01118	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1119	write(a, 'clash.txt', 'A second\n')1120	assert run_home(a, home, 'save', 'A second clash').code == 01121	write(b, 'clash.txt', 'B second\n')1122	assert run_home(b, home, 'save', 'B second clash').code == 01123	assert run_home(b, home, 'steal', '--mine').code == 01124	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'1125	assert run_home(b, home, 'view').out.contains('combine: kept mine for')1126}11271128fn test_guided_steal_walks_the_terminal_and_can_cancel() {1129	syncroot := temp_repo('guided-steal')1130	home := temp_repo('guided-steal-home')1131	defer {1132		os.rmdir_all(syncroot) or {}1133		os.rmdir_all(home) or {}1134	}1135	remote := os.join_path(syncroot, 'remote')1136	a := os.join_path(syncroot, 'A', 'proj')1137	b_parent := os.join_path(syncroot, 'B')1138	os.mkdir_all(a) or { panic(err) }1139	os.mkdir_all(b_parent) or { panic(err) }1140	init_repo(a)1141	write(a, 'clash.txt', 'base\n')1142	write(a, 'other.txt', 'base\n')1143	write(a, 'same.txt', 'base\n')1144	write(a, 'remote-only.txt', 'base\n')1145	write(a, 'local-only.txt', 'base\n')1146	assert run_home(a, home, 'remote', 'folder', remote).code == 01147	assert run_home(a, home, 'save', 'base').code == 01148	assert run_home(b_parent, home, 'steal', 'proj').code == 01149	b := os.join_path(b_parent, 'proj')11501151	write(b, 'dirty.txt', 'mine\n')1152	before := run_home(b, home, 'status', '--json').out1153	quit := run_pty_home(b, home, ['q'], 'steal')1154	assert quit.out.contains('steal proj')1155	assert quit.out.contains('you have 1 unsaved file')1156	assert quit.out.contains('dirty.txt')1157	assert run_home(b, home, 'status', '--json').out == before1158	// A save needs a message; an empty one stops, says so, and saves nothing.1159	unsaid := run_pty_home(b, home, ['s', ''], 'steal')1160	assert unsaid.code == 11161	assert unsaid.out.contains('no message — nothing was saved')1162	assert run_home(b, home, 'status', '--json').out == before1163	checkpoint := run_pty_home(b, home, ['c'], 'steal')1164	assert checkpoint.code == 0, checkpoint.err1165	assert run_home(b, home, 'view', '--checkpoints').out.contains('before steal')11661167	assert run_home(a, home, 'steal').code == 01168	write(a, 'forward.txt', 'new\n')1169	assert run_home(a, home, 'save', 'fast forward').code == 01170	forward := run_pty_home(b, home, []string{}, 'steal')1171	assert forward.out.contains('proj is up to date · 1 new save')1172	assert forward.out.split_into_lines().filter(it.trim_space() != '').len == 11173	write(a, 'clash.txt', 'remote\n')1174	write(a, 'other.txt', 'remote\n')1175	write(a, 'same.txt', 'identical\n')1176	write(a, 'remote-only.txt', 'remote\n')1177	assert run_home(a, home, 'save', 'remote change').code == 01178	write(b, 'clash.txt', 'mine\n')1179	write(b, 'other.txt', 'mine\n')1180	write(b, 'same.txt', 'identical\n')1181	write(b, 'local-only.txt', 'mine\n')1182	assert run_home(b, home, 'save', 'local change').code == 01183	local_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1184	// `d` opens both changes in the pager, which Enter leaves; `?` explains the two sides.1185	cancel := run_pty_home(b, home, ['d', '', '?', 'm', 'b', 't', 't', 'n'], 'steal')1186	assert cancel.out.contains('your changes')1187	assert cancel.out.contains('remote changes')1188	assert cancel.out.contains('Nothing is lost either way')1189	// The shared save's age, relative: seconds old here, so `now` unless the machine is slow.1190	since := cancel.out.split_into_lines().filter(it.contains('both moved since'))1191	assert since.len == 11192	assert since[0].trim_space().ends_with(' · now') || since[0].trim_space().ends_with(' ago'), since[0]1193	assert cancel.out.contains('5 files changed')1194	assert cancel.out.contains('2 combine by themselves')1195	assert cancel.out.contains('1 changed the same way')1196	assert cancel.out.contains('2 need you')1197	assert cancel.out.contains('ready to combine')1198	assert run_home(b, home, 'status', '--json').out.contains('"head_id":"${local_head}"')1199	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'mine\n'12001201	done := run_pty_home(b, home, ['y'], 'steal', '--theirs')1202	assert done.out.contains('combined · offered to proj')1203	assert done.out.contains('took theirs: clash.txt · other.txt')1204	assert !done.out.contains('kept mine')1205	assert done.out.contains('to undo all of it: koh load ${local_head}')1206	assert done.out.contains('your clash.txt is in ${local_head}')1207	assert !done.out.contains('\x1b')1208	for line in done.out.split_into_lines() {1209		assert line.runes().len <= 80, line1210	}1211}12121213// A steal brings in the whole history, flags included; both output forms must1214// say which saves came in flagged, and why.1215fn test_a_steal_reports_flagged_saves() {1216	syncroot := temp_repo('steal-flags')1217	home := temp_repo('steal-flags-home')1218	defer {1219		os.rmdir_all(syncroot) or {}1220		os.rmdir_all(home) or {}1221	}1222	a := os.join_path(syncroot, 'A', 'proj')1223	os.mkdir_all(a) or { panic(err) }1224	init_repo(a)1225	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 01226	write(a, 'a.txt', 'one\n')1227	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]1228	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 01229	assert run_home(a, home, 'offer').code == 01230	for name in ['B', 'C'] {1231		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }1232	}1233	json_stolen := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')1234	assert json_stolen.code == 01235	assert json_stolen.out.contains('"flagged":["${id}"]')1236	text_stolen := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')1237	assert text_stolen.code == 01238	assert text_stolen.out.contains('[${id}] came in flagged — broke the build')1239}12401241// A folder remote on a disk or share that is not mounted is simply not there.1242// Creating it would put the saves in a stand-in folder the other machine never1243// sees; the offer must say what is wrong instead.1244fn test_an_unmounted_folder_remote_is_not_recreated() {1245	syncroot := temp_repo('unmounted')1246	home := temp_repo('unmounted-home')1247	defer {1248		os.rmdir_all(syncroot) or {}1249		os.rmdir_all(home) or {}1250	}1251	mount := os.join_path(syncroot, 'nas')1252	remote := os.join_path(mount, 'koh')1253	a := os.join_path(syncroot, 'proj')1254	os.mkdir_all(a) or { panic(err) }1255	init_repo(a)1256	assert run_home(a, home, 'remote', 'folder', remote).code == 01257	write(a, 'a.txt', 'one\n')1258	assert run_home(a, home, 'save', 'first').code == 01259	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }1260	os.mkdir(mount) or { panic(err) }1261	offered := run_home(a, home, 'offer')1262	assert offered.code == 11263	assert offered.err.contains('mounted')1264	assert !os.exists(remote)1265	write(a, 'a.txt', 'two\n')1266	saved := run_home(a, home, 'save', 'second')1267	assert saved.code == 01268	assert saved.out.contains('mounted')1269	assert !os.exists(remote)1270}12711272fn test_man_and_koh2_handoff() {1273	dir := temp_repo('man')1274	home := temp_repo('man-home')1275	defer {1276		os.rmdir_all(dir) or {}1277		os.rmdir_all(home) or {}1278	}1279	whole := run_home(dir, home, 'man')1280	assert whole.code == 01281	assert whole.out.contains('NAME')1282	assert whole.out.contains('COMMANDS')1283	assert whole.out.contains('STRICT KOH DISCIPLINE')1284	assert !whole.out.contains('\x1b') && !whole.out.contains('◆')1285	strip := run_home(dir, home, 'man', 'strip')1286	assert strip.code == 01287	assert strip.out.contains('strip')1288	assert !strip.out.contains('koh save ')1289	steal := run_home(dir, home, 'man', 'steal').out1290	assert steal.starts_with('    koh steal') && steal.contains('koh steal my-project')1291	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."1292	assert run_home(dir, home, 'man', 'nonsense').code == 21293	legacy := temp_repo('legacy')1294	defer { os.rmdir_all(legacy) or {} }1295	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }1296	fake := os.join_path(home, 'bin')1297	os.mkdir_all(fake) or { panic(err) }1298	fake_koh := os.join_path(fake, 'koh2')1299	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }1300	os.chmod(fake_koh, 0o755) or { panic(err) }1301	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')1302	assert handoff.code == 71303	assert handoff.out.contains('handoff:status --json')1304	// One notice line, on stderr, so koh2's own output stays as it was.1305	assert handoff.err.contains('Koh 2 repo')1306	assert handoff.err.trim_space().split_into_lines().len == 11307	assert handoff.out.trim_space() == 'handoff:status --json'1308}13091310fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {1311	stamp := '${os.getpid()}-${time.now().unix_nano()}'1312	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')1313	out_path := '${base}.out'1314	err_path := '${base}.err'1315	code_path := '${base}.code'1316	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'1317	for arg in args {1318		command += ' ${q(arg)}'1319	}1320	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'1321	result := os.execute(shell)1322	if result.exit_code != 0 {1323		panic('could not run test command: ${result.output}')1324	}1325	code := os.read_file(code_path) or { panic(err) }1326	out := os.read_file(out_path) or { '' }1327	err := os.read_file(err_path) or { '' }1328	os.rm(out_path) or {}1329	os.rm(err_path) or {}1330	os.rm(code_path) or {}1331	return Result{1332		code: code.int()1333		out:  out1334		err:  err1335	}1336}13371338// --- migration -------------------------------------------------------------13391340fn koh2_binary() string {1341	return os.find_abs_path_of_executable('koh') or { '' }1342}13431344// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under1345// test here.1346fn run_koh2(dir string, command string) {1347	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')1348}13491350fn save_ids(dir string) []string {1351	mut ids := []string{}1352	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {1353		if name.ends_with('.json') {1354			ids << name.trim_right('.json')1355		}1356	}1357	ids.sort()1358	return ids1359}13601361fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {1362	koh2 := koh2_binary()1363	if koh2 == '' {1364		println('skipping the migration tests: koh (Koh 2) is not on PATH')1365		return1366	}1367	dir := temp_repo('migrate')1368	defer { os.rmdir_all(dir) or {} }1369	home := temp_repo('migrate-home')1370	defer { os.rmdir_all(home) or {} }1371	run_koh2(dir, '${q(koh2)} init')1372	// One file large enough to be an object, one small enough to be inlined.1373	write(dir, 'code.txt', 'x'.repeat(700))1374	write(dir, 'tiny.txt', 'tiny\n')1375	run_koh2(dir, '${q(koh2)} save "first save"')1376	run_koh2(dir, '${q(koh2)} checkpoint "before something"')1377	write(dir, 'code.txt', 'y'.repeat(700))1378	run_koh2(dir, '${q(koh2)} save "second save"')1379	original := save_ids(dir)1380	assert original.len == 313811382	report := run_home(dir, home, 'migrate')1383	assert report.code == 01384	assert report.out.contains('migrated 3 saves')1385	// The swap: `.koh` is a file, the old data is archived, nothing is left in the draft.1386	assert os.is_file(os.join_path(dir, '.koh'))1387	assert os.is_dir(os.join_path(dir, '.koh-v2'))1388	assert os.is_file(os.join_path(dir, '.kohignore'))1389	assert !os.exists(os.join_path(dir, '.koh-migrate'))13901391	// Every save kept its original ID, and the new repo is sound.1392	listed := run_home(dir, home, 'view', '--json')1393	assert listed.code == 01394	for id in original {1395		assert listed.out.contains(id)1396	}1397	assert run_home(dir, home, 'doctor').code == 01398	assert run_home(dir, home, 'status').code == 013991400	// Migrating again has nothing to convert.1401	assert run_home(dir, home, 'migrate').code == 11402}14031404fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {1405	koh2 := koh2_binary()1406	if koh2 == '' {1407		return1408	}1409	dir := temp_repo('migrate-dirty')1410	defer { os.rmdir_all(dir) or {} }1411	home := temp_repo('migrate-dirty-home')1412	defer { os.rmdir_all(home) or {} }1413	run_koh2(dir, '${q(koh2)} init')1414	write(dir, 'code.txt', 'x'.repeat(700))1415	run_koh2(dir, '${q(koh2)} save "only save"')1416	write(dir, 'code.txt', 'unsaved change\n')14171418	refused := run_home(dir, home, 'migrate')1419	assert refused.code == 11420	assert refused.err.contains('save with koh2 first')1421	// Nothing moved: still Koh 2, no archive, no draft file.1422	assert os.is_dir(os.join_path(dir, '.koh'))1423	assert !os.exists(os.join_path(dir, '.koh-v2'))1424	assert !os.exists(os.join_path(dir, '.koh-migrate'))1425}14261427// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or1428// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have1429// a `.kohconfig`; migrate must not call them unsaved work.1430fn test_migrate_passes_over_the_files_koh2_never_saved() {1431	koh2 := koh2_binary()1432	if koh2 == '' {1433		return1434	}1435	dir := temp_repo('migrate-koh2-ignores')1436	defer { os.rmdir_all(dir) or {} }1437	home := temp_repo('migrate-koh2-ignores-home')1438	defer { os.rmdir_all(home) or {} }1439	run_koh2(dir, '${q(koh2)} init')1440	write(dir, 'code.txt', 'x'.repeat(700))1441	run_koh2(dir, '${q(koh2)} save "only save"')1442	write(dir, '.kohconfig', 'stable_days = 14\n')1443	write(dir, '.kohignore.public', 'private/\n')1444	write(dir, 'lib/app.bundle', 'bundle\n')1445	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1446	// Koh 2 keeps saving a file under a folder pattern added later, where1447	// Koh 3 reads the same rule as covering the folder: the saved file is on1448	// disk and matches, so the tree is clean.1449	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1450	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1451	// Koh 2 skips *.bundle even when its rules no longer list it.1452	ignore_path := os.join_path(dir, '.koh', 'ignore')1453	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1454	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1455	// A saved file the walk skips still has to match what was saved.1456	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1457	changed := run_home(dir, home, 'migrate')1458	assert changed.code == 11459	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1460	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1461	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')14621463	migrated := run_home(dir, home, 'migrate')1464	assert migrated.code == 0, migrated.err1465	// They stay where they were, for the user to keep or delete.1466	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1467}14681469struct FakeKepr {1470	no_access bool1471	// One reply the redemption must cope with: '500', 'garbage' or 'incomplete'.1472	fail string1473	// When set, /api/connect answers 307 here instead of a code reply.1474	redirect_to string1475mut:1476	objects map[string][]u81477	// What the client asked for. A map, because the server holds its own copy of this struct.1478	seen map[string]string1479}14801481fn (mut h FakeKepr) handle(req http.Request) http.Response {1482	if req.method == .post && req.url == '/api/connect' {1483		h.seen['code'] = req.data1484		if h.redirect_to != '' {1485			return http.Response{1486				status_code: 3071487				status_msg:  'Temporary Redirect'1488				header:      http.new_header(1489					key:   .location1490					value: h.redirect_to1491				)1492			}1493		}1494		if h.fail == '500' {1495			return http.Response{ status_code: 500, status_msg: 'Internal Server Error' }1496		}1497		if h.fail == 'garbage' {1498			return http.Response{ status_code: 200, status_msg: 'OK', body: 'not json at all' }1499		}1500		if h.fail == 'incomplete' {1501			return http.Response{ status_code: 200, status_msg: 'OK', body: '{"endpoint":"http://x","bucket":"","region":"","access_key_id":"","secret_access_key":""}' }1502		}1503		if req.data == 'code=good' && !h.no_access {1504			return http.Response{ status_code: 200, status_msg: 'OK', body: '{"endpoint":"http://${req.header.get_custom('Host', http.HeaderQueryConfig{}) or { '' }}","bucket":"bucket","region":"test","access_key_id":"access","secret_access_key":"secret"}' }1505		}1506		return http.Response{ status_code: 404, status_msg: 'Not Found', body: '{"error":"no_code","message":"no code"}' }1507	}1508	if req.method == .get && req.url.starts_with('/connect') {1509		h.seen['connect'] = req.url1510		return http.Response{ status_code: if h.no_access { 404 } else { 302 }, status_msg: 'Found' }1511	}1512	key := req.url1513	if key.starts_with('/bucket/') {1514		match req.method {1515			.put {1516				if req.header.get_custom('If-None-Match', http.HeaderQueryConfig{}) or { '' } == '*' && key in h.objects {1517					return http.Response{ status_code: 412, status_msg: 'Precondition Failed' }1518				}1519				h.objects[key] = req.data.bytes()1520				return http.Response{ status_code: 200, status_msg: 'OK' }1521			}1522			.get {1523				if body := h.objects[key] {1524					return http.Response{1525						status_code: 2001526						status_msg:  'OK'1527						body:        body.bytestr()1528						header:      http.new_header(1529							key:   .etag1530							value: '"tag"'1531						)1532					}1533				}1534				return http.Response{ status_code: 404, status_msg: 'Not Found' }1535			}1536			.delete {1537				h.objects.delete(key)1538				return http.Response{ status_code: 204, status_msg: 'No Content' }1539			}1540			else {}1541		}1542	}1543	return http.Response{ status_code: 404, status_msg: 'Not Found' }1544}15451546fn start_fake_kepr(no_access bool, fail string, redirect_to string) !(int, &http.Server, &FakeKepr) {1547	for port in 19401 .. 19411 {1548		listener := net.listen_tcp(.ip, '127.0.0.1:${port}') or { continue }1549		fake := &FakeKepr{1550			no_access:   no_access1551			fail:        fail1552			redirect_to: redirect_to1553			seen:        map[string]string{}1554		}1555		mut server := &http.Server{1556			listener:             listener1557			handler:              fake1558			show_startup_message: false1559		}1560		spawn server.listen_and_serve()1561		server.wait_till_running()!1562		return port, server, fake1563	}1564	return error('no free fake Kepr port')1565}15661567// A slash makes an argument an address, so half an address is an error and never a repo name.1568fn test_steal_refuses_an_address_that_is_not_one() {1569	outside := temp_repo('steal-address')1570	home := temp_repo('steal-address-home')1571	defer { os.rmdir_all(outside) or {} }1572	defer { os.rmdir_all(home) or {} }1573	// The repo half becomes a URL path segment and a folder here, so it is a name Kepr serves.1574	for bad in ['kepr.uk/', '/shipped', 'kepr.uk/..', 'kepr.uk/.', 'kepr.uk/a b', 'kepr.uk/nina?x',1575		'kepr.uk/nina#x', 'kepr.uk/nína'] {1576		refused := run_home(outside, home, 'steal', bad)1577		assert refused.code == 1, bad1578		assert refused.err.contains('is not <host>/<repo>'), '${bad}: ${refused.err}'1579	}1580	assert run_home(outside, home, 'steal', 'one', 'two').code == 21581	assert run_home(outside, home, 'steal', '--list', 'extra').code == 21582}15831584fn test_remote_kepr_saves_and_refuses_without_changes() {1585	repo := temp_repo('kepr')1586	home := temp_repo('kepr-home')1587	defer { os.rmdir_all(repo) or {} }1588	defer { os.rmdir_all(home) or {} }1589	init_repo(repo)1590	port, mut server, fake := start_fake_kepr(false, '', '')!1591	defer { server.stop() }1592	host := 'http://127.0.0.1:${port}'1593	// A trailing slash is the same host, and the saved line keeps the normalised form.1594	good := run_home(repo, home, 'remote', '${host}/', '--code', 'good')1595	assert good.code == 0, good.err1596	remote_path := os.join_path(home, '.config', 'koh', 'remote')1597	credentials_path := os.join_path(home, '.config', 'koh', 'credentials')1598	assert os.read_file(remote_path)! == '# written by koh remote — the remote for every repo on this machine\nkind=s3\nendpoint=${host}\nbucket=bucket\nregion=test\nkepr=${host}\n'1599	assert os.read_file(credentials_path)! == '# written by koh remote — keep this file private\naccess_key=access\nsecret_key=secret\n'1600	// The code went as a form field, and the connect page was never asked for: there was a code.1601	assert (fake.seen['code'] or { '' }) == 'code=good'1602	assert (fake.seen['connect'] or { '' }) == ''1603	// A refused code, a missing terminal and a wrong reply all leave both files as they were.1604	before := os.read_file(remote_path)!1605	before_keys := os.read_file(credentials_path)!1606	bad := run_home(repo, home, 'remote', host, '--code', 'bad')1607	assert bad.code == 11608	assert bad.err.contains('wrong or has expired')1609	// The 404 could also mean a Kepr that hands out nothing, so the connect page is asked for1610	// with this machine's name. (This machine's name holds no character needing an escape, so1611	// that part of the query cannot be exercised here.)1612	// `machine.name()` is `os.hostname() or { 'unknown' }`, so the query carries the same text.1613	assert (fake.seen['connect'] or { '' }).contains('machine=${os.hostname() or { 'unknown' }}')1614	no_terminal := run_home(repo, home, 'remote', host)1615	assert no_terminal.code == 11616	assert no_terminal.err.contains('needs a terminal')1617	assert os.read_file(remote_path)! == before1618	assert os.read_file(credentials_path)! == before_keys1619}16201621fn test_remote_kepr_refuses_hosts_that_are_not_hosts() {1622	repo := temp_repo('kepr-host')1623	home := temp_repo('kepr-host-home')1624	defer { os.rmdir_all(repo) or {} }1625	defer { os.rmdir_all(home) or {} }1626	init_repo(repo)1627	for host in ['kepr.uk/foo', 'https://kepr.uk?x=1', 'kepr.uk#frag', '[email protected]', 'kepr uk',1628		'http://127.0.0.1:1/foo', 'https://'] {1629		refused := run_home(repo, home, 'remote', host, '--code', 'good')1630		assert refused.code == 1, host1631		assert refused.err.contains('is not a Kepr address'), '${host}: ${refused.err}'1632	}1633	// The reply carries the bucket's secret key, so plain http is only for this machine's own Kepr.1634	for host in ['http://kepr.uk', 'http://10.0.0.2:3000', 'http://KEPR.uk:80'] {1635		refused := run_home(repo, home, 'remote', host, '--code', 'good')1636		assert refused.code == 1, host1637		assert refused.err.contains('needs https'), '${host}: ${refused.err}'1638		stolen := run_home(home, home, 'steal', '${host}/nina')1639		assert stolen.code == 1, host1640		assert stolen.err.contains('needs https'), '${host}: ${stolen.err}'1641	}1642	// --code belongs to the host form alone.1643	assert run_home(repo, home, 'remote', 's3', 'https://x', 'b', 'r', '--code', 'good').code == 21644	assert run_home(repo, home, 'remote', 'folder', '/tmp', '--code', 'good').code == 21645	assert run_home(repo, home, 'remote', '--code', 'good').code == 21646	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1647}16481649fn test_remote_kepr_refuses_what_is_not_a_code_reply() {1650	repo := temp_repo('kepr-reply')1651	home := temp_repo('kepr-reply-home')1652	defer { os.rmdir_all(repo) or {} }1653	defer { os.rmdir_all(home) or {} }1654	init_repo(repo)1655	remote_path := os.join_path(home, '.config', 'koh', 'remote')1656	for mode in ['500', 'garbage', 'incomplete'] {1657		port, mut server, _ := start_fake_kepr(false, mode, '')!1658		refused := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1659		server.stop()1660		assert refused.code == 1, mode1661		assert refused.err.contains('nothing was changed'), '${mode}: ${refused.err}'1662		assert !os.exists(remote_path)1663	}1664	// A redirect would hand the code to wherever it points, so it is refused and never followed.1665	target_port, mut target, target_fake := start_fake_kepr(false, '', '')!1666	port, mut server, _ := start_fake_kepr(false, '', 'http://127.0.0.1:${target_port}/api/connect')!1667	redirected := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1668	server.stop()1669	target.stop()1670	assert redirected.code == 11671	assert redirected.err.contains('refused the code')1672	assert target_fake.seen.len == 0, 'the code was forwarded: ${target_fake.seen}'1673	assert !os.exists(remote_path)1674}16751676// An unreachable Kepr is a refusal too, and the settings are still untouched.1677fn test_remote_kepr_that_cannot_be_reached_changes_nothing() {1678	repo := temp_repo('kepr-down')1679	home := temp_repo('kepr-down-home')1680	defer { os.rmdir_all(repo) or {} }1681	defer { os.rmdir_all(home) or {} }1682	init_repo(repo)1683	refused := run_home(repo, home, 'remote', 'http://127.0.0.1:1', '--code', 'good')1684	assert refused.code == 11685	assert refused.err.contains('could not reach Kepr')1686	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1687}16881689fn test_remote_kepr_without_bucket_access_is_explained() {1690	repo := temp_repo('kepr-no-access')1691	home := temp_repo('kepr-no-access-home')1692	defer { os.rmdir_all(repo) or {} }1693	defer { os.rmdir_all(home) or {} }1694	init_repo(repo)1695	port, mut server, _ := start_fake_kepr(true, '', '')!1696	defer { server.stop() }1697	r := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'bad')1698	assert r.code == 11699	assert r.err.contains("doesn't hand out bucket access")1700	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1701}