cli_test.v

68.6 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}6970// shown is what a terminal leaves on screen: on each line, only what follows its71// last carriage return, so a progress line cleared in place does not count.72fn shown(out string) []string {73	return out.split('\n').map(it.trim_right('\r').all_after_last('\r')).filter(it.trim_space() != '')74}7576fn run_pty_home(repo string, home string, answers []string, args ...string) Result {77	stamp := '${os.getpid()}-${time.now().unix_nano()}'78	transcript := os.join_path(os.temp_dir(), 'koh3-pty-${stamp}.txt')79	script_path := os.join_path(os.temp_dir(), 'koh3-pty-${stamp}.exp')80	defer {81		os.rm(transcript) or {}82		os.rm(script_path) or {}83	}84	mut script := 'log_file -noappend {${transcript}}\nset timeout 20\nspawn -noecho env {HOME=${home}} NO_COLOR=1 {${binary}}'85	for arg in args {86		script += ' {${arg}}'87	}88	script += '\n'89	// Each answer waits for its prompt: typed ahead, it would be flushed when the pager takes the90	// terminal raw. `close` ends a run that is still asking, so `wait` can never hang the suite.91	for answer in answers {92		script += 'expect -re {› \$|message: \$|confirm: \$|\\[y/N\\] \$|q quit}\nsend -- "${answer}\\r"\n'93	}94	script += 'expect eof\ncatch close\nset status [wait]\nexit [lindex $status 3]\n'95	os.write_file(script_path, script) or { panic(err) }96	result := os.execute('cd ${q(repo)} && expect -f ${q(script_path)}')97	return Result{98		code: result.exit_code99		out:  os.read_file(transcript) or { '' }100		err:  result.output101	}102}103104fn init_repo(repo string) {105	r := run(repo, 'init')106	assert r.code == 0107	assert os.exists(os.join_path(repo, '.koh'))108	assert os.exists(os.join_path(repo, '.kohignore'))109}110111fn write(repo string, path string, text string) {112	full := os.join_path(repo, path)113	os.mkdir_all(os.dir(full)) or { panic(err) }114	os.write_file(full, text) or { panic(err) }115}116117fn read_json_has(text string, key string) {118	if !text.contains(key) {119		panic('missing JSON key ${key}: ${text}')120	}121}122123fn test_init_and_usage() {124	dir := temp_repo('init')125	defer { os.rmdir_all(dir) or {} }126	r := run(dir, 'init', '--json')127	assert r.code == 0128	read_json_has(r.out, 'repo')129	read_json_has(r.out, 'ignore_created')130	assert run(dir, 'init').code == 1131	assert run(dir, 'unknown-command').code == 2132	assert run(dir, 'unknown-command').err.contains('unknown command')133	// An agent asking for JSON gets JSON for a usage mistake too, exit 2.134	for args in [['unknown-command', '--json'], ['save', '--json'], ['save', 'x', '--nope', '--json']] {135		r2 := run(dir, ...args)136		assert r2.code == 2137		assert r2.out == ''138		assert r2.err.starts_with('{"error":'), r2.err139	}140}141142// The help screen is commands and plain words: every flag lives in `koh man`.143// this_platform is the platform name for the machine the tests run on, so a144// build test does not depend on which machine that is.145fn this_platform() string {146	machine := os.uname().machine147	arch := if machine in ['arm64', 'aarch64'] { 'aarch64' } else { 'x86_64' }148	return '${os.user_os()}-${arch}'149}150151// `koh build` builds with `koh.build`: the version and platform fill the output152// path, and each artifact is printed with its size.153fn test_build_builds_the_named_platforms() {154	dir := temp_repo('build_ok')155	defer { os.rmdir_all(dir) or {} }156	init_repo(dir)157	host := this_platform()158	write(dir, 'VERSION', '1.2.3\n')159	write(dir, 'koh.build', 'command = mkdir -p out && printf built > out/demo-1.2.3-${host}160output = out/demo-{version}-{platform}161platforms = ${host}162')163	one := run(dir, 'build')164	assert one.code == 0, one.err165	assert one.out.contains('version 1.2.3')166	assert one.out.contains('out/demo-1.2.3-${host}')167	assert os.exists(os.join_path(dir, 'out/demo-1.2.3-${host}'))168169	// --platform picks one, --all takes every platform the file names.170	write(dir, 'koh.build', 'command = mkdir -p out && printf m > out/demo-macos-aarch64 && printf l > out/demo-linux-aarch64171output = out/demo-{platform}172platforms = macos-aarch64, linux-aarch64173')174	all := run(dir, 'build', '--all', '--json')175	assert all.code == 0, all.err176	assert all.out.contains('"platform":"macos-aarch64"')177	assert all.out.contains('"platform":"linux-aarch64"')178	assert os.exists(os.join_path(dir, 'out/demo-linux-aarch64'))179	picked := run(dir, 'build', '--platform', 'linux-aarch64')180	assert picked.code == 0, picked.err181	assert picked.out.contains('out/demo-linux-aarch64')182	assert !picked.out.contains('out/demo-macos-aarch64')183}184185// The item's exit check, as a test: `koh build` builds Koh 3 itself with the186// real toolchain, in a copy, and the binary it produces runs.187// `koh update` refuses a command line that cannot be answered: JSON cannot carry188// the question, and a stray argument is a mistake. Both are settled before any189// source is read, so no network is needed here.190fn test_update_refuses_a_command_line_it_cannot_answer() {191	dir := temp_repo('update_args')192	defer { os.rmdir_all(dir) or {} }193	init_repo(dir)194	json_without_yes := run(dir, 'update', '--json')195	assert json_without_yes.code == 2196	assert json_without_yes.err.contains('needs --yes')197	assert run(dir, 'update', 'extra').code == 2198}199200fn test_build_builds_koh_itself() {201	dir := temp_repo('selfbuild')202	defer { os.rmdir_all(dir) or {} }203	// Only what a build reads: the copy needs no history and no archive.204	for item in ['src', 'vendor', 'docs', 'v.mod', 'VERSION'] {205		os.cp_all(os.join_path(root, item), os.join_path(dir, item), true) or { panic(err) }206	}207	write(dir, 'koh.build', 'command = mkdir -p zig-out/bin && v -o zig-out/bin/koh3 src/koh3.v208output = zig-out/bin/koh3209platforms = ${this_platform()}210')211	init_repo(dir)212	built := run(dir, 'build')213	assert built.code == 0, built.err214	assert built.out.contains('zig-out/bin/koh3')215	fresh := os.join_path(dir, 'zig-out/bin/koh3')216	assert os.exists(fresh)217	version := os.read_file(os.join_path(dir, 'VERSION'))!.trim_space()218	assert os.execute('${q(fresh)} --version').output.trim_space() == 'koh ${version}'219}220221fn test_build_refuses_what_it_cannot_do() {222	dir := temp_repo('build_bad')223	defer { os.rmdir_all(dir) or {} }224	init_repo(dir)225	missing := run(dir, 'build')226	assert missing.code == 1227	assert missing.err.contains('koh.build')228229	write(dir, 'koh.build', 'command = true230output = out/demo231platforms = macos-aarch64232')233	no_version := run(dir, 'build')234	assert no_version.code == 1235	assert no_version.err.contains('VERSION')236237	write(dir, 'VERSION', '1.2.3\n')238	not_listed := run(dir, 'build', '--platform', 'linux-aarch64')239	assert not_listed.code == 1240	assert not_listed.err.contains('does not build for')241242	unknown := run(dir, 'build', '--platform', 'amiga')243	assert unknown.code == 1244	assert unknown.err.contains('amiga')245246	both := run(dir, 'build', '--all', '--platform', 'macos-aarch64')247	assert both.code == 2248	assert both.err.contains('cannot be combined')249250	write(dir, 'koh.build', 'command = true251output = out/demo252platforms = macos-aarch64, amiga253')254	bad_platform := run(dir, 'build')255	assert bad_platform.code == 1256	assert bad_platform.err.contains('amiga')257258	write(dir, 'koh.build', 'command = sh -c \'echo "no toolchain" >&2; exit 1\'259output = out/demo260platforms = ${this_platform()}261')262	failed := run(dir, 'build')263	assert failed.code == 1264	assert failed.err.contains('no toolchain')265}266267fn test_the_help_screen_lists_commands_and_no_flags() {268	dir := temp_repo('help')269	defer { os.rmdir_all(dir) or {} }270	help := run(dir, '--help')271	assert help.code == 0272	names := ['save', 'checkpoint', 'status', 'view', 'diff', 'undo', 'revert', 'load', 'offer',273		'steal']274	for name in names {275		assert help.out.contains('  ${name} '), name276	}277	assert help.out.contains('koh man <command>')278	assert help.out.contains('  status      where things stand\n')279	assert help.out.contains('  diff        what changed\n')280	assert help.out.contains('Asha Software · asha.software')281	// No flag text anywhere on the screen.282	assert !help.out.contains('--'), help.out283	lines := help.out.split_into_lines()284	for line in lines {285		assert line.runes().len <= 80, line286	}287	// Each command has its own paragraph, a blank line above it.288	for name in names {289		for i, line in lines {290			if line.starts_with('  ${name} ') {291				assert i > 0 && lines[i - 1] == '', line292			}293		}294	}295	// A bare `koh` keeps its stream and exit code; `-h` shows the same screen.296	bare := run(dir)297	assert bare.code == 2298	assert bare.out == ''299	assert bare.err.contains('koh man <command>')300	short := run(dir, '-h')301	assert short.code == 0302	assert short.out == help.out303}304305// Colour on the screen follows NO_COLOR, as it does everywhere else.306fn test_the_help_screen_has_no_colour_when_it_is_off() {307	dir := temp_repo('help_plain')308	defer { os.rmdir_all(dir) or {} }309	home := temp_repo('help_plain_home')310	defer { os.rmdir_all(home) or {} }311	out_path := os.join_path(os.temp_dir(), 'koh3-help-${os.getpid()}-${time.now().unix_nano()}')312	defer { os.rm(out_path) or {} }313	code := os.system('cd ${q(dir)} && HOME=${q(home)} NO_COLOR=1 ${q(binary)} --help > ${q(out_path)}')314	assert code == 0315	text := os.read_file(out_path) or { panic(err) }316	assert !text.contains('\x1b'), text317	assert text.contains('  save        snapshot your work')318}319320// The binary embeds VERSION while saves bump v.mod; they drifted once.321fn test_version_matches_the_manifest() {322	dir := temp_repo('version')323	defer { os.rmdir_all(dir) or {} }324	version := run(dir, '--version').out.trim_space().all_after('koh ')325	manifest := os.read_file(os.join_path(root, 'v.mod')) or { panic(err) }326	assert manifest.contains("version: '${version}'"), version327}328329fn test_save_checkpoint_and_status() {330	dir := temp_repo('save')331	defer { os.rmdir_all(dir) or {} }332	init_repo(dir)333	write(dir, 'tracked.txt', 'one\n')334	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')335	assert r.code == 0336	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent', 'session',337		'files', 'size_bytes'] {338		read_json_has(r.out, key)339	}340	assert r.out.contains('"message":"first message"')341	assert r.out.contains('"agent":"agent-7"')342	assert r.out.contains('"session":"session-a"')343	assert r.out.contains('"is_checkpoint":false')344	assert run(dir, 'save', 'again').code == 1345	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')346	assert run(dir, 'save').code == 2347	assert run(dir, 'save', 'x', '--bogus').code == 2348	cp := run(dir, 'checkpoint', 'still first', '--json')349	assert cp.code == 0350	assert cp.out.contains('"is_checkpoint":true')351	assert cp.out.contains('"parent":')352	clean := run(dir, 'status')353	assert clean.code == 0354	assert clean.out.contains('no changes')355	write(dir, 'tracked.txt', 'two\n')356	write(dir, 'new.txt', 'new\n')357	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }358	write(dir, '.kohignore', '*.log\n')359	status := run(dir, 'status')360	assert status.code == 0361	assert status.out.contains('+')362	assert status.out.contains('~') || status.out.contains('-')363	assert status.out.contains('added')364	js := run(dir, 'status', '--json')365	assert js.code == 0366	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed',367		'saves', 'size_bytes', 'head_flagged'] {368		read_json_has(js.out, key)369	}370	assert js.out.contains('"ignore_changed":true')371	// What the shell prompt shows: saves on the line, the .koh size, the flag.372	assert js.out.contains('"saves":2')373	assert js.out.contains('"size_bytes":${os.file_size(os.join_path(dir, '.koh'))}')374	assert js.out.contains('"head_flagged":false')375	head := js.out.all_after('"head_id":"').all_before('"')376	assert run(dir, 'flag', head, '--reason', 'bad').code == 0377	assert run(dir, 'status', '--json').out.contains('"head_flagged":true')378}379380fn test_status_requires_repo_and_ignore_rules() {381	dir := temp_repo('status')382	defer { os.rmdir_all(dir) or {} }383	assert run(dir, 'status').code == 1384	init_repo(dir)385	write(dir, '.kohignore', '*.log\nbuild/\n')386	write(dir, 'keep.txt', 'keep\n')387	write(dir, 'ignored.log', 'ignore\n')388	write(dir, 'build/output.txt', 'ignore\n')389	saved := run(dir, 'save', 'keep', '--json')390	assert saved.code == 0391	id := saved.out.all_after('"id":"')[..12]392	// Where things stand comes first, clean or not.393	clean := run(dir, 'status').out394	assert clean.contains('at [${id}] keep · '), clean395	assert clean.contains(' · 1 save\n'), clean396	assert clean.contains('no changes')397	write(dir, 'keep.txt', 'changed\n')398	assert run(dir, 'status').out.contains('at [${id}] keep · ')399	write(dir, 'keep.txt', 'keep\n')400	assert !run(dir, 'status').out.contains('ignored.log')401	assert !run(dir, 'status').out.contains('build/output.txt')402	assert !run(dir, 'status').out.contains('LOG.md')403}404405fn test_status_and_save_report_unsafe_names_without_refusing_the_save() {406	dir := temp_repo('unsafe-names')407	defer { os.rmdir_all(dir) or {} }408	init_repo(dir)409	write(dir, 'safe.txt', 'safe\n')410	assert run(dir, 'save', 'safe').code == 0411	os.write_file('${dir}/bad\\name.txt', 'bad\n') or { panic(err) }412	os.write_file('${dir}/Icon\r', 'icon\n') or { panic(err) }413414	status := run(dir, 'status', '--json')415	assert status.code == 0416	assert status.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), status.out417	saved := run(dir, 'checkpoint', 'unsafe names', '--json')418	assert saved.code == 0419	assert saved.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), saved.out420}421422// LOG.md is a convenience written after the save lands. If it cannot be423// written, the save still happened, and an agent that retried on a failure424// would only be told nothing had changed.425fn test_a_save_succeeds_when_log_md_cannot_be_written() {426	dir := temp_repo('logmd')427	defer { os.rmdir_all(dir) or {} }428	init_repo(dir)429	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }430	write(dir, 'a.txt', 'one\n')431	r := run(dir, 'save', 'first', '--json')432	assert r.code == 0433	assert r.out.starts_with('{')434	assert r.err.contains('LOG.md')435	assert run(dir, 'view', '--json').out.contains('"message":"first"')436}437438// A folder of ignored files can sit where a restored file should go. Koh439// never touches ignored files, so the restore must stop and say so, not drop440// the file inside the folder under a temporary name.441fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {442	dir := temp_repo('dir-in-way')443	defer { os.rmdir_all(dir) or {} }444	init_repo(dir)445	write(dir, 'out', 'a file\n')446	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]447	os.rm(os.join_path(dir, 'out')) or { panic(err) }448	write(dir, 'out/build.log', 'ignored\n')449	assert run(dir, 'save', 'out is gone').code == 0450	r := run(dir, 'load', first, '--yes')451	assert r.code == 1452	assert r.err.contains('out')453	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']454}455456// Koh never follows a symlink, so a folder replaced by a link to somewhere457// else is not the repo's to write into: restoring through it would overwrite458// files outside the repo. The refusal comes before anything is recorded.459fn test_a_restore_never_writes_through_a_symlinked_folder() {460	dir := temp_repo('link-in-way')461	outside := temp_repo('link-target')462	defer {463		os.rmdir_all(dir) or {}464		os.rmdir_all(outside) or {}465	}466	init_repo(dir)467	write(dir, 'docs/a.md', 'saved\n')468	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]469	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }470	write(outside, 'a.md', 'precious\n')471	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }472	assert run(dir, 'save', 'docs is a link now').code == 0473	head := run(dir, 'status', '--json').out474	r := run(dir, 'load', first, '--yes')475	assert r.code == 1476	assert r.err.contains('docs')477	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'478	assert run(dir, 'status', '--json').out == head479}480481// A restore records its save first, then writes files. When the writing stops482// part way, the half-written tree is not somebody's work: saving it would483// record (and offer) a tree that undoes changes nobody asked to undo. Every484// command that would build on it points at revert, which finishes the job.485fn test_a_restore_cut_short_points_at_revert() {486	dir := temp_repo('cut-short')487	defer {488		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}489		os.rmdir_all(dir) or {}490	}491	init_repo(dir)492	write(dir, 'zero', '0\n')493	assert run(dir, 'save', 'zero').code == 0494	write(dir, 'a.txt', 'v1\n')495	write(dir, 'zz/f', 'v1\n')496	assert run(dir, 'save', 'first').code == 0497	write(dir, 'a.txt', 'v2\n')498	write(dir, 'zz/f', 'v2\n')499	assert run(dir, 'save', 'second').code == 0500	// a.txt is written, then the read-only folder stops the restore: the501	// tree is genuinely half one save and half the other.502	os.chmod(os.join_path(dir, 'zz'), 0o555)!503	stopped := run(dir, 'undo', '--yes')504	assert stopped.code == 1505	assert stopped.err.contains('koh revert')506	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'507	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'508	// Even a status that cannot read the tree says what happened.509	os.chmod(os.join_path(dir, 'zz'), 0o000)!510	assert run(dir, 'status').err.contains('koh revert')511	os.chmod(os.join_path(dir, 'zz'), 0o755)!512513	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')514	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {515		r := run(dir, ...args)516		assert r.code == 1517		assert r.err.contains('koh revert')518	}519	assert run(dir, 'revert', '--yes').code == 0520	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'521	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'522	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')523	write(dir, 'a.txt', 'v3\n')524	assert run(dir, 'save', 'carry on').code == 0525}526527// Doctor clears peek folders left from earlier days, never one somebody may528// be reading right now.529fn test_doctor_sweeps_only_old_peek_folders() {530	dir := temp_repo('peek-sweep')531	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in532	// the real temp directory under names no save could have.533	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')534	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')535	defer {536		os.rmdir_all(dir) or {}537		os.rmdir_all(fresh) or {}538		os.rmdir_all(old) or {}539	}540	init_repo(dir)541	write(dir, 'a.txt', 'one\n')542	assert run(dir, 'save', 'one').code == 0543	os.mkdir_all(fresh) or { panic(err) }544	os.mkdir_all(old) or { panic(err) }545	two_days_ago := time.now().unix() - 2 * 86400546	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }547	assert run(dir, 'doctor', '--json').code == 0548	assert os.exists(fresh)549	assert !os.exists(old)550}551552// A file saved long ago and ignored since holds work no save has. Loading the553// old save must not write over it; the document says a restore never touches554// ignored files.555fn test_a_restore_never_overwrites_an_ignored_file() {556	dir := temp_repo('ignored-restore')557	defer { os.rmdir_all(dir) or {} }558	init_repo(dir)559	write(dir, '.env', 'KEY=saved long ago\n')560	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]561	write(dir, '.kohignore', '.env\n')562	assert run(dir, 'save', 'ignore env').code == 0563	write(dir, '.env', 'KEY=never saved\n')564	assert run(dir, 'load', first, '--yes').code == 0565	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'566567	// Where the ignored file is missing, the restore still brings it back.568	other := temp_repo('ignored-restore-missing')569	defer { os.rmdir_all(other) or {} }570	init_repo(other)571	write(other, '.env', 'KEY=saved long ago\n')572	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]573	write(other, '.kohignore', '.env\n')574	assert run(other, 'save', 'ignore env').code == 0575	os.rm(os.join_path(other, '.env')) or { panic(err) }576	assert run(other, 'load', again, '--yes').code == 0577	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'578}579580// A going-back preview lists paths only. Running diff(1) per file to draw it581// cost 27 s for 5,000 changed files, so it must not run diff at all.582fn test_a_going_back_preview_does_not_run_diff() {583	dir := temp_repo('preview-nodiff')584	home := temp_repo('preview-nodiff-home')585	defer {586		os.rmdir_all(dir) or {}587		os.rmdir_all(home) or {}588	}589	init_repo(dir)590	write(dir, 'a.txt', 'one\n')591	assert run_home(dir, home, 'save', 'one').code == 0592	write(dir, 'a.txt', 'two\n')593	assert run_home(dir, home, 'save', 'two').code == 0594	fake := os.join_path(home, 'bin')595	os.mkdir_all(fake) or { panic(err) }596	marker := os.join_path(home, 'diff-ran')597	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {598		panic(err)599	}600	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }601	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0602	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'603	assert !os.exists(marker)604}605606// A restore rewrites only what differs. Rewriting every file resets every607// mtime, so the next status has to hash the whole tree again.608fn test_a_restore_leaves_unchanged_files_alone() {609	dir := temp_repo('restore-skip')610	defer { os.rmdir_all(dir) or {} }611	init_repo(dir)612	write(dir, 'a.txt', 'one\n')613	write(dir, 'same.txt', 'never changes\n')614	assert run(dir, 'save', 'one').code == 0615	write(dir, 'a.txt', 'two\n')616	assert run(dir, 'save', 'two').code == 0617	long_ago := i64(1700000000)618	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }619	assert run(dir, 'undo', '--yes').code == 0620	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'621	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago622}623624// `save` records the executable bit, so `status` has to see it too, or a625// chmod would be invisible until it turned up in a save.626fn test_status_sees_an_executable_bit_change() {627	dir := temp_repo('chmod')628	defer { os.rmdir_all(dir) or {} }629	init_repo(dir)630	write(dir, 'run.sh', 'echo hi\n')631	assert run(dir, 'save', 'script').code == 0632	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }633	status := run(dir, 'status', '--json')634	assert status.out.contains('"dirty":true')635	assert status.out.contains('"modified":["run.sh"]')636}637638fn test_view_and_diff() {639	dir := temp_repo('history')640	defer { os.rmdir_all(dir) or {} }641	init_repo(dir)642	write(dir, 'a.txt', 'one\n')643	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')644	id1 := first.out.all_after('"id":"')[..12]645	write(dir, 'a.txt', 'two\n')646	second := run(dir, 'save', 'two', '--session', 'beta', '--json')647	id2 := second.out.all_after('"id":"')[..12]648	cp := run(dir, 'checkpoint', 'checkpoint', '--json')649	assert cp.code == 0650	printed := run(dir, 'view')651	assert printed.code == 0652	assert printed.out.contains('▸')653	assert printed.out.contains('◐')654	lj := run(dir, 'view', '--json')655	assert lj.code == 0656	assert lj.out.contains('"head_id"')657	assert lj.out.contains('"saves"')658	assert run(dir, 'view', '--since', 'today').out.contains('two')659	session := run(dir, 'view', '--session', 'alpha')660	assert session.out.contains('one')661	assert !session.out.contains('two')662	assert run(dir, 'view', '--since', '9999-01-01').out.contains('no saves in that range')663	write(dir, 'a.txt', 'three\n')664	d := run(dir, 'diff')665	assert d.code == 0666	assert d.out.contains('--- a/')667	assert d.out.contains('+++ b/')668	assert run(dir, 'diff', id1).code == 0669	assert run(dir, 'diff', id1, id2).code == 0670	dj := run(dir, 'diff', '--json')671	assert dj.code == 0672	assert dj.out.contains('"from"')673	assert dj.out.contains('"to"')674	assert dj.out.contains('"files"')675	assert dj.out.contains('"change":"modified"')676	assert run(dir, 'diff', 'not-a-real-id').code == 1677	assert run(dir, 'diff', id1, id2, 'third').code == 1678	write(dir, 'blob.bin', '\x00\x01\x02')679	diff_binary := run(dir, 'diff', '--json')680	assert diff_binary.out.contains('"binary":true')681	assert diff_binary.out.contains('Binary files differ')682}683684fn test_undo_revert_and_load() {685	dir := temp_repo('restore')686	defer { os.rmdir_all(dir) or {} }687	init_repo(dir)688	write(dir, 'a.txt', 'one\n')689	one := run(dir, 'save', 'one', '--json').out690	id1 := one.all_after('"id":"')[..12]691	write(dir, 'a.txt', 'two\n')692	write(dir, 'gone.txt', 'gone\n')693	second := run(dir, 'save', 'two', '--json').out694	id2 := second.all_after('"id":"')[..12]695	write(dir, 'a.txt', 'three\n')696	third := run(dir, 'save', 'three', '--json').out697	id3 := third.all_after('"id":"')[..12]698	// Unsaved work — here a file never saved — blocks every going-back but699	// revert, as in Koh 2: a restore must never overwrite what only the disk has.700	write(dir, 'never.txt', 'keep me\n')701	view_before := run(dir, 'view').out702	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {703		blocked := run(dir, ...args)704		assert blocked.code == 1705		assert blocked.err.contains('unsaved changes')706	}707	assert run(dir, 'view').out == view_before708	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }709	write(dir, 'a.txt', 'edited, never saved\n')710	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')711	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'712	write(dir, 'a.txt', 'three\n')713	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }714	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')715	write(dir, 'gone.txt', 'gone\n')716	undo := run(dir, 'undo', '--yes', '--json')717	assert undo.code == 0718	if !undo.out.contains(id2) {719		panic('undo JSON did not name ${id2}: ${undo.out}')720	}721	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'722	assert os.exists(os.join_path(dir, 'gone.txt'))723	assert run(dir, 'load', id3, '--yes').code == 0724	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'725	assert run(dir, 'undo', '2', '--yes').code == 0726	assert run(dir, 'load', id2, '--yes').code == 0727	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')728	write(dir, 'a.txt', 'dirty\n')729	before := run(dir, 'view')730	refuse := run(dir, 'revert')731	assert refuse.code == 1732	assert refuse.err.contains('needs --yes when not interactive')733	assert run(dir, 'view').out == before.out734	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'735	write(dir, 'untracked.txt', 'remove\n')736	rv := run(dir, 'revert', '--yes', '--json')737	assert rv.code == 0738	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'739	assert !os.exists(os.join_path(dir, 'untracked.txt'))740	// The way back to the discarded work is named, not left to be found.741	kept := rv.out.all_after('"checkpoint":"')[..12]742	assert run(dir, 'load', kept, '--yes').code == 0743	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'744	assert os.read_file(os.join_path(dir, 'untracked.txt'))! == 'remove\n'745	write(dir, 'a.txt', 'dirty again\n')746	assert run(dir, 'revert', '--yes').out.contains('koh load ')747	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')748	assert run(dir, 'load', '--checkpoint', '--yes').code == 0749	assert run(dir, 'load', id2, '--json').code == 1750	assert run(dir, 'load', id2, '--json').err.contains('error')751	assert run(dir, 'load').code == 2752	assert run(dir, 'load', 'unknown-id', '--yes').code == 1753}754755fn test_flag_and_flagged_view() {756	dir := temp_repo('flag')757	defer { os.rmdir_all(dir) or {} }758	init_repo(dir)759	write(dir, 'flag.txt', 'one\n')760	saved := run(dir, 'save', 'flag me', '--json')761	id := saved.out.all_after('"id":"')[..12]762	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')763	assert flagged.code == 0764	assert flagged.out.contains('"flagged":true')765	assert flagged.out.contains('"reason":"unsafe"')766	list := run(dir, 'flag', '--json')767	assert list.code == 0768	assert list.out.contains(id)769	assert list.out.contains('unsafe')770	assert run(dir, 'view').out.contains('⚑')771	assert run(dir, 'flag', '--clear', id).code == 0772	assert run(dir, 'flag').out.contains('nothing is flagged')773	assert run(dir, 'flag', 'unknown-id').code == 1774	assert run(dir, 'flag').code == 0775}776777fn test_pluck_forward_reverse_dry_run_and_conflict() {778	dir := temp_repo('pluck')779	defer { os.rmdir_all(dir) or {} }780	init_repo(dir)781	write(dir, 'a.txt', 'one\n')782	first := run(dir, 'save', 'one', '--json').out783	id1 := first.all_after('"id":"')[..12]784	write(dir, 'a.txt', 'two\n')785	second := run(dir, 'save', 'two', '--json').out786	id2 := second.all_after('"id":"')[..12]787	assert run(dir, 'load', id1, '--yes').code == 0788	dry := run(dir, 'pluck', id2, '--dry-run')789	assert dry.code == 0790	assert dry.out.contains('a.txt')791	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'792	assert run(dir, 'pluck', id2, '--yes').code == 0793	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'794	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0795	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'796	write(dir, 'a.txt', 'different\n')797	assert run(dir, 'pluck', id2, '--dry-run').code == 1798	assert run(dir, 'save', 'different').code == 0799	conflict := run(dir, 'pluck', id2, '--yes')800	assert conflict.code == 1801	assert conflict.err.contains('a.txt')802	assert run(dir, 'pluck').code == 2803	assert run(dir, 'pluck', 'unknown-id').code == 1804}805806fn test_peek_and_doctor() {807	dir := temp_repo('peek-doctor')808	defer { os.rmdir_all(dir) or {} }809	init_repo(dir)810	write(dir, 'peek.txt', 'peek me\n')811	assert run(dir, 'save', 'peekable').code == 0812	id := run(dir, 'view', '--json').out.all_after('"id":"')[..12]813	before_view := run(dir, 'view', '--json').out814	peek := run(dir, 'peek', id, '--json')815	assert peek.code == 0816	peek_path := peek.out.all_after('"path":"').before('"')817	assert peek.out.contains('"id":"${id}"')818	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'819	assert run(dir, 'status').out.contains('no changes')820	assert run(dir, 'view', '--json').out == before_view821	assert run(dir, 'peek').code == 2822	assert run(dir, 'peek', 'unknown-id').code == 1823	backup := os.join_path(dir, 'doctor.backup')824	healthy := run(dir, 'doctor')825	assert healthy.code == 0826	assert healthy.out.contains('is sound')827	report := run(dir, 'doctor', '--json')828	assert report.code == 0829	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',830		'backup'] {831		read_json_has(report.out, key)832	}833	backed := run(dir, 'doctor', '--backup', backup)834	assert backed.code == 0835	assert os.exists(backup)836	assert backed.out.contains(backup)837	assert run(dir, 'doctor', '--backup', backup).code == 1838	assert run(dir, 'peek', id, '--json').code == 0839	// A peek made today is left for whoever is reading it.840	kept := run(dir, 'doctor', '--json')841	assert kept.code == 0842	assert os.exists(peek_path)843	os.rmdir_all(peek_path) or {}844}845846fn test_strip_refuses_without_terminal() {847	dir := temp_repo('strip')848	defer { os.rmdir_all(dir) or {} }849	init_repo(dir)850	write(dir, 'secret.txt', 'keep\n')851	assert run(dir, 'save', 'secret').code == 0852	before_view := run(dir, 'view', '--json').out853	refused := run(dir, 'strip', 'secret.txt')854	assert refused.code == 1855	assert refused.err.contains('needs a terminal')856	assert run(dir, 'view', '--json').out == before_view857	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'858	assert run(dir, 'view', '--json').out.contains('secret')859}860861// A whole-history strip bans the path: `.kohignore` names it, once, and the file left on disk862// is never unsaved work or part of a save again.863fn test_strip_adds_the_path_to_kohignore_and_it_stays_out() {864	dir := temp_repo('strip-ignore')865	home := temp_repo('strip-ignore-home')866	defer { os.rmdir_all(dir) or {} }867	defer { os.rmdir_all(home) or {} }868	init_repo(dir)869	write(dir, 'secret.txt', 'leaked\n')870	write(dir, 'keep.txt', 'fine\n')871	assert run_home(dir, home, 'save', 'leak').code == 0872	stripped := run_pty_home(dir, home, ['y', 'secret.txt'], 'strip', 'secret.txt')873	assert stripped.code == 0, stripped.out874	assert stripped.out.contains('added /secret.txt to .kohignore')875	ignore_path := os.join_path(dir, '.kohignore')876	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1877	assert run_home(dir, home, 'save', 'ignore the stripped secret').code == 0878	write(dir, 'secret.txt', 'leaked again\n')879	assert run_home(dir, home, 'status', '--json').out.contains('"dirty":false')880	// Running the strip again (with no remote, it stays pending) adds no second line.881	again := run_pty_home(dir, home, [], 'strip', 'secret.txt')882	assert again.code == 0, again.out883	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1884}885886// `koh view` is the one way into the history: the whole line by default,887// checkpoints alone with the flag, and the two lists never overlap.888fn test_view_shows_the_line_and_checkpoints_apart() {889	dir := temp_repo('view')890	defer { os.rmdir_all(dir) or {} }891	init_repo(dir)892	write(dir, 'view.txt', 'one\n')893	assert run(dir, 'save', 'plain save').code == 0894	assert run(dir, 'checkpoint', 'checkpoint save').code == 0895	line := run(dir, 'view')896	assert line.code == 0897	assert line.out.contains('plain save')898	assert line.out.contains('checkpoint save')899	checkpoints := run(dir, 'view', '--checkpoints')900	assert checkpoints.code == 0901	assert checkpoints.out.contains('checkpoint save')902	assert !checkpoints.out.contains('plain save')903	json_line := run(dir, 'view', '--json')904	assert json_line.code == 0905	assert json_line.out.contains('"is_checkpoint":false')906	assert json_line.out.contains('"is_checkpoint":true')907	json_checkpoints := run(dir, 'view', '--checkpoints', '--json')908	assert json_checkpoints.code == 0909	assert json_checkpoints.out.contains('"is_checkpoint":true')910	assert !json_checkpoints.out.contains('"is_checkpoint":false')911	// `view` takes no arguments, so a stray one is a usage error, and the names912	// it replaced are gone rather than hidden: the diagnostic says which.913	assert run(dir, 'view', 'extra').code == 2914	for gone in ['log', 'saves', 'checkpoints'] {915		refused := run(dir, gone)916		assert refused.code == 2917		assert refused.err.contains('unknown command "${gone}"')918	}919	// Every save is on the whole line exactly once, as the JSON says.920	assert line.out.split_into_lines().len == json_line.out.count('"id":"')921}922923fn test_remote_configuration_is_isolated_and_atomic() {924	dir := temp_repo('remote')925	home := temp_repo('remote-home')926	defer {927		os.rmdir_all(dir) or {}928		os.rmdir_all(home) or {}929	}930	empty := run_home(dir, home, 'remote', '--json')931	assert empty.code == 0932	assert empty.out.contains('"configured":false')933	target := os.join_path(home, 'remote-store')934	set := run_home(dir, home, 'remote', 'folder', target)935	assert set.code == 0936	assert os.is_dir(target)937	state := run_home(dir, home, 'remote', '--json')938	assert state.code == 0939	assert state.out.contains('"kind":"folder"')940	assert state.out.contains(target)941	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1942	assert run_home(dir, home, 'remote', '--json').out.contains(target)943	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')944	assert run_home(dir, home, 'remote', '--forget').code == 0945	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')946}947948// The files under ~/.config/koh can be written by hand instead of by949// `koh remote`, and are then read the same way.950fn test_remote_written_by_hand() {951	dir := temp_repo('remote-by-hand')952	home := temp_repo('remote-by-hand-home')953	defer {954		os.rmdir_all(dir) or {}955		os.rmdir_all(home) or {}956	}957	config := os.join_path(home, '.config', 'koh')958	os.mkdir_all(config) or { panic(err) }959	target := os.join_path(home, 'remote-store')960	os.mkdir_all(target) or { panic(err) }961	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {962		panic(err)963	}964	assert run_home(dir, home, 'init').code == 0965	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }966	assert run_home(dir, home, 'save', 'first').code == 0967	offered := run_home(dir, home, 'offer', '--json')968	assert offered.code == 0969	assert offered.out.contains('"head"')970971	// Keys anyone else can read are refused before they are ever sent.972	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {973		panic(err)974	}975	credentials := os.join_path(config, 'credentials')976	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }977	os.chmod(credentials, 0o644) or { panic(err) }978	loose := run_home(dir, home, 'offer')979	assert loose.code == 1980	assert loose.err.contains('chmod 600')981982	// A setting koh cannot read is replaced by setting the remote again.983	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }984	unreadable := run_home(dir, home, 'offer')985	assert unreadable.code == 1986	assert unreadable.err.contains('not readable')987	assert run_home(dir, home, 'remote', 'folder', target).code == 0988	assert run_home(dir, home, 'offer').code == 0989}990991// A stolen repo belongs to the repo it was stolen from, whatever its folder is992// called later: renaming it must not start a second repo on the remote.993fn test_a_renamed_stolen_repo_keeps_offering_to_its_repo() {994	syncroot := temp_repo('rename-steal')995	home := temp_repo('rename-steal-home')996	defer {997		os.rmdir_all(syncroot) or {}998		os.rmdir_all(home) or {}999	}1000	remote := os.join_path(syncroot, 'remote')1001	a := os.join_path(syncroot, 'A', 'proj')1002	b_parent := os.join_path(syncroot, 'B')1003	os.mkdir_all(a) or { panic(err) }1004	os.mkdir_all(b_parent) or { panic(err) }1005	init_repo(a)1006	write(a, 'a.txt', 'from A\n')1007	assert run_home(a, home, 'remote', 'folder', remote).code == 01008	assert run_home(a, home, 'save', 'A first').code == 01009	assert run_home(b_parent, home, 'steal', 'proj').code == 01010	renamed := os.join_path(b_parent, 'renamed')1011	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }1012	write(renamed, 'b.txt', 'from B\n')1013	assert run_home(renamed, home, 'save', 'B first').code == 01014	assert !os.exists(os.join_path(remote, 'renamed'))1015	assert run_home(a, home, 'steal').code == 01016	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'1017}10181019// A damaged object on the remote stops a steal, names the object, and leaves1020// no half-made folder that would make the retry refuse.1021fn test_steal_of_a_damaged_remote_leaves_nothing() {1022	syncroot := temp_repo('damaged')1023	home := temp_repo('damaged-home')1024	defer {1025		os.rmdir_all(syncroot) or {}1026		os.rmdir_all(home) or {}1027	}1028	remote := os.join_path(syncroot, 'remote')1029	a := os.join_path(syncroot, 'A', 'proj')1030	b_parent := os.join_path(syncroot, 'B')1031	os.mkdir_all(a) or { panic(err) }1032	os.mkdir_all(b_parent) or { panic(err) }1033	init_repo(a)1034	write(a, 'a.txt', 'from A\n')1035	assert run_home(a, home, 'remote', 'folder', remote).code == 01036	assert run_home(a, home, 'save', 'A first').code == 01037	objects := os.join_path(remote, 'proj', 'objects')1038	for name in os.ls(objects) or { panic(err) } {1039		os.chmod(os.join_path(objects, name), 0o644) or {}1040		os.write_file(os.join_path(objects, name), 'junk') or { panic(err) }1041	}1042	stolen := run_home(b_parent, home, 'steal', 'proj')1043	assert stolen.code == 11044	assert stolen.err.contains('is damaged')1045	assert !os.exists(os.join_path(b_parent, 'proj'))1046}10471048fn test_steal_drops_crafted_unsafe_paths_and_lands_the_rest() {1049	syncroot := temp_repo('unsafe-remote')1050	home := temp_repo('unsafe-remote-home')1051	defer {1052		os.rmdir_all(syncroot) or {}1053		os.rmdir_all(home) or {}1054	}1055	remote := os.join_path(syncroot, 'remote')1056	a := os.join_path(syncroot, 'A', 'proj')1057	b_parent := os.join_path(syncroot, 'B')1058	os.mkdir_all(a) or { panic(err) }1059	os.mkdir_all(b_parent) or { panic(err) }1060	init_repo(a)1061	write(a, 'safe.txt', 'safe\n')1062	assert run_home(a, home, 'remote', 'folder', remote).code == 01063	id := run_home(a, home, 'save', 'crafted', '--json').out.all_after('"id":"')[..12]1064	assert run_home(a, home, 'offer').code == 01065	record_path := os.join_path(remote, 'proj', 'saves', id)1066	record := os.read_file(record_path) or { panic(err) }1067	path_at := record.index('"path":"safe.txt"') or { panic('safe path missing from ${record}') }1068	file_start := record[..path_at].last_index('{') or { panic('safe file start missing') }1069	file_end := path_at + (record[path_at..].index('}') or { panic('safe file end missing') }) + 11070	file := record[file_start..file_end]1071	mut files := [file]1072	for path in ['../outside.txt', '/etc/koh-test', 'a/../../outside.txt', 'bad\\\\name',1073		'control\\rname'] {1074		files << file.replace('safe.txt', path)1075	}1076	os.write_file(record_path, record[..file_start] + files.join(',') + record[file_end..]) or {1077		panic(err)1078	}10791080	stolen := run_home(b_parent, home, 'steal', 'proj')1081	assert stolen.code == 0, stolen.err1082	for dropped in ['../outside.txt', 'bad\\\\name', 'control\\x0dname'] {1083		assert (stolen.out + stolen.err).contains('dropped unsafe path ${dropped}'), stolen.out + stolen.err1084	}1085	assert os.read_file(os.join_path(b_parent, 'proj', 'safe.txt'))! == 'safe\n'1086	assert !os.exists(os.join_path(b_parent, 'outside.txt'))1087	assert !os.exists(os.join_path(b_parent, 'proj', 'bad', 'name'))1088	assert !os.exists('${b_parent}/proj/control\rname')1089}10901091fn test_offer_steal_folder_remote() {1092	syncroot := temp_repo('sync')1093	home := temp_repo('sync-home')1094	defer {1095		os.rmdir_all(syncroot) or {}1096		os.rmdir_all(home) or {}1097	}1098	remote := os.join_path(syncroot, 'remote')1099	a := os.join_path(syncroot, 'A', 'proj')1100	b_parent := os.join_path(syncroot, 'B')1101	os.mkdir_all(a) or { panic(err) }1102	os.mkdir_all(b_parent) or { panic(err) }1103	init_repo(a)1104	write(a, 'a.txt', 'from A\n')1105	assert run_home(a, home, 'remote', 'folder', remote).code == 01106	assert run_home(a, home, 'save', 'A first').code == 01107	stolen := run_home(b_parent, home, 'steal', 'proj')1108	assert stolen.code == 01109	b := os.join_path(b_parent, 'proj')1110	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'1111	write(b, 'b.txt', 'from B\n')1112	assert run_home(b, home, 'save', 'B first').code == 01113	write(a, 'a2.txt', 'second\n')1114	assert run_home(a, home, 'save', 'A second').code == 01115	assert run_home(a, home, 'steal').code == 01116	assert os.exists(os.join_path(a, 'b.txt'))1117	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')1118	write(a, 'clash.txt', 'base\n')1119	assert run_home(a, home, 'save', 'clash base').code == 01120	assert run_home(b, home, 'steal').code == 01121	write(a, 'clash.txt', 'A version\n')1122	assert run_home(a, home, 'save', 'A clash').code == 01123	write(b, 'clash.txt', 'B version\n')1124	assert run_home(b, home, 'save', 'B clash').code == 01125	refused := run_home(b, home, 'steal')1126	assert refused.code == 11127	assert refused.err.contains('--mine') || refused.err.contains('--theirs')1128	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1129	theirs := run_home(b, home, 'steal', '--theirs', '--json')1130	assert theirs.code == 01131	// The pre-combine tree is off the line now; the way back must be named,1132	// or an agent without the history view cannot find it.1133	assert theirs.out.contains('"previous_head":"${b_head}"')1134	assert theirs.out.contains('"kept_versions":["clash.txt:${b_head}"]')1135	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1136	assert run_home(b, home, 'load', b_head, '--yes').code == 01137	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'1138	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 01139	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1140	write(a, 'clash.txt', 'A second\n')1141	assert run_home(a, home, 'save', 'A second clash').code == 01142	write(b, 'clash.txt', 'B second\n')1143	assert run_home(b, home, 'save', 'B second clash').code == 01144	assert run_home(b, home, 'steal', '--mine').code == 01145	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'1146	assert run_home(b, home, 'view').out.contains('combine: kept mine for')1147}11481149fn test_guided_steal_walks_the_terminal_and_can_cancel() {1150	syncroot := temp_repo('guided-steal')1151	home := temp_repo('guided-steal-home')1152	defer {1153		os.rmdir_all(syncroot) or {}1154		os.rmdir_all(home) or {}1155	}1156	remote := os.join_path(syncroot, 'remote')1157	a := os.join_path(syncroot, 'A', 'proj')1158	b_parent := os.join_path(syncroot, 'B')1159	os.mkdir_all(a) or { panic(err) }1160	os.mkdir_all(b_parent) or { panic(err) }1161	init_repo(a)1162	write(a, 'clash.txt', 'base\n')1163	write(a, 'other.txt', 'base\n')1164	write(a, 'same.txt', 'base\n')1165	write(a, 'remote-only.txt', 'base\n')1166	write(a, 'local-only.txt', 'base\n')1167	assert run_home(a, home, 'remote', 'folder', remote).code == 01168	assert run_home(a, home, 'save', 'base').code == 01169	assert run_home(b_parent, home, 'steal', 'proj').code == 01170	b := os.join_path(b_parent, 'proj')11711172	write(b, 'dirty.txt', 'mine\n')1173	before := run_home(b, home, 'status', '--json').out1174	quit := run_pty_home(b, home, ['q'], 'steal')1175	assert quit.out.contains('steal proj')1176	assert quit.out.contains('you have 1 unsaved file')1177	assert quit.out.contains('dirty.txt')1178	assert run_home(b, home, 'status', '--json').out == before1179	// A save needs a message; an empty one stops, says so, and saves nothing.1180	unsaid := run_pty_home(b, home, ['s', ''], 'steal')1181	assert unsaid.code == 11182	assert unsaid.out.contains('no message — nothing was saved')1183	assert run_home(b, home, 'status', '--json').out == before1184	checkpoint := run_pty_home(b, home, ['c'], 'steal')1185	assert checkpoint.code == 0, checkpoint.err1186	assert run_home(b, home, 'view', '--checkpoints').out.contains('before steal')11871188	assert run_home(a, home, 'steal').code == 01189	write(a, 'forward.txt', 'new\n')1190	assert run_home(a, home, 'save', 'fast forward').code == 01191	forward := run_pty_home(b, home, []string{}, 'steal')1192	assert forward.out.contains('proj is up to date · 1 new save')1193	assert shown(forward.out).len == 1, forward.out1194	write(a, 'clash.txt', 'remote\n')1195	write(a, 'other.txt', 'remote\n')1196	write(a, 'same.txt', 'identical\n')1197	write(a, 'remote-only.txt', 'remote\n')1198	assert run_home(a, home, 'save', 'remote change').code == 01199	write(b, 'clash.txt', 'mine\n')1200	write(b, 'other.txt', 'mine\n')1201	write(b, 'same.txt', 'identical\n')1202	write(b, 'local-only.txt', 'mine\n')1203	assert run_home(b, home, 'save', 'local change').code == 01204	local_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1205	// `d` opens both changes in the pager, which Enter leaves; `?` explains the two sides.1206	cancel := run_pty_home(b, home, ['d', '', '?', 'm', 'b', 't', 't', 'n'], 'steal')1207	assert cancel.out.contains('your changes')1208	assert cancel.out.contains('remote changes')1209	assert cancel.out.contains('Nothing is lost either way')1210	// The shared save's age, relative: seconds old here, so `now` unless the machine is slow.1211	since := cancel.out.split_into_lines().filter(it.contains('both moved since'))1212	assert since.len == 11213	assert since[0].trim_space().ends_with(' · now') || since[0].trim_space().ends_with(' ago'), since[0]1214	assert cancel.out.contains('5 files changed')1215	assert cancel.out.contains('2 combine by themselves')1216	assert cancel.out.contains('1 changed the same way')1217	assert cancel.out.contains('2 need you')1218	assert cancel.out.contains('ready to combine')1219	assert run_home(b, home, 'status', '--json').out.contains('"head_id":"${local_head}"')1220	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'mine\n'12211222	done := run_pty_home(b, home, ['y'], 'steal', '--theirs')1223	assert done.out.contains('combined · offered to proj')1224	assert done.out.contains('took theirs: clash.txt · other.txt')1225	assert !done.out.contains('kept mine')1226	assert done.out.contains('to undo all of it: koh load ${local_head}')1227	assert done.out.contains('your clash.txt is in ${local_head}')1228	assert !done.out.contains('\x1b')1229	for line in done.out.split_into_lines() {1230		assert line.runes().len <= 80, line1231	}1232}12331234// A steal brings in the whole history, flags included; both output forms must1235// say which saves came in flagged, and why.1236fn test_a_steal_reports_flagged_saves() {1237	syncroot := temp_repo('steal-flags')1238	home := temp_repo('steal-flags-home')1239	defer {1240		os.rmdir_all(syncroot) or {}1241		os.rmdir_all(home) or {}1242	}1243	a := os.join_path(syncroot, 'A', 'proj')1244	os.mkdir_all(a) or { panic(err) }1245	init_repo(a)1246	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 01247	write(a, 'a.txt', 'one\n')1248	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]1249	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 01250	assert run_home(a, home, 'offer').code == 01251	for name in ['B', 'C'] {1252		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }1253	}1254	json_stolen := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')1255	assert json_stolen.code == 01256	assert json_stolen.out.contains('"flagged":["${id}"]')1257	text_stolen := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')1258	assert text_stolen.code == 01259	assert text_stolen.out.contains('[${id}] came in flagged — broke the build')1260}12611262// A folder remote on a disk or share that is not mounted is simply not there.1263// Creating it would put the saves in a stand-in folder the other machine never1264// sees; the offer must say what is wrong instead.1265fn test_an_unmounted_folder_remote_is_not_recreated() {1266	syncroot := temp_repo('unmounted')1267	home := temp_repo('unmounted-home')1268	defer {1269		os.rmdir_all(syncroot) or {}1270		os.rmdir_all(home) or {}1271	}1272	mount := os.join_path(syncroot, 'nas')1273	remote := os.join_path(mount, 'koh')1274	a := os.join_path(syncroot, 'proj')1275	os.mkdir_all(a) or { panic(err) }1276	init_repo(a)1277	assert run_home(a, home, 'remote', 'folder', remote).code == 01278	write(a, 'a.txt', 'one\n')1279	assert run_home(a, home, 'save', 'first').code == 01280	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }1281	os.mkdir(mount) or { panic(err) }1282	offered := run_home(a, home, 'offer')1283	assert offered.code == 11284	assert offered.err.contains('mounted')1285	assert !os.exists(remote)1286	write(a, 'a.txt', 'two\n')1287	saved := run_home(a, home, 'save', 'second')1288	assert saved.code == 01289	assert saved.out.contains('mounted')1290	assert !os.exists(remote)1291}12921293fn test_man_and_koh2_handoff() {1294	dir := temp_repo('man')1295	home := temp_repo('man-home')1296	defer {1297		os.rmdir_all(dir) or {}1298		os.rmdir_all(home) or {}1299	}1300	whole := run_home(dir, home, 'man')1301	assert whole.code == 01302	assert whole.out.contains('NAME')1303	assert whole.out.contains('COMMANDS')1304	assert whole.out.contains('STRICT KOH DISCIPLINE')1305	assert whole.out.contains('Asha Software · asha.software')1306	assert !whole.out.contains('\x1b') && !whole.out.contains('◆')1307	strip := run_home(dir, home, 'man', 'strip')1308	assert strip.code == 01309	assert strip.out.contains('strip')1310	assert !strip.out.contains('koh save ')1311	steal := run_home(dir, home, 'man', 'steal').out1312	assert steal.starts_with('    koh steal') && steal.contains('koh steal my-project')1313	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."1314	assert run_home(dir, home, 'man', 'nonsense').code == 21315	legacy := temp_repo('legacy')1316	defer { os.rmdir_all(legacy) or {} }1317	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }1318	fake := os.join_path(home, 'bin')1319	os.mkdir_all(fake) or { panic(err) }1320	fake_koh := os.join_path(fake, 'koh2')1321	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }1322	os.chmod(fake_koh, 0o755) or { panic(err) }1323	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')1324	assert handoff.code == 71325	assert handoff.out.contains('handoff:status --json')1326	// One notice line, on stderr, so koh2's own output stays as it was.1327	assert handoff.err.contains('Koh 2 repo')1328	assert handoff.err.trim_space().split_into_lines().len == 11329	assert handoff.out.trim_space() == 'handoff:status --json'1330	// A command Koh 2 reads differently, or lacks, is refused rather than handed off.1331	for command in ['view', 'strip', 'build', 'doctor', 'steal'] {1332		refused := run_home_with_path(legacy, home, fake, command)1333		assert refused.code == 1, command1334		assert !refused.out.contains('handoff'), command1335		assert refused.err.contains('koh migrate'), refused.err1336	}1337	// And one that belongs to the machine, not the repo, is Koh 3's own.1338	remote := run_home_with_path(legacy, home, fake, 'remote')1339	assert !remote.out.contains('handoff'), remote.out1340	assert remote.err.contains('needs a terminal'), remote.err1341}13421343fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {1344	stamp := '${os.getpid()}-${time.now().unix_nano()}'1345	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')1346	out_path := '${base}.out'1347	err_path := '${base}.err'1348	code_path := '${base}.code'1349	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'1350	for arg in args {1351		command += ' ${q(arg)}'1352	}1353	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'1354	result := os.execute(shell)1355	if result.exit_code != 0 {1356		panic('could not run test command: ${result.output}')1357	}1358	code := os.read_file(code_path) or { panic(err) }1359	out := os.read_file(out_path) or { '' }1360	err := os.read_file(err_path) or { '' }1361	os.rm(out_path) or {}1362	os.rm(err_path) or {}1363	os.rm(code_path) or {}1364	return Result{1365		code: code.int()1366		out:  out1367		err:  err1368	}1369}13701371// --- migration -------------------------------------------------------------13721373// koh2_binary finds Koh 2: `koh2` since the cutover, `koh` before it, and never Koh 3.1374fn koh2_binary() string {1375	for name in ['koh2', 'koh'] {1376		path := os.find_abs_path_of_executable(name) or { continue }1377		if os.execute('${os.quoted_path(path)} --version').output.starts_with('koh v2') {1378			return path1379		}1380	}1381	return ''1382}13831384// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under1385// test here.1386fn run_koh2(dir string, command string) {1387	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')1388}13891390fn save_ids(dir string) []string {1391	mut ids := []string{}1392	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {1393		if name.ends_with('.json') {1394			ids << name.trim_right('.json')1395		}1396	}1397	ids.sort()1398	return ids1399}14001401fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {1402	koh2 := koh2_binary()1403	if koh2 == '' {1404		println('skipping the migration tests: koh (Koh 2) is not on PATH')1405		return1406	}1407	dir := temp_repo('migrate')1408	defer { os.rmdir_all(dir) or {} }1409	home := temp_repo('migrate-home')1410	defer { os.rmdir_all(home) or {} }1411	run_koh2(dir, '${q(koh2)} init')1412	// One file large enough to be an object, one small enough to be inlined.1413	write(dir, 'code.txt', 'x'.repeat(700))1414	write(dir, 'tiny.txt', 'tiny\n')1415	run_koh2(dir, '${q(koh2)} save "first save"')1416	run_koh2(dir, '${q(koh2)} checkpoint "before something"')1417	write(dir, 'code.txt', 'y'.repeat(700))1418	run_koh2(dir, '${q(koh2)} save "second save"')1419	original := save_ids(dir)1420	assert original.len == 314211422	// Off a terminal it asks nothing and changes nothing without --yes.1423	unasked := run_home(dir, home, 'migrate')1424	assert unasked.code == 1 && unasked.err.contains('needs --yes'), unasked.err1425	assert os.is_dir(os.join_path(dir, '.koh'))1426	report := run_home(dir, home, 'migrate', '--yes')1427	assert report.code == 01428	assert report.out.contains('this will:')1429	assert report.out.contains('migrated 3 saves')1430	// The swap: `.koh` is a file, the old data is archived, nothing is left in the draft.1431	assert os.is_file(os.join_path(dir, '.koh'))1432	assert os.is_dir(os.join_path(dir, '.koh-v2'))1433	assert os.is_file(os.join_path(dir, '.kohignore'))1434	assert !os.exists(os.join_path(dir, '.koh-migrate'))14351436	// Every save kept its original ID, and the new repo is sound.1437	listed := run_home(dir, home, 'view', '--json')1438	assert listed.code == 01439	for id in original {1440		assert listed.out.contains(id)1441	}1442	assert run_home(dir, home, 'doctor').code == 01443	assert run_home(dir, home, 'status').code == 014441445	// Migrating again has nothing to convert.1446	assert run_home(dir, home, 'migrate', '--yes').code == 11447}14481449fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {1450	koh2 := koh2_binary()1451	if koh2 == '' {1452		return1453	}1454	dir := temp_repo('migrate-dirty')1455	defer { os.rmdir_all(dir) or {} }1456	home := temp_repo('migrate-dirty-home')1457	defer { os.rmdir_all(home) or {} }1458	run_koh2(dir, '${q(koh2)} init')1459	write(dir, 'code.txt', 'x'.repeat(700))1460	run_koh2(dir, '${q(koh2)} save "only save"')1461	write(dir, 'code.txt', 'unsaved change\n')14621463	refused := run_home(dir, home, 'migrate', '--yes')1464	assert refused.code == 11465	assert refused.err.contains('save with koh2 first')1466	// Nothing moved: still Koh 2, no archive, no draft file.1467	assert os.is_dir(os.join_path(dir, '.koh'))1468	assert !os.exists(os.join_path(dir, '.koh-v2'))1469	assert !os.exists(os.join_path(dir, '.koh-migrate'))1470}14711472// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or1473// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have1474// a `.kohconfig`; migrate must not call them unsaved work.1475fn test_migrate_passes_over_the_files_koh2_never_saved() {1476	koh2 := koh2_binary()1477	if koh2 == '' {1478		return1479	}1480	dir := temp_repo('migrate-koh2-ignores')1481	defer { os.rmdir_all(dir) or {} }1482	home := temp_repo('migrate-koh2-ignores-home')1483	defer { os.rmdir_all(home) or {} }1484	run_koh2(dir, '${q(koh2)} init')1485	write(dir, 'code.txt', 'x'.repeat(700))1486	run_koh2(dir, '${q(koh2)} save "only save"')1487	write(dir, '.kohconfig', 'stable_days = 14\n')1488	write(dir, '.kohignore.public', 'private/\n')1489	write(dir, 'lib/app.bundle', 'bundle\n')1490	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1491	// Koh 2 keeps saving a file under a folder pattern added later, where1492	// Koh 3 reads the same rule as covering the folder: the saved file is on1493	// disk and matches, so the tree is clean.1494	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1495	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1496	// Koh 2 skips *.bundle even when its rules no longer list it.1497	ignore_path := os.join_path(dir, '.koh', 'ignore')1498	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1499	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1500	// A saved file the walk skips still has to match what was saved.1501	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1502	changed := run_home(dir, home, 'migrate', '--yes')1503	assert changed.code == 11504	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1505	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1506	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')15071508	migrated := run_home(dir, home, 'migrate', '--yes')1509	assert migrated.code == 0, migrated.err1510	// They stay where they were, for the user to keep or delete.1511	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1512}15131514struct FakeKepr {1515	no_access bool1516	// One reply the redemption must cope with: '500', 'garbage' or 'incomplete'.1517	fail string1518	// When set, /api/connect answers 307 here instead of a code reply.1519	redirect_to string1520mut:1521	objects map[string][]u81522	// What the client asked for. A map, because the server holds its own copy of this struct.1523	seen map[string]string1524}15251526fn (mut h FakeKepr) handle(req http.Request) http.Response {1527	if req.method == .post && req.url == '/api/connect' {1528		h.seen['code'] = req.data1529		if h.redirect_to != '' {1530			return http.Response{1531				status_code: 3071532				status_msg:  'Temporary Redirect'1533				header:      http.new_header(1534					key:   .location1535					value: h.redirect_to1536				)1537			}1538		}1539		if h.fail == '500' {1540			return http.Response{ status_code: 500, status_msg: 'Internal Server Error' }1541		}1542		if h.fail == 'garbage' {1543			return http.Response{ status_code: 200, status_msg: 'OK', body: 'not json at all' }1544		}1545		if h.fail == 'incomplete' {1546			return http.Response{ status_code: 200, status_msg: 'OK', body: '{"endpoint":"http://x","bucket":"","region":"","access_key_id":"","secret_access_key":""}' }1547		}1548		if req.data == 'code=good' && !h.no_access {1549			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"}' }1550		}1551		return http.Response{ status_code: 404, status_msg: 'Not Found', body: '{"error":"no_code","message":"no code"}' }1552	}1553	if req.method == .get && req.url.starts_with('/connect') {1554		h.seen['connect'] = req.url1555		return http.Response{ status_code: if h.no_access { 404 } else { 302 }, status_msg: 'Found' }1556	}1557	key := req.url1558	if key.starts_with('/bucket/') {1559		match req.method {1560			.put {1561				if req.header.get_custom('If-None-Match', http.HeaderQueryConfig{}) or { '' } == '*' && key in h.objects {1562					return http.Response{ status_code: 412, status_msg: 'Precondition Failed' }1563				}1564				h.objects[key] = req.data.bytes()1565				return http.Response{ status_code: 200, status_msg: 'OK' }1566			}1567			.get {1568				if body := h.objects[key] {1569					return http.Response{1570						status_code: 2001571						status_msg:  'OK'1572						body:        body.bytestr()1573						header:      http.new_header(1574							key:   .etag1575							value: '"tag"'1576						)1577					}1578				}1579				return http.Response{ status_code: 404, status_msg: 'Not Found' }1580			}1581			.delete {1582				h.objects.delete(key)1583				return http.Response{ status_code: 204, status_msg: 'No Content' }1584			}1585			else {}1586		}1587	}1588	return http.Response{ status_code: 404, status_msg: 'Not Found' }1589}15901591fn start_fake_kepr(no_access bool, fail string, redirect_to string) !(int, &http.Server, &FakeKepr) {1592	for port in 19401 .. 19411 {1593		listener := net.listen_tcp(.ip, '127.0.0.1:${port}') or { continue }1594		fake := &FakeKepr{1595			no_access:   no_access1596			fail:        fail1597			redirect_to: redirect_to1598			seen:        map[string]string{}1599		}1600		mut server := &http.Server{1601			listener:             listener1602			handler:              fake1603			show_startup_message: false1604		}1605		spawn server.listen_and_serve()1606		server.wait_till_running()!1607		return port, server, fake1608	}1609	return error('no free fake Kepr port')1610}16111612// A slash makes an argument an address, so half an address is an error and never a repo name.1613fn test_steal_refuses_an_address_that_is_not_one() {1614	outside := temp_repo('steal-address')1615	home := temp_repo('steal-address-home')1616	defer { os.rmdir_all(outside) or {} }1617	defer { os.rmdir_all(home) or {} }1618	// The repo half becomes a URL path segment and a folder here, so it is a name Kepr serves.1619	for bad in ['kepr.uk/', '/shipped', 'kepr.uk/..', 'kepr.uk/.', 'kepr.uk/a b', 'kepr.uk/nina?x',1620		'kepr.uk/nina#x', 'kepr.uk/nína'] {1621		refused := run_home(outside, home, 'steal', bad)1622		assert refused.code == 1, bad1623		assert refused.err.contains('is not <host>/<repo>'), '${bad}: ${refused.err}'1624	}1625	assert run_home(outside, home, 'steal', 'one', 'two').code == 21626	assert run_home(outside, home, 'steal', '--list', 'extra').code == 21627}16281629fn test_remote_kepr_saves_and_refuses_without_changes() {1630	repo := temp_repo('kepr')1631	home := temp_repo('kepr-home')1632	defer { os.rmdir_all(repo) or {} }1633	defer { os.rmdir_all(home) or {} }1634	init_repo(repo)1635	port, mut server, fake := start_fake_kepr(false, '', '')!1636	defer { server.stop() }1637	host := 'http://127.0.0.1:${port}'1638	// A trailing slash is the same host, and the saved line keeps the normalised form.1639	good := run_home(repo, home, 'remote', '${host}/', '--code', 'good')1640	assert good.code == 0, good.err1641	remote_path := os.join_path(home, '.config', 'koh', 'remote')1642	credentials_path := os.join_path(home, '.config', 'koh', 'credentials')1643	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'1644	assert os.read_file(credentials_path)! == '# written by koh remote — keep this file private\naccess_key=access\nsecret_key=secret\n'1645	// The code went as a form field, and the connect page was never asked for: there was a code.1646	assert (fake.seen['code'] or { '' }) == 'code=good'1647	assert (fake.seen['connect'] or { '' }) == ''1648	// A refused code, a missing terminal and a wrong reply all leave both files as they were.1649	before := os.read_file(remote_path)!1650	before_keys := os.read_file(credentials_path)!1651	bad := run_home(repo, home, 'remote', host, '--code', 'bad')1652	assert bad.code == 11653	assert bad.err.contains('wrong or has expired')1654	// The 404 could also mean a Kepr that hands out nothing, so the connect page is asked for1655	// with this machine's name. (This machine's name holds no character needing an escape, so1656	// that part of the query cannot be exercised here.)1657	// `machine.name()` is `os.hostname() or { 'unknown' }`, so the query carries the same text.1658	assert (fake.seen['connect'] or { '' }).contains('machine=${os.hostname() or { 'unknown' }}')1659	no_terminal := run_home(repo, home, 'remote', host)1660	assert no_terminal.code == 11661	assert no_terminal.err.contains('needs a terminal')1662	assert os.read_file(remote_path)! == before1663	assert os.read_file(credentials_path)! == before_keys1664}16651666fn test_remote_kepr_refuses_hosts_that_are_not_hosts() {1667	repo := temp_repo('kepr-host')1668	home := temp_repo('kepr-host-home')1669	defer { os.rmdir_all(repo) or {} }1670	defer { os.rmdir_all(home) or {} }1671	init_repo(repo)1672	for host in ['kepr.uk/foo', 'https://kepr.uk?x=1', 'kepr.uk#frag', '[email protected]', 'kepr uk',1673		'http://127.0.0.1:1/foo', 'https://'] {1674		refused := run_home(repo, home, 'remote', host, '--code', 'good')1675		assert refused.code == 1, host1676		assert refused.err.contains('is not a Kepr address'), '${host}: ${refused.err}'1677	}1678	// The reply carries the bucket's secret key, so plain http is only for this machine's own Kepr.1679	for host in ['http://kepr.uk', 'http://10.0.0.2:3000', 'http://KEPR.uk:80'] {1680		refused := run_home(repo, home, 'remote', host, '--code', 'good')1681		assert refused.code == 1, host1682		assert refused.err.contains('needs https'), '${host}: ${refused.err}'1683		stolen := run_home(home, home, 'steal', '${host}/nina')1684		assert stolen.code == 1, host1685		assert stolen.err.contains('needs https'), '${host}: ${stolen.err}'1686	}1687	// --code belongs to the host form alone.1688	assert run_home(repo, home, 'remote', 's3', 'https://x', 'b', 'r', '--code', 'good').code == 21689	assert run_home(repo, home, 'remote', 'folder', '/tmp', '--code', 'good').code == 21690	assert run_home(repo, home, 'remote', '--code', 'good').code == 21691	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1692}16931694fn test_remote_kepr_refuses_what_is_not_a_code_reply() {1695	repo := temp_repo('kepr-reply')1696	home := temp_repo('kepr-reply-home')1697	defer { os.rmdir_all(repo) or {} }1698	defer { os.rmdir_all(home) or {} }1699	init_repo(repo)1700	remote_path := os.join_path(home, '.config', 'koh', 'remote')1701	for mode in ['500', 'garbage', 'incomplete'] {1702		port, mut server, _ := start_fake_kepr(false, mode, '')!1703		refused := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1704		server.stop()1705		assert refused.code == 1, mode1706		assert refused.err.contains('nothing was changed'), '${mode}: ${refused.err}'1707		assert !os.exists(remote_path)1708	}1709	// A redirect would hand the code to wherever it points, so it is refused and never followed.1710	target_port, mut target, target_fake := start_fake_kepr(false, '', '')!1711	port, mut server, _ := start_fake_kepr(false, '', 'http://127.0.0.1:${target_port}/api/connect')!1712	redirected := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1713	server.stop()1714	target.stop()1715	assert redirected.code == 11716	assert redirected.err.contains('refused the code')1717	assert target_fake.seen.len == 0, 'the code was forwarded: ${target_fake.seen}'1718	assert !os.exists(remote_path)1719}17201721// An unreachable Kepr is a refusal too, and the settings are still untouched.1722fn test_remote_kepr_that_cannot_be_reached_changes_nothing() {1723	repo := temp_repo('kepr-down')1724	home := temp_repo('kepr-down-home')1725	defer { os.rmdir_all(repo) or {} }1726	defer { os.rmdir_all(home) or {} }1727	init_repo(repo)1728	refused := run_home(repo, home, 'remote', 'http://127.0.0.1:1', '--code', 'good')1729	assert refused.code == 11730	assert refused.err.contains('could not reach Kepr')1731	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1732}17331734fn test_remote_kepr_without_bucket_access_is_explained() {1735	repo := temp_repo('kepr-no-access')1736	home := temp_repo('kepr-no-access-home')1737	defer { os.rmdir_all(repo) or {} }1738	defer { os.rmdir_all(home) or {} }1739	init_repo(repo)1740	port, mut server, _ := start_fake_kepr(true, '', '')!1741	defer { server.stop() }1742	r := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'bad')1743	assert r.code == 11744	assert r.err.contains("doesn't hand out bucket access")1745	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1746}