cli_test.v

67.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	assert help.out.contains('  status      where things stand\n')273	assert help.out.contains('  diff        what changed\n')274	assert help.out.contains('Asha Software · asha.software')275	// No flag text anywhere on the screen.276	assert !help.out.contains('--'), help.out277	lines := help.out.split_into_lines()278	for line in lines {279		assert line.runes().len <= 80, line280	}281	// Each command has its own paragraph, a blank line above it.282	for name in names {283		for i, line in lines {284			if line.starts_with('  ${name} ') {285				assert i > 0 && lines[i - 1] == '', line286			}287		}288	}289	// A bare `koh` keeps its stream and exit code; `-h` shows the same screen.290	bare := run(dir)291	assert bare.code == 2292	assert bare.out == ''293	assert bare.err.contains('koh man <command>')294	short := run(dir, '-h')295	assert short.code == 0296	assert short.out == help.out297}298299// Colour on the screen follows NO_COLOR, as it does everywhere else.300fn test_the_help_screen_has_no_colour_when_it_is_off() {301	dir := temp_repo('help_plain')302	defer { os.rmdir_all(dir) or {} }303	home := temp_repo('help_plain_home')304	defer { os.rmdir_all(home) or {} }305	out_path := os.join_path(os.temp_dir(), 'koh3-help-${os.getpid()}-${time.now().unix_nano()}')306	defer { os.rm(out_path) or {} }307	code := os.system('cd ${q(dir)} && HOME=${q(home)} NO_COLOR=1 ${q(binary)} --help > ${q(out_path)}')308	assert code == 0309	text := os.read_file(out_path) or { panic(err) }310	assert !text.contains('\x1b'), text311	assert text.contains('  save        snapshot your work')312}313314// The binary embeds VERSION while saves bump v.mod; they drifted once.315fn test_version_matches_the_manifest() {316	dir := temp_repo('version')317	defer { os.rmdir_all(dir) or {} }318	version := run(dir, '--version').out.trim_space().all_after('koh ')319	manifest := os.read_file(os.join_path(root, 'v.mod')) or { panic(err) }320	assert manifest.contains("version: '${version}'"), version321}322323fn test_save_checkpoint_and_status() {324	dir := temp_repo('save')325	defer { os.rmdir_all(dir) or {} }326	init_repo(dir)327	write(dir, 'tracked.txt', 'one\n')328	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')329	assert r.code == 0330	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent', 'session',331		'files', 'size_bytes'] {332		read_json_has(r.out, key)333	}334	assert r.out.contains('"message":"first message"')335	assert r.out.contains('"agent":"agent-7"')336	assert r.out.contains('"session":"session-a"')337	assert r.out.contains('"is_checkpoint":false')338	assert run(dir, 'save', 'again').code == 1339	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')340	assert run(dir, 'save').code == 2341	assert run(dir, 'save', 'x', '--bogus').code == 2342	cp := run(dir, 'checkpoint', 'still first', '--json')343	assert cp.code == 0344	assert cp.out.contains('"is_checkpoint":true')345	assert cp.out.contains('"parent":')346	clean := run(dir, 'status')347	assert clean.code == 0348	assert clean.out.contains('no changes')349	write(dir, 'tracked.txt', 'two\n')350	write(dir, 'new.txt', 'new\n')351	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }352	write(dir, '.kohignore', '*.log\n')353	status := run(dir, 'status')354	assert status.code == 0355	assert status.out.contains('+')356	assert status.out.contains('~') || status.out.contains('-')357	assert status.out.contains('added')358	js := run(dir, 'status', '--json')359	assert js.code == 0360	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed',361		'saves', 'size_bytes', 'head_flagged'] {362		read_json_has(js.out, key)363	}364	assert js.out.contains('"ignore_changed":true')365	// What the shell prompt shows: saves on the line, the .koh size, the flag.366	assert js.out.contains('"saves":2')367	assert js.out.contains('"size_bytes":${os.file_size(os.join_path(dir, '.koh'))}')368	assert js.out.contains('"head_flagged":false')369	head := js.out.all_after('"head_id":"').all_before('"')370	assert run(dir, 'flag', head, '--reason', 'bad').code == 0371	assert run(dir, 'status', '--json').out.contains('"head_flagged":true')372}373374fn test_status_requires_repo_and_ignore_rules() {375	dir := temp_repo('status')376	defer { os.rmdir_all(dir) or {} }377	assert run(dir, 'status').code == 1378	init_repo(dir)379	write(dir, '.kohignore', '*.log\nbuild/\n')380	write(dir, 'keep.txt', 'keep\n')381	write(dir, 'ignored.log', 'ignore\n')382	write(dir, 'build/output.txt', 'ignore\n')383	saved := run(dir, 'save', 'keep', '--json')384	assert saved.code == 0385	id := saved.out.all_after('"id":"')[..12]386	// Where things stand comes first, clean or not.387	clean := run(dir, 'status').out388	assert clean.contains('at [${id}] keep · '), clean389	assert clean.contains(' · 1 save\n'), clean390	assert clean.contains('no changes')391	write(dir, 'keep.txt', 'changed\n')392	assert run(dir, 'status').out.contains('at [${id}] keep · ')393	write(dir, 'keep.txt', 'keep\n')394	assert !run(dir, 'status').out.contains('ignored.log')395	assert !run(dir, 'status').out.contains('build/output.txt')396	assert !run(dir, 'status').out.contains('LOG.md')397}398399fn test_status_and_save_report_unsafe_names_without_refusing_the_save() {400	dir := temp_repo('unsafe-names')401	defer { os.rmdir_all(dir) or {} }402	init_repo(dir)403	write(dir, 'safe.txt', 'safe\n')404	assert run(dir, 'save', 'safe').code == 0405	os.write_file('${dir}/bad\\name.txt', 'bad\n') or { panic(err) }406	os.write_file('${dir}/Icon\r', 'icon\n') or { panic(err) }407408	status := run(dir, 'status', '--json')409	assert status.code == 0410	assert status.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), status.out411	saved := run(dir, 'checkpoint', 'unsafe names', '--json')412	assert saved.code == 0413	assert saved.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), saved.out414}415416// LOG.md is a convenience written after the save lands. If it cannot be417// written, the save still happened, and an agent that retried on a failure418// would only be told nothing had changed.419fn test_a_save_succeeds_when_log_md_cannot_be_written() {420	dir := temp_repo('logmd')421	defer { os.rmdir_all(dir) or {} }422	init_repo(dir)423	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }424	write(dir, 'a.txt', 'one\n')425	r := run(dir, 'save', 'first', '--json')426	assert r.code == 0427	assert r.out.starts_with('{')428	assert r.err.contains('LOG.md')429	assert run(dir, 'view', '--json').out.contains('"message":"first"')430}431432// A folder of ignored files can sit where a restored file should go. Koh433// never touches ignored files, so the restore must stop and say so, not drop434// the file inside the folder under a temporary name.435fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {436	dir := temp_repo('dir-in-way')437	defer { os.rmdir_all(dir) or {} }438	init_repo(dir)439	write(dir, 'out', 'a file\n')440	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]441	os.rm(os.join_path(dir, 'out')) or { panic(err) }442	write(dir, 'out/build.log', 'ignored\n')443	assert run(dir, 'save', 'out is gone').code == 0444	r := run(dir, 'load', first, '--yes')445	assert r.code == 1446	assert r.err.contains('out')447	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']448}449450// Koh never follows a symlink, so a folder replaced by a link to somewhere451// else is not the repo's to write into: restoring through it would overwrite452// files outside the repo. The refusal comes before anything is recorded.453fn test_a_restore_never_writes_through_a_symlinked_folder() {454	dir := temp_repo('link-in-way')455	outside := temp_repo('link-target')456	defer {457		os.rmdir_all(dir) or {}458		os.rmdir_all(outside) or {}459	}460	init_repo(dir)461	write(dir, 'docs/a.md', 'saved\n')462	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]463	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }464	write(outside, 'a.md', 'precious\n')465	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }466	assert run(dir, 'save', 'docs is a link now').code == 0467	head := run(dir, 'status', '--json').out468	r := run(dir, 'load', first, '--yes')469	assert r.code == 1470	assert r.err.contains('docs')471	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'472	assert run(dir, 'status', '--json').out == head473}474475// A restore records its save first, then writes files. When the writing stops476// part way, the half-written tree is not somebody's work: saving it would477// record (and offer) a tree that undoes changes nobody asked to undo. Every478// command that would build on it points at revert, which finishes the job.479fn test_a_restore_cut_short_points_at_revert() {480	dir := temp_repo('cut-short')481	defer {482		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}483		os.rmdir_all(dir) or {}484	}485	init_repo(dir)486	write(dir, 'zero', '0\n')487	assert run(dir, 'save', 'zero').code == 0488	write(dir, 'a.txt', 'v1\n')489	write(dir, 'zz/f', 'v1\n')490	assert run(dir, 'save', 'first').code == 0491	write(dir, 'a.txt', 'v2\n')492	write(dir, 'zz/f', 'v2\n')493	assert run(dir, 'save', 'second').code == 0494	// a.txt is written, then the read-only folder stops the restore: the495	// tree is genuinely half one save and half the other.496	os.chmod(os.join_path(dir, 'zz'), 0o555)!497	stopped := run(dir, 'undo', '--yes')498	assert stopped.code == 1499	assert stopped.err.contains('koh revert')500	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'501	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'502	// Even a status that cannot read the tree says what happened.503	os.chmod(os.join_path(dir, 'zz'), 0o000)!504	assert run(dir, 'status').err.contains('koh revert')505	os.chmod(os.join_path(dir, 'zz'), 0o755)!506507	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')508	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {509		r := run(dir, ...args)510		assert r.code == 1511		assert r.err.contains('koh revert')512	}513	assert run(dir, 'revert', '--yes').code == 0514	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'515	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'516	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')517	write(dir, 'a.txt', 'v3\n')518	assert run(dir, 'save', 'carry on').code == 0519}520521// Doctor clears peek folders left from earlier days, never one somebody may522// be reading right now.523fn test_doctor_sweeps_only_old_peek_folders() {524	dir := temp_repo('peek-sweep')525	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in526	// the real temp directory under names no save could have.527	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')528	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')529	defer {530		os.rmdir_all(dir) or {}531		os.rmdir_all(fresh) or {}532		os.rmdir_all(old) or {}533	}534	init_repo(dir)535	write(dir, 'a.txt', 'one\n')536	assert run(dir, 'save', 'one').code == 0537	os.mkdir_all(fresh) or { panic(err) }538	os.mkdir_all(old) or { panic(err) }539	two_days_ago := time.now().unix() - 2 * 86400540	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }541	assert run(dir, 'doctor', '--json').code == 0542	assert os.exists(fresh)543	assert !os.exists(old)544}545546// A file saved long ago and ignored since holds work no save has. Loading the547// old save must not write over it; the document says a restore never touches548// ignored files.549fn test_a_restore_never_overwrites_an_ignored_file() {550	dir := temp_repo('ignored-restore')551	defer { os.rmdir_all(dir) or {} }552	init_repo(dir)553	write(dir, '.env', 'KEY=saved long ago\n')554	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]555	write(dir, '.kohignore', '.env\n')556	assert run(dir, 'save', 'ignore env').code == 0557	write(dir, '.env', 'KEY=never saved\n')558	assert run(dir, 'load', first, '--yes').code == 0559	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'560561	// Where the ignored file is missing, the restore still brings it back.562	other := temp_repo('ignored-restore-missing')563	defer { os.rmdir_all(other) or {} }564	init_repo(other)565	write(other, '.env', 'KEY=saved long ago\n')566	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]567	write(other, '.kohignore', '.env\n')568	assert run(other, 'save', 'ignore env').code == 0569	os.rm(os.join_path(other, '.env')) or { panic(err) }570	assert run(other, 'load', again, '--yes').code == 0571	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'572}573574// A going-back preview lists paths only. Running diff(1) per file to draw it575// cost 27 s for 5,000 changed files, so it must not run diff at all.576fn test_a_going_back_preview_does_not_run_diff() {577	dir := temp_repo('preview-nodiff')578	home := temp_repo('preview-nodiff-home')579	defer {580		os.rmdir_all(dir) or {}581		os.rmdir_all(home) or {}582	}583	init_repo(dir)584	write(dir, 'a.txt', 'one\n')585	assert run_home(dir, home, 'save', 'one').code == 0586	write(dir, 'a.txt', 'two\n')587	assert run_home(dir, home, 'save', 'two').code == 0588	fake := os.join_path(home, 'bin')589	os.mkdir_all(fake) or { panic(err) }590	marker := os.join_path(home, 'diff-ran')591	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {592		panic(err)593	}594	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }595	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0596	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'597	assert !os.exists(marker)598}599600// A restore rewrites only what differs. Rewriting every file resets every601// mtime, so the next status has to hash the whole tree again.602fn test_a_restore_leaves_unchanged_files_alone() {603	dir := temp_repo('restore-skip')604	defer { os.rmdir_all(dir) or {} }605	init_repo(dir)606	write(dir, 'a.txt', 'one\n')607	write(dir, 'same.txt', 'never changes\n')608	assert run(dir, 'save', 'one').code == 0609	write(dir, 'a.txt', 'two\n')610	assert run(dir, 'save', 'two').code == 0611	long_ago := i64(1700000000)612	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }613	assert run(dir, 'undo', '--yes').code == 0614	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'615	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago616}617618// `save` records the executable bit, so `status` has to see it too, or a619// chmod would be invisible until it turned up in a save.620fn test_status_sees_an_executable_bit_change() {621	dir := temp_repo('chmod')622	defer { os.rmdir_all(dir) or {} }623	init_repo(dir)624	write(dir, 'run.sh', 'echo hi\n')625	assert run(dir, 'save', 'script').code == 0626	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }627	status := run(dir, 'status', '--json')628	assert status.out.contains('"dirty":true')629	assert status.out.contains('"modified":["run.sh"]')630}631632fn test_view_and_diff() {633	dir := temp_repo('history')634	defer { os.rmdir_all(dir) or {} }635	init_repo(dir)636	write(dir, 'a.txt', 'one\n')637	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')638	id1 := first.out.all_after('"id":"')[..12]639	write(dir, 'a.txt', 'two\n')640	second := run(dir, 'save', 'two', '--session', 'beta', '--json')641	id2 := second.out.all_after('"id":"')[..12]642	cp := run(dir, 'checkpoint', 'checkpoint', '--json')643	assert cp.code == 0644	printed := run(dir, 'view')645	assert printed.code == 0646	assert printed.out.contains('▸')647	assert printed.out.contains('◐')648	lj := run(dir, 'view', '--json')649	assert lj.code == 0650	assert lj.out.contains('"head_id"')651	assert lj.out.contains('"saves"')652	assert run(dir, 'view', '--since', 'today').out.contains('two')653	session := run(dir, 'view', '--session', 'alpha')654	assert session.out.contains('one')655	assert !session.out.contains('two')656	assert run(dir, 'view', '--since', '9999-01-01').out.contains('no saves in that range')657	write(dir, 'a.txt', 'three\n')658	d := run(dir, 'diff')659	assert d.code == 0660	assert d.out.contains('--- a/')661	assert d.out.contains('+++ b/')662	assert run(dir, 'diff', id1).code == 0663	assert run(dir, 'diff', id1, id2).code == 0664	dj := run(dir, 'diff', '--json')665	assert dj.code == 0666	assert dj.out.contains('"from"')667	assert dj.out.contains('"to"')668	assert dj.out.contains('"files"')669	assert dj.out.contains('"change":"modified"')670	assert run(dir, 'diff', 'not-a-real-id').code == 1671	assert run(dir, 'diff', id1, id2, 'third').code == 1672	write(dir, 'blob.bin', '\x00\x01\x02')673	diff_binary := run(dir, 'diff', '--json')674	assert diff_binary.out.contains('"binary":true')675	assert diff_binary.out.contains('Binary files differ')676}677678fn test_undo_revert_and_load() {679	dir := temp_repo('restore')680	defer { os.rmdir_all(dir) or {} }681	init_repo(dir)682	write(dir, 'a.txt', 'one\n')683	one := run(dir, 'save', 'one', '--json').out684	id1 := one.all_after('"id":"')[..12]685	write(dir, 'a.txt', 'two\n')686	write(dir, 'gone.txt', 'gone\n')687	second := run(dir, 'save', 'two', '--json').out688	id2 := second.all_after('"id":"')[..12]689	write(dir, 'a.txt', 'three\n')690	third := run(dir, 'save', 'three', '--json').out691	id3 := third.all_after('"id":"')[..12]692	// Unsaved work — here a file never saved — blocks every going-back but693	// revert, as in Koh 2: a restore must never overwrite what only the disk has.694	write(dir, 'never.txt', 'keep me\n')695	view_before := run(dir, 'view').out696	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {697		blocked := run(dir, ...args)698		assert blocked.code == 1699		assert blocked.err.contains('unsaved changes')700	}701	assert run(dir, 'view').out == view_before702	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }703	write(dir, 'a.txt', 'edited, never saved\n')704	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')705	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'706	write(dir, 'a.txt', 'three\n')707	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }708	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')709	write(dir, 'gone.txt', 'gone\n')710	undo := run(dir, 'undo', '--yes', '--json')711	assert undo.code == 0712	if !undo.out.contains(id2) {713		panic('undo JSON did not name ${id2}: ${undo.out}')714	}715	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'716	assert os.exists(os.join_path(dir, 'gone.txt'))717	assert run(dir, 'load', id3, '--yes').code == 0718	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'719	assert run(dir, 'undo', '2', '--yes').code == 0720	assert run(dir, 'load', id2, '--yes').code == 0721	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')722	write(dir, 'a.txt', 'dirty\n')723	before := run(dir, 'view')724	refuse := run(dir, 'revert')725	assert refuse.code == 1726	assert refuse.err.contains('needs --yes when not interactive')727	assert run(dir, 'view').out == before.out728	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'729	write(dir, 'untracked.txt', 'remove\n')730	rv := run(dir, 'revert', '--yes', '--json')731	assert rv.code == 0732	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'733	assert !os.exists(os.join_path(dir, 'untracked.txt'))734	// The way back to the discarded work is named, not left to be found.735	kept := rv.out.all_after('"checkpoint":"')[..12]736	assert run(dir, 'load', kept, '--yes').code == 0737	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'738	assert os.read_file(os.join_path(dir, 'untracked.txt'))! == 'remove\n'739	write(dir, 'a.txt', 'dirty again\n')740	assert run(dir, 'revert', '--yes').out.contains('koh load ')741	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')742	assert run(dir, 'load', '--checkpoint', '--yes').code == 0743	assert run(dir, 'load', id2, '--json').code == 1744	assert run(dir, 'load', id2, '--json').err.contains('error')745	assert run(dir, 'load').code == 2746	assert run(dir, 'load', 'unknown-id', '--yes').code == 1747}748749fn test_flag_and_flagged_view() {750	dir := temp_repo('flag')751	defer { os.rmdir_all(dir) or {} }752	init_repo(dir)753	write(dir, 'flag.txt', 'one\n')754	saved := run(dir, 'save', 'flag me', '--json')755	id := saved.out.all_after('"id":"')[..12]756	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')757	assert flagged.code == 0758	assert flagged.out.contains('"flagged":true')759	assert flagged.out.contains('"reason":"unsafe"')760	list := run(dir, 'flag', '--json')761	assert list.code == 0762	assert list.out.contains(id)763	assert list.out.contains('unsafe')764	assert run(dir, 'view').out.contains('⚑')765	assert run(dir, 'flag', '--clear', id).code == 0766	assert run(dir, 'flag').out.contains('nothing is flagged')767	assert run(dir, 'flag', 'unknown-id').code == 1768	assert run(dir, 'flag').code == 0769}770771fn test_pluck_forward_reverse_dry_run_and_conflict() {772	dir := temp_repo('pluck')773	defer { os.rmdir_all(dir) or {} }774	init_repo(dir)775	write(dir, 'a.txt', 'one\n')776	first := run(dir, 'save', 'one', '--json').out777	id1 := first.all_after('"id":"')[..12]778	write(dir, 'a.txt', 'two\n')779	second := run(dir, 'save', 'two', '--json').out780	id2 := second.all_after('"id":"')[..12]781	assert run(dir, 'load', id1, '--yes').code == 0782	dry := run(dir, 'pluck', id2, '--dry-run')783	assert dry.code == 0784	assert dry.out.contains('a.txt')785	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'786	assert run(dir, 'pluck', id2, '--yes').code == 0787	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'788	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0789	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'790	write(dir, 'a.txt', 'different\n')791	assert run(dir, 'pluck', id2, '--dry-run').code == 1792	assert run(dir, 'save', 'different').code == 0793	conflict := run(dir, 'pluck', id2, '--yes')794	assert conflict.code == 1795	assert conflict.err.contains('a.txt')796	assert run(dir, 'pluck').code == 2797	assert run(dir, 'pluck', 'unknown-id').code == 1798}799800fn test_peek_and_doctor() {801	dir := temp_repo('peek-doctor')802	defer { os.rmdir_all(dir) or {} }803	init_repo(dir)804	write(dir, 'peek.txt', 'peek me\n')805	assert run(dir, 'save', 'peekable').code == 0806	id := run(dir, 'view', '--json').out.all_after('"id":"')[..12]807	before_view := run(dir, 'view', '--json').out808	peek := run(dir, 'peek', id, '--json')809	assert peek.code == 0810	peek_path := peek.out.all_after('"path":"').before('"')811	assert peek.out.contains('"id":"${id}"')812	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'813	assert run(dir, 'status').out.contains('no changes')814	assert run(dir, 'view', '--json').out == before_view815	assert run(dir, 'peek').code == 2816	assert run(dir, 'peek', 'unknown-id').code == 1817	backup := os.join_path(dir, 'doctor.backup')818	healthy := run(dir, 'doctor')819	assert healthy.code == 0820	assert healthy.out.contains('is sound')821	report := run(dir, 'doctor', '--json')822	assert report.code == 0823	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',824		'backup'] {825		read_json_has(report.out, key)826	}827	backed := run(dir, 'doctor', '--backup', backup)828	assert backed.code == 0829	assert os.exists(backup)830	assert backed.out.contains(backup)831	assert run(dir, 'doctor', '--backup', backup).code == 1832	assert run(dir, 'peek', id, '--json').code == 0833	// A peek made today is left for whoever is reading it.834	kept := run(dir, 'doctor', '--json')835	assert kept.code == 0836	assert os.exists(peek_path)837	os.rmdir_all(peek_path) or {}838}839840fn test_strip_refuses_without_terminal() {841	dir := temp_repo('strip')842	defer { os.rmdir_all(dir) or {} }843	init_repo(dir)844	write(dir, 'secret.txt', 'keep\n')845	assert run(dir, 'save', 'secret').code == 0846	before_view := run(dir, 'view', '--json').out847	refused := run(dir, 'strip', 'secret.txt')848	assert refused.code == 1849	assert refused.err.contains('needs a terminal')850	assert run(dir, 'view', '--json').out == before_view851	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'852	assert run(dir, 'view', '--json').out.contains('secret')853}854855// A whole-history strip bans the path: `.kohignore` names it, once, and the file left on disk856// is never unsaved work or part of a save again.857fn test_strip_adds_the_path_to_kohignore_and_it_stays_out() {858	dir := temp_repo('strip-ignore')859	home := temp_repo('strip-ignore-home')860	defer { os.rmdir_all(dir) or {} }861	defer { os.rmdir_all(home) or {} }862	init_repo(dir)863	write(dir, 'secret.txt', 'leaked\n')864	write(dir, 'keep.txt', 'fine\n')865	assert run_home(dir, home, 'save', 'leak').code == 0866	stripped := run_pty_home(dir, home, ['y', 'secret.txt'], 'strip', 'secret.txt')867	assert stripped.code == 0, stripped.out868	assert stripped.out.contains('added /secret.txt to .kohignore')869	ignore_path := os.join_path(dir, '.kohignore')870	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1871	assert run_home(dir, home, 'save', 'ignore the stripped secret').code == 0872	write(dir, 'secret.txt', 'leaked again\n')873	assert run_home(dir, home, 'status', '--json').out.contains('"dirty":false')874	// Running the strip again (with no remote, it stays pending) adds no second line.875	again := run_pty_home(dir, home, [], 'strip', 'secret.txt')876	assert again.code == 0, again.out877	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1878}879880// `koh view` is the one way into the history: the whole line by default,881// checkpoints alone with the flag, and the two lists never overlap.882fn test_view_shows_the_line_and_checkpoints_apart() {883	dir := temp_repo('view')884	defer { os.rmdir_all(dir) or {} }885	init_repo(dir)886	write(dir, 'view.txt', 'one\n')887	assert run(dir, 'save', 'plain save').code == 0888	assert run(dir, 'checkpoint', 'checkpoint save').code == 0889	line := run(dir, 'view')890	assert line.code == 0891	assert line.out.contains('plain save')892	assert line.out.contains('checkpoint save')893	checkpoints := run(dir, 'view', '--checkpoints')894	assert checkpoints.code == 0895	assert checkpoints.out.contains('checkpoint save')896	assert !checkpoints.out.contains('plain save')897	json_line := run(dir, 'view', '--json')898	assert json_line.code == 0899	assert json_line.out.contains('"is_checkpoint":false')900	assert json_line.out.contains('"is_checkpoint":true')901	json_checkpoints := run(dir, 'view', '--checkpoints', '--json')902	assert json_checkpoints.code == 0903	assert json_checkpoints.out.contains('"is_checkpoint":true')904	assert !json_checkpoints.out.contains('"is_checkpoint":false')905	// `view` takes no arguments, so a stray one is a usage error, and the names906	// it replaced are gone rather than hidden: the diagnostic says which.907	assert run(dir, 'view', 'extra').code == 2908	for gone in ['log', 'saves', 'checkpoints'] {909		refused := run(dir, gone)910		assert refused.code == 2911		assert refused.err.contains('unknown command "${gone}"')912	}913	// Every save is on the whole line exactly once, as the JSON says.914	assert line.out.split_into_lines().len == json_line.out.count('"id":"')915}916917fn test_remote_configuration_is_isolated_and_atomic() {918	dir := temp_repo('remote')919	home := temp_repo('remote-home')920	defer {921		os.rmdir_all(dir) or {}922		os.rmdir_all(home) or {}923	}924	empty := run_home(dir, home, 'remote', '--json')925	assert empty.code == 0926	assert empty.out.contains('"configured":false')927	target := os.join_path(home, 'remote-store')928	set := run_home(dir, home, 'remote', 'folder', target)929	assert set.code == 0930	assert os.is_dir(target)931	state := run_home(dir, home, 'remote', '--json')932	assert state.code == 0933	assert state.out.contains('"kind":"folder"')934	assert state.out.contains(target)935	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1936	assert run_home(dir, home, 'remote', '--json').out.contains(target)937	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')938	assert run_home(dir, home, 'remote', '--forget').code == 0939	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')940}941942// The files under ~/.config/koh can be written by hand instead of by943// `koh remote`, and are then read the same way.944fn test_remote_written_by_hand() {945	dir := temp_repo('remote-by-hand')946	home := temp_repo('remote-by-hand-home')947	defer {948		os.rmdir_all(dir) or {}949		os.rmdir_all(home) or {}950	}951	config := os.join_path(home, '.config', 'koh')952	os.mkdir_all(config) or { panic(err) }953	target := os.join_path(home, 'remote-store')954	os.mkdir_all(target) or { panic(err) }955	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {956		panic(err)957	}958	assert run_home(dir, home, 'init').code == 0959	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }960	assert run_home(dir, home, 'save', 'first').code == 0961	offered := run_home(dir, home, 'offer', '--json')962	assert offered.code == 0963	assert offered.out.contains('"head"')964965	// Keys anyone else can read are refused before they are ever sent.966	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {967		panic(err)968	}969	credentials := os.join_path(config, 'credentials')970	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }971	os.chmod(credentials, 0o644) or { panic(err) }972	loose := run_home(dir, home, 'offer')973	assert loose.code == 1974	assert loose.err.contains('chmod 600')975976	// A setting koh cannot read is replaced by setting the remote again.977	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }978	unreadable := run_home(dir, home, 'offer')979	assert unreadable.code == 1980	assert unreadable.err.contains('not readable')981	assert run_home(dir, home, 'remote', 'folder', target).code == 0982	assert run_home(dir, home, 'offer').code == 0983}984985// A stolen repo belongs to the repo it was stolen from, whatever its folder is986// called later: renaming it must not start a second repo on the remote.987fn test_a_renamed_stolen_repo_keeps_offering_to_its_repo() {988	syncroot := temp_repo('rename-steal')989	home := temp_repo('rename-steal-home')990	defer {991		os.rmdir_all(syncroot) or {}992		os.rmdir_all(home) or {}993	}994	remote := os.join_path(syncroot, 'remote')995	a := os.join_path(syncroot, 'A', 'proj')996	b_parent := os.join_path(syncroot, 'B')997	os.mkdir_all(a) or { panic(err) }998	os.mkdir_all(b_parent) or { panic(err) }999	init_repo(a)1000	write(a, 'a.txt', 'from A\n')1001	assert run_home(a, home, 'remote', 'folder', remote).code == 01002	assert run_home(a, home, 'save', 'A first').code == 01003	assert run_home(b_parent, home, 'steal', 'proj').code == 01004	renamed := os.join_path(b_parent, 'renamed')1005	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }1006	write(renamed, 'b.txt', 'from B\n')1007	assert run_home(renamed, home, 'save', 'B first').code == 01008	assert !os.exists(os.join_path(remote, 'renamed'))1009	assert run_home(a, home, 'steal').code == 01010	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'1011}10121013// A damaged object on the remote stops a steal, names the object, and leaves1014// no half-made folder that would make the retry refuse.1015fn test_steal_of_a_damaged_remote_leaves_nothing() {1016	syncroot := temp_repo('damaged')1017	home := temp_repo('damaged-home')1018	defer {1019		os.rmdir_all(syncroot) or {}1020		os.rmdir_all(home) or {}1021	}1022	remote := os.join_path(syncroot, 'remote')1023	a := os.join_path(syncroot, 'A', 'proj')1024	b_parent := os.join_path(syncroot, 'B')1025	os.mkdir_all(a) or { panic(err) }1026	os.mkdir_all(b_parent) or { panic(err) }1027	init_repo(a)1028	write(a, 'a.txt', 'from A\n')1029	assert run_home(a, home, 'remote', 'folder', remote).code == 01030	assert run_home(a, home, 'save', 'A first').code == 01031	objects := os.join_path(remote, 'proj', 'objects')1032	for name in os.ls(objects) or { panic(err) } {1033		os.chmod(os.join_path(objects, name), 0o644) or {}1034		os.write_file(os.join_path(objects, name), 'junk') or { panic(err) }1035	}1036	stolen := run_home(b_parent, home, 'steal', 'proj')1037	assert stolen.code == 11038	assert stolen.err.contains('is damaged')1039	assert !os.exists(os.join_path(b_parent, 'proj'))1040}10411042fn test_steal_drops_crafted_unsafe_paths_and_lands_the_rest() {1043	syncroot := temp_repo('unsafe-remote')1044	home := temp_repo('unsafe-remote-home')1045	defer {1046		os.rmdir_all(syncroot) or {}1047		os.rmdir_all(home) or {}1048	}1049	remote := os.join_path(syncroot, 'remote')1050	a := os.join_path(syncroot, 'A', 'proj')1051	b_parent := os.join_path(syncroot, 'B')1052	os.mkdir_all(a) or { panic(err) }1053	os.mkdir_all(b_parent) or { panic(err) }1054	init_repo(a)1055	write(a, 'safe.txt', 'safe\n')1056	assert run_home(a, home, 'remote', 'folder', remote).code == 01057	id := run_home(a, home, 'save', 'crafted', '--json').out.all_after('"id":"')[..12]1058	assert run_home(a, home, 'offer').code == 01059	record_path := os.join_path(remote, 'proj', 'saves', id)1060	record := os.read_file(record_path) or { panic(err) }1061	path_at := record.index('"path":"safe.txt"') or { panic('safe path missing from ${record}') }1062	file_start := record[..path_at].last_index('{') or { panic('safe file start missing') }1063	file_end := path_at + (record[path_at..].index('}') or { panic('safe file end missing') }) + 11064	file := record[file_start..file_end]1065	mut files := [file]1066	for path in ['../outside.txt', '/etc/koh-test', 'a/../../outside.txt', 'bad\\\\name',1067		'control\\rname'] {1068		files << file.replace('safe.txt', path)1069	}1070	os.write_file(record_path, record[..file_start] + files.join(',') + record[file_end..]) or {1071		panic(err)1072	}10731074	stolen := run_home(b_parent, home, 'steal', 'proj')1075	assert stolen.code == 0, stolen.err1076	for dropped in ['../outside.txt', 'bad\\\\name', 'control\\x0dname'] {1077		assert (stolen.out + stolen.err).contains('dropped unsafe path ${dropped}'), stolen.out + stolen.err1078	}1079	assert os.read_file(os.join_path(b_parent, 'proj', 'safe.txt'))! == 'safe\n'1080	assert !os.exists(os.join_path(b_parent, 'outside.txt'))1081	assert !os.exists(os.join_path(b_parent, 'proj', 'bad', 'name'))1082	assert !os.exists('${b_parent}/proj/control\rname')1083}10841085fn test_offer_steal_folder_remote() {1086	syncroot := temp_repo('sync')1087	home := temp_repo('sync-home')1088	defer {1089		os.rmdir_all(syncroot) or {}1090		os.rmdir_all(home) or {}1091	}1092	remote := os.join_path(syncroot, 'remote')1093	a := os.join_path(syncroot, 'A', 'proj')1094	b_parent := os.join_path(syncroot, 'B')1095	os.mkdir_all(a) or { panic(err) }1096	os.mkdir_all(b_parent) or { panic(err) }1097	init_repo(a)1098	write(a, 'a.txt', 'from A\n')1099	assert run_home(a, home, 'remote', 'folder', remote).code == 01100	assert run_home(a, home, 'save', 'A first').code == 01101	stolen := run_home(b_parent, home, 'steal', 'proj')1102	assert stolen.code == 01103	b := os.join_path(b_parent, 'proj')1104	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'1105	write(b, 'b.txt', 'from B\n')1106	assert run_home(b, home, 'save', 'B first').code == 01107	write(a, 'a2.txt', 'second\n')1108	assert run_home(a, home, 'save', 'A second').code == 01109	assert run_home(a, home, 'steal').code == 01110	assert os.exists(os.join_path(a, 'b.txt'))1111	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')1112	write(a, 'clash.txt', 'base\n')1113	assert run_home(a, home, 'save', 'clash base').code == 01114	assert run_home(b, home, 'steal').code == 01115	write(a, 'clash.txt', 'A version\n')1116	assert run_home(a, home, 'save', 'A clash').code == 01117	write(b, 'clash.txt', 'B version\n')1118	assert run_home(b, home, 'save', 'B clash').code == 01119	refused := run_home(b, home, 'steal')1120	assert refused.code == 11121	assert refused.err.contains('--mine') || refused.err.contains('--theirs')1122	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1123	theirs := run_home(b, home, 'steal', '--theirs', '--json')1124	assert theirs.code == 01125	// The pre-combine tree is off the line now; the way back must be named,1126	// or an agent without the history view cannot find it.1127	assert theirs.out.contains('"previous_head":"${b_head}"')1128	assert theirs.out.contains('"kept_versions":["clash.txt:${b_head}"]')1129	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1130	assert run_home(b, home, 'load', b_head, '--yes').code == 01131	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'1132	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 01133	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1134	write(a, 'clash.txt', 'A second\n')1135	assert run_home(a, home, 'save', 'A second clash').code == 01136	write(b, 'clash.txt', 'B second\n')1137	assert run_home(b, home, 'save', 'B second clash').code == 01138	assert run_home(b, home, 'steal', '--mine').code == 01139	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'1140	assert run_home(b, home, 'view').out.contains('combine: kept mine for')1141}11421143fn test_guided_steal_walks_the_terminal_and_can_cancel() {1144	syncroot := temp_repo('guided-steal')1145	home := temp_repo('guided-steal-home')1146	defer {1147		os.rmdir_all(syncroot) or {}1148		os.rmdir_all(home) or {}1149	}1150	remote := os.join_path(syncroot, 'remote')1151	a := os.join_path(syncroot, 'A', 'proj')1152	b_parent := os.join_path(syncroot, 'B')1153	os.mkdir_all(a) or { panic(err) }1154	os.mkdir_all(b_parent) or { panic(err) }1155	init_repo(a)1156	write(a, 'clash.txt', 'base\n')1157	write(a, 'other.txt', 'base\n')1158	write(a, 'same.txt', 'base\n')1159	write(a, 'remote-only.txt', 'base\n')1160	write(a, 'local-only.txt', 'base\n')1161	assert run_home(a, home, 'remote', 'folder', remote).code == 01162	assert run_home(a, home, 'save', 'base').code == 01163	assert run_home(b_parent, home, 'steal', 'proj').code == 01164	b := os.join_path(b_parent, 'proj')11651166	write(b, 'dirty.txt', 'mine\n')1167	before := run_home(b, home, 'status', '--json').out1168	quit := run_pty_home(b, home, ['q'], 'steal')1169	assert quit.out.contains('steal proj')1170	assert quit.out.contains('you have 1 unsaved file')1171	assert quit.out.contains('dirty.txt')1172	assert run_home(b, home, 'status', '--json').out == before1173	// A save needs a message; an empty one stops, says so, and saves nothing.1174	unsaid := run_pty_home(b, home, ['s', ''], 'steal')1175	assert unsaid.code == 11176	assert unsaid.out.contains('no message — nothing was saved')1177	assert run_home(b, home, 'status', '--json').out == before1178	checkpoint := run_pty_home(b, home, ['c'], 'steal')1179	assert checkpoint.code == 0, checkpoint.err1180	assert run_home(b, home, 'view', '--checkpoints').out.contains('before steal')11811182	assert run_home(a, home, 'steal').code == 01183	write(a, 'forward.txt', 'new\n')1184	assert run_home(a, home, 'save', 'fast forward').code == 01185	forward := run_pty_home(b, home, []string{}, 'steal')1186	assert forward.out.contains('proj is up to date · 1 new save')1187	assert forward.out.split_into_lines().filter(it.trim_space() != '').len == 11188	write(a, 'clash.txt', 'remote\n')1189	write(a, 'other.txt', 'remote\n')1190	write(a, 'same.txt', 'identical\n')1191	write(a, 'remote-only.txt', 'remote\n')1192	assert run_home(a, home, 'save', 'remote change').code == 01193	write(b, 'clash.txt', 'mine\n')1194	write(b, 'other.txt', 'mine\n')1195	write(b, 'same.txt', 'identical\n')1196	write(b, 'local-only.txt', 'mine\n')1197	assert run_home(b, home, 'save', 'local change').code == 01198	local_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1199	// `d` opens both changes in the pager, which Enter leaves; `?` explains the two sides.1200	cancel := run_pty_home(b, home, ['d', '', '?', 'm', 'b', 't', 't', 'n'], 'steal')1201	assert cancel.out.contains('your changes')1202	assert cancel.out.contains('remote changes')1203	assert cancel.out.contains('Nothing is lost either way')1204	// The shared save's age, relative: seconds old here, so `now` unless the machine is slow.1205	since := cancel.out.split_into_lines().filter(it.contains('both moved since'))1206	assert since.len == 11207	assert since[0].trim_space().ends_with(' · now') || since[0].trim_space().ends_with(' ago'), since[0]1208	assert cancel.out.contains('5 files changed')1209	assert cancel.out.contains('2 combine by themselves')1210	assert cancel.out.contains('1 changed the same way')1211	assert cancel.out.contains('2 need you')1212	assert cancel.out.contains('ready to combine')1213	assert run_home(b, home, 'status', '--json').out.contains('"head_id":"${local_head}"')1214	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'mine\n'12151216	done := run_pty_home(b, home, ['y'], 'steal', '--theirs')1217	assert done.out.contains('combined · offered to proj')1218	assert done.out.contains('took theirs: clash.txt · other.txt')1219	assert !done.out.contains('kept mine')1220	assert done.out.contains('to undo all of it: koh load ${local_head}')1221	assert done.out.contains('your clash.txt is in ${local_head}')1222	assert !done.out.contains('\x1b')1223	for line in done.out.split_into_lines() {1224		assert line.runes().len <= 80, line1225	}1226}12271228// A steal brings in the whole history, flags included; both output forms must1229// say which saves came in flagged, and why.1230fn test_a_steal_reports_flagged_saves() {1231	syncroot := temp_repo('steal-flags')1232	home := temp_repo('steal-flags-home')1233	defer {1234		os.rmdir_all(syncroot) or {}1235		os.rmdir_all(home) or {}1236	}1237	a := os.join_path(syncroot, 'A', 'proj')1238	os.mkdir_all(a) or { panic(err) }1239	init_repo(a)1240	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 01241	write(a, 'a.txt', 'one\n')1242	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]1243	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 01244	assert run_home(a, home, 'offer').code == 01245	for name in ['B', 'C'] {1246		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }1247	}1248	json_stolen := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')1249	assert json_stolen.code == 01250	assert json_stolen.out.contains('"flagged":["${id}"]')1251	text_stolen := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')1252	assert text_stolen.code == 01253	assert text_stolen.out.contains('[${id}] came in flagged — broke the build')1254}12551256// A folder remote on a disk or share that is not mounted is simply not there.1257// Creating it would put the saves in a stand-in folder the other machine never1258// sees; the offer must say what is wrong instead.1259fn test_an_unmounted_folder_remote_is_not_recreated() {1260	syncroot := temp_repo('unmounted')1261	home := temp_repo('unmounted-home')1262	defer {1263		os.rmdir_all(syncroot) or {}1264		os.rmdir_all(home) or {}1265	}1266	mount := os.join_path(syncroot, 'nas')1267	remote := os.join_path(mount, 'koh')1268	a := os.join_path(syncroot, 'proj')1269	os.mkdir_all(a) or { panic(err) }1270	init_repo(a)1271	assert run_home(a, home, 'remote', 'folder', remote).code == 01272	write(a, 'a.txt', 'one\n')1273	assert run_home(a, home, 'save', 'first').code == 01274	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }1275	os.mkdir(mount) or { panic(err) }1276	offered := run_home(a, home, 'offer')1277	assert offered.code == 11278	assert offered.err.contains('mounted')1279	assert !os.exists(remote)1280	write(a, 'a.txt', 'two\n')1281	saved := run_home(a, home, 'save', 'second')1282	assert saved.code == 01283	assert saved.out.contains('mounted')1284	assert !os.exists(remote)1285}12861287fn test_man_and_koh2_handoff() {1288	dir := temp_repo('man')1289	home := temp_repo('man-home')1290	defer {1291		os.rmdir_all(dir) or {}1292		os.rmdir_all(home) or {}1293	}1294	whole := run_home(dir, home, 'man')1295	assert whole.code == 01296	assert whole.out.contains('NAME')1297	assert whole.out.contains('COMMANDS')1298	assert whole.out.contains('STRICT KOH DISCIPLINE')1299	assert whole.out.contains('Asha Software · asha.software')1300	assert !whole.out.contains('\x1b') && !whole.out.contains('◆')1301	strip := run_home(dir, home, 'man', 'strip')1302	assert strip.code == 01303	assert strip.out.contains('strip')1304	assert !strip.out.contains('koh save ')1305	steal := run_home(dir, home, 'man', 'steal').out1306	assert steal.starts_with('    koh steal') && steal.contains('koh steal my-project')1307	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."1308	assert run_home(dir, home, 'man', 'nonsense').code == 21309	legacy := temp_repo('legacy')1310	defer { os.rmdir_all(legacy) or {} }1311	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }1312	fake := os.join_path(home, 'bin')1313	os.mkdir_all(fake) or { panic(err) }1314	fake_koh := os.join_path(fake, 'koh2')1315	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }1316	os.chmod(fake_koh, 0o755) or { panic(err) }1317	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')1318	assert handoff.code == 71319	assert handoff.out.contains('handoff:status --json')1320	// One notice line, on stderr, so koh2's own output stays as it was.1321	assert handoff.err.contains('Koh 2 repo')1322	assert handoff.err.trim_space().split_into_lines().len == 11323	assert handoff.out.trim_space() == 'handoff:status --json'1324}13251326fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {1327	stamp := '${os.getpid()}-${time.now().unix_nano()}'1328	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')1329	out_path := '${base}.out'1330	err_path := '${base}.err'1331	code_path := '${base}.code'1332	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'1333	for arg in args {1334		command += ' ${q(arg)}'1335	}1336	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'1337	result := os.execute(shell)1338	if result.exit_code != 0 {1339		panic('could not run test command: ${result.output}')1340	}1341	code := os.read_file(code_path) or { panic(err) }1342	out := os.read_file(out_path) or { '' }1343	err := os.read_file(err_path) or { '' }1344	os.rm(out_path) or {}1345	os.rm(err_path) or {}1346	os.rm(code_path) or {}1347	return Result{1348		code: code.int()1349		out:  out1350		err:  err1351	}1352}13531354// --- migration -------------------------------------------------------------13551356// koh2_binary finds Koh 2: `koh2` since the cutover, `koh` before it, and never Koh 3.1357fn koh2_binary() string {1358	for name in ['koh2', 'koh'] {1359		path := os.find_abs_path_of_executable(name) or { continue }1360		if os.execute('${os.quoted_path(path)} --version').output.starts_with('koh v2') {1361			return path1362		}1363	}1364	return ''1365}13661367// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under1368// test here.1369fn run_koh2(dir string, command string) {1370	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')1371}13721373fn save_ids(dir string) []string {1374	mut ids := []string{}1375	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {1376		if name.ends_with('.json') {1377			ids << name.trim_right('.json')1378		}1379	}1380	ids.sort()1381	return ids1382}13831384fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {1385	koh2 := koh2_binary()1386	if koh2 == '' {1387		println('skipping the migration tests: koh (Koh 2) is not on PATH')1388		return1389	}1390	dir := temp_repo('migrate')1391	defer { os.rmdir_all(dir) or {} }1392	home := temp_repo('migrate-home')1393	defer { os.rmdir_all(home) or {} }1394	run_koh2(dir, '${q(koh2)} init')1395	// One file large enough to be an object, one small enough to be inlined.1396	write(dir, 'code.txt', 'x'.repeat(700))1397	write(dir, 'tiny.txt', 'tiny\n')1398	run_koh2(dir, '${q(koh2)} save "first save"')1399	run_koh2(dir, '${q(koh2)} checkpoint "before something"')1400	write(dir, 'code.txt', 'y'.repeat(700))1401	run_koh2(dir, '${q(koh2)} save "second save"')1402	original := save_ids(dir)1403	assert original.len == 314041405	report := run_home(dir, home, 'migrate')1406	assert report.code == 01407	assert report.out.contains('migrated 3 saves')1408	// The swap: `.koh` is a file, the old data is archived, nothing is left in the draft.1409	assert os.is_file(os.join_path(dir, '.koh'))1410	assert os.is_dir(os.join_path(dir, '.koh-v2'))1411	assert os.is_file(os.join_path(dir, '.kohignore'))1412	assert !os.exists(os.join_path(dir, '.koh-migrate'))14131414	// Every save kept its original ID, and the new repo is sound.1415	listed := run_home(dir, home, 'view', '--json')1416	assert listed.code == 01417	for id in original {1418		assert listed.out.contains(id)1419	}1420	assert run_home(dir, home, 'doctor').code == 01421	assert run_home(dir, home, 'status').code == 014221423	// Migrating again has nothing to convert.1424	assert run_home(dir, home, 'migrate').code == 11425}14261427fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {1428	koh2 := koh2_binary()1429	if koh2 == '' {1430		return1431	}1432	dir := temp_repo('migrate-dirty')1433	defer { os.rmdir_all(dir) or {} }1434	home := temp_repo('migrate-dirty-home')1435	defer { os.rmdir_all(home) or {} }1436	run_koh2(dir, '${q(koh2)} init')1437	write(dir, 'code.txt', 'x'.repeat(700))1438	run_koh2(dir, '${q(koh2)} save "only save"')1439	write(dir, 'code.txt', 'unsaved change\n')14401441	refused := run_home(dir, home, 'migrate')1442	assert refused.code == 11443	assert refused.err.contains('save with koh2 first')1444	// Nothing moved: still Koh 2, no archive, no draft file.1445	assert os.is_dir(os.join_path(dir, '.koh'))1446	assert !os.exists(os.join_path(dir, '.koh-v2'))1447	assert !os.exists(os.join_path(dir, '.koh-migrate'))1448}14491450// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or1451// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have1452// a `.kohconfig`; migrate must not call them unsaved work.1453fn test_migrate_passes_over_the_files_koh2_never_saved() {1454	koh2 := koh2_binary()1455	if koh2 == '' {1456		return1457	}1458	dir := temp_repo('migrate-koh2-ignores')1459	defer { os.rmdir_all(dir) or {} }1460	home := temp_repo('migrate-koh2-ignores-home')1461	defer { os.rmdir_all(home) or {} }1462	run_koh2(dir, '${q(koh2)} init')1463	write(dir, 'code.txt', 'x'.repeat(700))1464	run_koh2(dir, '${q(koh2)} save "only save"')1465	write(dir, '.kohconfig', 'stable_days = 14\n')1466	write(dir, '.kohignore.public', 'private/\n')1467	write(dir, 'lib/app.bundle', 'bundle\n')1468	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1469	// Koh 2 keeps saving a file under a folder pattern added later, where1470	// Koh 3 reads the same rule as covering the folder: the saved file is on1471	// disk and matches, so the tree is clean.1472	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1473	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1474	// Koh 2 skips *.bundle even when its rules no longer list it.1475	ignore_path := os.join_path(dir, '.koh', 'ignore')1476	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1477	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1478	// A saved file the walk skips still has to match what was saved.1479	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1480	changed := run_home(dir, home, 'migrate')1481	assert changed.code == 11482	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1483	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1484	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')14851486	migrated := run_home(dir, home, 'migrate')1487	assert migrated.code == 0, migrated.err1488	// They stay where they were, for the user to keep or delete.1489	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1490}14911492struct FakeKepr {1493	no_access bool1494	// One reply the redemption must cope with: '500', 'garbage' or 'incomplete'.1495	fail string1496	// When set, /api/connect answers 307 here instead of a code reply.1497	redirect_to string1498mut:1499	objects map[string][]u81500	// What the client asked for. A map, because the server holds its own copy of this struct.1501	seen map[string]string1502}15031504fn (mut h FakeKepr) handle(req http.Request) http.Response {1505	if req.method == .post && req.url == '/api/connect' {1506		h.seen['code'] = req.data1507		if h.redirect_to != '' {1508			return http.Response{1509				status_code: 3071510				status_msg:  'Temporary Redirect'1511				header:      http.new_header(1512					key:   .location1513					value: h.redirect_to1514				)1515			}1516		}1517		if h.fail == '500' {1518			return http.Response{ status_code: 500, status_msg: 'Internal Server Error' }1519		}1520		if h.fail == 'garbage' {1521			return http.Response{ status_code: 200, status_msg: 'OK', body: 'not json at all' }1522		}1523		if h.fail == 'incomplete' {1524			return http.Response{ status_code: 200, status_msg: 'OK', body: '{"endpoint":"http://x","bucket":"","region":"","access_key_id":"","secret_access_key":""}' }1525		}1526		if req.data == 'code=good' && !h.no_access {1527			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"}' }1528		}1529		return http.Response{ status_code: 404, status_msg: 'Not Found', body: '{"error":"no_code","message":"no code"}' }1530	}1531	if req.method == .get && req.url.starts_with('/connect') {1532		h.seen['connect'] = req.url1533		return http.Response{ status_code: if h.no_access { 404 } else { 302 }, status_msg: 'Found' }1534	}1535	key := req.url1536	if key.starts_with('/bucket/') {1537		match req.method {1538			.put {1539				if req.header.get_custom('If-None-Match', http.HeaderQueryConfig{}) or { '' } == '*' && key in h.objects {1540					return http.Response{ status_code: 412, status_msg: 'Precondition Failed' }1541				}1542				h.objects[key] = req.data.bytes()1543				return http.Response{ status_code: 200, status_msg: 'OK' }1544			}1545			.get {1546				if body := h.objects[key] {1547					return http.Response{1548						status_code: 2001549						status_msg:  'OK'1550						body:        body.bytestr()1551						header:      http.new_header(1552							key:   .etag1553							value: '"tag"'1554						)1555					}1556				}1557				return http.Response{ status_code: 404, status_msg: 'Not Found' }1558			}1559			.delete {1560				h.objects.delete(key)1561				return http.Response{ status_code: 204, status_msg: 'No Content' }1562			}1563			else {}1564		}1565	}1566	return http.Response{ status_code: 404, status_msg: 'Not Found' }1567}15681569fn start_fake_kepr(no_access bool, fail string, redirect_to string) !(int, &http.Server, &FakeKepr) {1570	for port in 19401 .. 19411 {1571		listener := net.listen_tcp(.ip, '127.0.0.1:${port}') or { continue }1572		fake := &FakeKepr{1573			no_access:   no_access1574			fail:        fail1575			redirect_to: redirect_to1576			seen:        map[string]string{}1577		}1578		mut server := &http.Server{1579			listener:             listener1580			handler:              fake1581			show_startup_message: false1582		}1583		spawn server.listen_and_serve()1584		server.wait_till_running()!1585		return port, server, fake1586	}1587	return error('no free fake Kepr port')1588}15891590// A slash makes an argument an address, so half an address is an error and never a repo name.1591fn test_steal_refuses_an_address_that_is_not_one() {1592	outside := temp_repo('steal-address')1593	home := temp_repo('steal-address-home')1594	defer { os.rmdir_all(outside) or {} }1595	defer { os.rmdir_all(home) or {} }1596	// The repo half becomes a URL path segment and a folder here, so it is a name Kepr serves.1597	for bad in ['kepr.uk/', '/shipped', 'kepr.uk/..', 'kepr.uk/.', 'kepr.uk/a b', 'kepr.uk/nina?x',1598		'kepr.uk/nina#x', 'kepr.uk/nína'] {1599		refused := run_home(outside, home, 'steal', bad)1600		assert refused.code == 1, bad1601		assert refused.err.contains('is not <host>/<repo>'), '${bad}: ${refused.err}'1602	}1603	assert run_home(outside, home, 'steal', 'one', 'two').code == 21604	assert run_home(outside, home, 'steal', '--list', 'extra').code == 21605}16061607fn test_remote_kepr_saves_and_refuses_without_changes() {1608	repo := temp_repo('kepr')1609	home := temp_repo('kepr-home')1610	defer { os.rmdir_all(repo) or {} }1611	defer { os.rmdir_all(home) or {} }1612	init_repo(repo)1613	port, mut server, fake := start_fake_kepr(false, '', '')!1614	defer { server.stop() }1615	host := 'http://127.0.0.1:${port}'1616	// A trailing slash is the same host, and the saved line keeps the normalised form.1617	good := run_home(repo, home, 'remote', '${host}/', '--code', 'good')1618	assert good.code == 0, good.err1619	remote_path := os.join_path(home, '.config', 'koh', 'remote')1620	credentials_path := os.join_path(home, '.config', 'koh', 'credentials')1621	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'1622	assert os.read_file(credentials_path)! == '# written by koh remote — keep this file private\naccess_key=access\nsecret_key=secret\n'1623	// The code went as a form field, and the connect page was never asked for: there was a code.1624	assert (fake.seen['code'] or { '' }) == 'code=good'1625	assert (fake.seen['connect'] or { '' }) == ''1626	// A refused code, a missing terminal and a wrong reply all leave both files as they were.1627	before := os.read_file(remote_path)!1628	before_keys := os.read_file(credentials_path)!1629	bad := run_home(repo, home, 'remote', host, '--code', 'bad')1630	assert bad.code == 11631	assert bad.err.contains('wrong or has expired')1632	// The 404 could also mean a Kepr that hands out nothing, so the connect page is asked for1633	// with this machine's name. (This machine's name holds no character needing an escape, so1634	// that part of the query cannot be exercised here.)1635	// `machine.name()` is `os.hostname() or { 'unknown' }`, so the query carries the same text.1636	assert (fake.seen['connect'] or { '' }).contains('machine=${os.hostname() or { 'unknown' }}')1637	no_terminal := run_home(repo, home, 'remote', host)1638	assert no_terminal.code == 11639	assert no_terminal.err.contains('needs a terminal')1640	assert os.read_file(remote_path)! == before1641	assert os.read_file(credentials_path)! == before_keys1642}16431644fn test_remote_kepr_refuses_hosts_that_are_not_hosts() {1645	repo := temp_repo('kepr-host')1646	home := temp_repo('kepr-host-home')1647	defer { os.rmdir_all(repo) or {} }1648	defer { os.rmdir_all(home) or {} }1649	init_repo(repo)1650	for host in ['kepr.uk/foo', 'https://kepr.uk?x=1', 'kepr.uk#frag', '[email protected]', 'kepr uk',1651		'http://127.0.0.1:1/foo', 'https://'] {1652		refused := run_home(repo, home, 'remote', host, '--code', 'good')1653		assert refused.code == 1, host1654		assert refused.err.contains('is not a Kepr address'), '${host}: ${refused.err}'1655	}1656	// The reply carries the bucket's secret key, so plain http is only for this machine's own Kepr.1657	for host in ['http://kepr.uk', 'http://10.0.0.2:3000', 'http://KEPR.uk:80'] {1658		refused := run_home(repo, home, 'remote', host, '--code', 'good')1659		assert refused.code == 1, host1660		assert refused.err.contains('needs https'), '${host}: ${refused.err}'1661		stolen := run_home(home, home, 'steal', '${host}/nina')1662		assert stolen.code == 1, host1663		assert stolen.err.contains('needs https'), '${host}: ${stolen.err}'1664	}1665	// --code belongs to the host form alone.1666	assert run_home(repo, home, 'remote', 's3', 'https://x', 'b', 'r', '--code', 'good').code == 21667	assert run_home(repo, home, 'remote', 'folder', '/tmp', '--code', 'good').code == 21668	assert run_home(repo, home, 'remote', '--code', 'good').code == 21669	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1670}16711672fn test_remote_kepr_refuses_what_is_not_a_code_reply() {1673	repo := temp_repo('kepr-reply')1674	home := temp_repo('kepr-reply-home')1675	defer { os.rmdir_all(repo) or {} }1676	defer { os.rmdir_all(home) or {} }1677	init_repo(repo)1678	remote_path := os.join_path(home, '.config', 'koh', 'remote')1679	for mode in ['500', 'garbage', 'incomplete'] {1680		port, mut server, _ := start_fake_kepr(false, mode, '')!1681		refused := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1682		server.stop()1683		assert refused.code == 1, mode1684		assert refused.err.contains('nothing was changed'), '${mode}: ${refused.err}'1685		assert !os.exists(remote_path)1686	}1687	// A redirect would hand the code to wherever it points, so it is refused and never followed.1688	target_port, mut target, target_fake := start_fake_kepr(false, '', '')!1689	port, mut server, _ := start_fake_kepr(false, '', 'http://127.0.0.1:${target_port}/api/connect')!1690	redirected := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1691	server.stop()1692	target.stop()1693	assert redirected.code == 11694	assert redirected.err.contains('refused the code')1695	assert target_fake.seen.len == 0, 'the code was forwarded: ${target_fake.seen}'1696	assert !os.exists(remote_path)1697}16981699// An unreachable Kepr is a refusal too, and the settings are still untouched.1700fn test_remote_kepr_that_cannot_be_reached_changes_nothing() {1701	repo := temp_repo('kepr-down')1702	home := temp_repo('kepr-down-home')1703	defer { os.rmdir_all(repo) or {} }1704	defer { os.rmdir_all(home) or {} }1705	init_repo(repo)1706	refused := run_home(repo, home, 'remote', 'http://127.0.0.1:1', '--code', 'good')1707	assert refused.code == 11708	assert refused.err.contains('could not reach Kepr')1709	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1710}17111712fn test_remote_kepr_without_bucket_access_is_explained() {1713	repo := temp_repo('kepr-no-access')1714	home := temp_repo('kepr-no-access-home')1715	defer { os.rmdir_all(repo) or {} }1716	defer { os.rmdir_all(home) or {} }1717	init_repo(repo)1718	port, mut server, _ := start_fake_kepr(true, '', '')!1719	defer { server.stop() }1720	r := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'bad')1721	assert r.code == 11722	assert r.err.contains("doesn't hand out bucket access")1723	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1724}