cli_test.v

67.3 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	// No flag text anywhere on the screen.275	assert !help.out.contains('--'), help.out276	lines := help.out.split_into_lines()277	for line in lines {278		assert line.runes().len <= 80, line279	}280	// Each command has its own paragraph, a blank line above it.281	for name in names {282		for i, line in lines {283			if line.starts_with('  ${name} ') {284				assert i > 0 && lines[i - 1] == '', line285			}286		}287	}288	// A bare `koh` keeps its stream and exit code; `-h` shows the same screen.289	bare := run(dir)290	assert bare.code == 2291	assert bare.out == ''292	assert bare.err.contains('koh man <command>')293	short := run(dir, '-h')294	assert short.code == 0295	assert short.out == help.out296}297298// Colour on the screen follows NO_COLOR, as it does everywhere else.299fn test_the_help_screen_has_no_colour_when_it_is_off() {300	dir := temp_repo('help_plain')301	defer { os.rmdir_all(dir) or {} }302	home := temp_repo('help_plain_home')303	defer { os.rmdir_all(home) or {} }304	out_path := os.join_path(os.temp_dir(), 'koh3-help-${os.getpid()}-${time.now().unix_nano()}')305	defer { os.rm(out_path) or {} }306	code := os.system('cd ${q(dir)} && HOME=${q(home)} NO_COLOR=1 ${q(binary)} --help > ${q(out_path)}')307	assert code == 0308	text := os.read_file(out_path) or { panic(err) }309	assert !text.contains('\x1b'), text310	assert text.contains('  save        snapshot your work')311}312313// The binary embeds VERSION while saves bump v.mod; they drifted once.314fn test_version_matches_the_manifest() {315	dir := temp_repo('version')316	defer { os.rmdir_all(dir) or {} }317	version := run(dir, '--version').out.trim_space().all_after('koh ')318	manifest := os.read_file(os.join_path(root, 'v.mod')) or { panic(err) }319	assert manifest.contains("version: '${version}'"), version320}321322fn test_save_checkpoint_and_status() {323	dir := temp_repo('save')324	defer { os.rmdir_all(dir) or {} }325	init_repo(dir)326	write(dir, 'tracked.txt', 'one\n')327	r := run(dir, 'save', 'first message', '--agent', 'agent-7', '--session', 'session-a', '--json')328	assert r.code == 0329	for key in ['id', 'parent', 'message', 'created_at', 'machine', 'is_checkpoint', 'agent', 'session',330		'files', 'size_bytes'] {331		read_json_has(r.out, key)332	}333	assert r.out.contains('"message":"first message"')334	assert r.out.contains('"agent":"agent-7"')335	assert r.out.contains('"session":"session-a"')336	assert r.out.contains('"is_checkpoint":false')337	assert run(dir, 'save', 'again').code == 1338	assert run(dir, 'save', 'again').err.contains('nothing has changed since the last save')339	assert run(dir, 'save').code == 2340	assert run(dir, 'save', 'x', '--bogus').code == 2341	cp := run(dir, 'checkpoint', 'still first', '--json')342	assert cp.code == 0343	assert cp.out.contains('"is_checkpoint":true')344	assert cp.out.contains('"parent":')345	clean := run(dir, 'status')346	assert clean.code == 0347	assert clean.out.contains('no changes')348	write(dir, 'tracked.txt', 'two\n')349	write(dir, 'new.txt', 'new\n')350	os.rm(os.join_path(dir, 'tracked.txt')) or { panic(err) }351	write(dir, '.kohignore', '*.log\n')352	status := run(dir, 'status')353	assert status.code == 0354	assert status.out.contains('+')355	assert status.out.contains('~') || status.out.contains('-')356	assert status.out.contains('added')357	js := run(dir, 'status', '--json')358	assert js.code == 0359	for key in ['head_id', 'head_msg', 'dirty', 'modified', 'added', 'deleted', 'ignore_changed',360		'saves', 'size_bytes', 'head_flagged'] {361		read_json_has(js.out, key)362	}363	assert js.out.contains('"ignore_changed":true')364	// What the shell prompt shows: saves on the line, the .koh size, the flag.365	assert js.out.contains('"saves":2')366	assert js.out.contains('"size_bytes":${os.file_size(os.join_path(dir, '.koh'))}')367	assert js.out.contains('"head_flagged":false')368	head := js.out.all_after('"head_id":"').all_before('"')369	assert run(dir, 'flag', head, '--reason', 'bad').code == 0370	assert run(dir, 'status', '--json').out.contains('"head_flagged":true')371}372373fn test_status_requires_repo_and_ignore_rules() {374	dir := temp_repo('status')375	defer { os.rmdir_all(dir) or {} }376	assert run(dir, 'status').code == 1377	init_repo(dir)378	write(dir, '.kohignore', '*.log\nbuild/\n')379	write(dir, 'keep.txt', 'keep\n')380	write(dir, 'ignored.log', 'ignore\n')381	write(dir, 'build/output.txt', 'ignore\n')382	saved := run(dir, 'save', 'keep', '--json')383	assert saved.code == 0384	id := saved.out.all_after('"id":"')[..12]385	// Where things stand comes first, clean or not.386	clean := run(dir, 'status').out387	assert clean.contains('at [${id}] keep · '), clean388	assert clean.contains(' · 1 save\n'), clean389	assert clean.contains('no changes')390	write(dir, 'keep.txt', 'changed\n')391	assert run(dir, 'status').out.contains('at [${id}] keep · ')392	write(dir, 'keep.txt', 'keep\n')393	assert !run(dir, 'status').out.contains('ignored.log')394	assert !run(dir, 'status').out.contains('build/output.txt')395	assert !run(dir, 'status').out.contains('LOG.md')396}397398fn test_status_and_save_report_unsafe_names_without_refusing_the_save() {399	dir := temp_repo('unsafe-names')400	defer { os.rmdir_all(dir) or {} }401	init_repo(dir)402	write(dir, 'safe.txt', 'safe\n')403	assert run(dir, 'save', 'safe').code == 0404	os.write_file('${dir}/bad\\name.txt', 'bad\n') or { panic(err) }405	os.write_file('${dir}/Icon\r', 'icon\n') or { panic(err) }406407	status := run(dir, 'status', '--json')408	assert status.code == 0409	assert status.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), status.out410	saved := run(dir, 'checkpoint', 'unsafe names', '--json')411	assert saved.code == 0412	assert saved.out.contains('"unsafe_paths":["Icon\\\\x0d","bad\\\\\\\\name.txt"]'), saved.out413}414415// LOG.md is a convenience written after the save lands. If it cannot be416// written, the save still happened, and an agent that retried on a failure417// would only be told nothing had changed.418fn test_a_save_succeeds_when_log_md_cannot_be_written() {419	dir := temp_repo('logmd')420	defer { os.rmdir_all(dir) or {} }421	init_repo(dir)422	os.mkdir_all(os.join_path(dir, 'LOG.md')) or { panic(err) }423	write(dir, 'a.txt', 'one\n')424	r := run(dir, 'save', 'first', '--json')425	assert r.code == 0426	assert r.out.starts_with('{')427	assert r.err.contains('LOG.md')428	assert run(dir, 'view', '--json').out.contains('"message":"first"')429}430431// A folder of ignored files can sit where a restored file should go. Koh432// never touches ignored files, so the restore must stop and say so, not drop433// the file inside the folder under a temporary name.434fn test_a_restore_refuses_a_folder_of_ignored_files_in_the_way() {435	dir := temp_repo('dir-in-way')436	defer { os.rmdir_all(dir) or {} }437	init_repo(dir)438	write(dir, 'out', 'a file\n')439	first := run(dir, 'save', 'out is a file', '--json').out.all_after('"id":"')[..12]440	os.rm(os.join_path(dir, 'out')) or { panic(err) }441	write(dir, 'out/build.log', 'ignored\n')442	assert run(dir, 'save', 'out is gone').code == 0443	r := run(dir, 'load', first, '--yes')444	assert r.code == 1445	assert r.err.contains('out')446	assert os.ls(os.join_path(dir, 'out'))! == ['build.log']447}448449// Koh never follows a symlink, so a folder replaced by a link to somewhere450// else is not the repo's to write into: restoring through it would overwrite451// files outside the repo. The refusal comes before anything is recorded.452fn test_a_restore_never_writes_through_a_symlinked_folder() {453	dir := temp_repo('link-in-way')454	outside := temp_repo('link-target')455	defer {456		os.rmdir_all(dir) or {}457		os.rmdir_all(outside) or {}458	}459	init_repo(dir)460	write(dir, 'docs/a.md', 'saved\n')461	first := run(dir, 'save', 'docs', '--json').out.all_after('"id":"')[..12]462	os.rmdir_all(os.join_path(dir, 'docs')) or { panic(err) }463	write(outside, 'a.md', 'precious\n')464	os.symlink(outside, os.join_path(dir, 'docs')) or { panic(err) }465	assert run(dir, 'save', 'docs is a link now').code == 0466	head := run(dir, 'status', '--json').out467	r := run(dir, 'load', first, '--yes')468	assert r.code == 1469	assert r.err.contains('docs')470	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'471	assert run(dir, 'status', '--json').out == head472}473474// A restore records its save first, then writes files. When the writing stops475// part way, the half-written tree is not somebody's work: saving it would476// record (and offer) a tree that undoes changes nobody asked to undo. Every477// command that would build on it points at revert, which finishes the job.478fn test_a_restore_cut_short_points_at_revert() {479	dir := temp_repo('cut-short')480	defer {481		os.chmod(os.join_path(dir, 'zz'), 0o755) or {}482		os.rmdir_all(dir) or {}483	}484	init_repo(dir)485	write(dir, 'zero', '0\n')486	assert run(dir, 'save', 'zero').code == 0487	write(dir, 'a.txt', 'v1\n')488	write(dir, 'zz/f', 'v1\n')489	assert run(dir, 'save', 'first').code == 0490	write(dir, 'a.txt', 'v2\n')491	write(dir, 'zz/f', 'v2\n')492	assert run(dir, 'save', 'second').code == 0493	// a.txt is written, then the read-only folder stops the restore: the494	// tree is genuinely half one save and half the other.495	os.chmod(os.join_path(dir, 'zz'), 0o555)!496	stopped := run(dir, 'undo', '--yes')497	assert stopped.code == 1498	assert stopped.err.contains('koh revert')499	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'500	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v2\n'501	// Even a status that cannot read the tree says what happened.502	os.chmod(os.join_path(dir, 'zz'), 0o000)!503	assert run(dir, 'status').err.contains('koh revert')504	os.chmod(os.join_path(dir, 'zz'), 0o755)!505506	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":true')507	for args in [['save', 'half'], ['checkpoint', 'half'], ['undo', '--yes']] {508		r := run(dir, ...args)509		assert r.code == 1510		assert r.err.contains('koh revert')511	}512	assert run(dir, 'revert', '--yes').code == 0513	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'v1\n'514	assert os.read_file(os.join_path(dir, 'zz/f'))! == 'v1\n'515	assert run(dir, 'status', '--json').out.contains('"restore_unfinished":false')516	write(dir, 'a.txt', 'v3\n')517	assert run(dir, 'save', 'carry on').code == 0518}519520// Doctor clears peek folders left from earlier days, never one somebody may521// be reading right now.522fn test_doctor_sweeps_only_old_peek_folders() {523	dir := temp_repo('peek-sweep')524	// V's temp_dir is /tmp on macOS whatever TMPDIR says, so these live in525	// the real temp directory under names no save could have.526	fresh := os.join_path(os.temp_dir(), 'koh-peek-fresh${os.getpid()}')527	old := os.join_path(os.temp_dir(), 'koh-peek-old${os.getpid()}')528	defer {529		os.rmdir_all(dir) or {}530		os.rmdir_all(fresh) or {}531		os.rmdir_all(old) or {}532	}533	init_repo(dir)534	write(dir, 'a.txt', 'one\n')535	assert run(dir, 'save', 'one').code == 0536	os.mkdir_all(fresh) or { panic(err) }537	os.mkdir_all(old) or { panic(err) }538	two_days_ago := time.now().unix() - 2 * 86400539	os.utime(old, two_days_ago, two_days_ago) or { panic(err) }540	assert run(dir, 'doctor', '--json').code == 0541	assert os.exists(fresh)542	assert !os.exists(old)543}544545// A file saved long ago and ignored since holds work no save has. Loading the546// old save must not write over it; the document says a restore never touches547// ignored files.548fn test_a_restore_never_overwrites_an_ignored_file() {549	dir := temp_repo('ignored-restore')550	defer { os.rmdir_all(dir) or {} }551	init_repo(dir)552	write(dir, '.env', 'KEY=saved long ago\n')553	first := run(dir, 'save', 'with env', '--json').out.all_after('"id":"')[..12]554	write(dir, '.kohignore', '.env\n')555	assert run(dir, 'save', 'ignore env').code == 0556	write(dir, '.env', 'KEY=never saved\n')557	assert run(dir, 'load', first, '--yes').code == 0558	assert os.read_file(os.join_path(dir, '.env'))! == 'KEY=never saved\n'559560	// Where the ignored file is missing, the restore still brings it back.561	other := temp_repo('ignored-restore-missing')562	defer { os.rmdir_all(other) or {} }563	init_repo(other)564	write(other, '.env', 'KEY=saved long ago\n')565	again := run(other, 'save', 'with env', '--json').out.all_after('"id":"')[..12]566	write(other, '.kohignore', '.env\n')567	assert run(other, 'save', 'ignore env').code == 0568	os.rm(os.join_path(other, '.env')) or { panic(err) }569	assert run(other, 'load', again, '--yes').code == 0570	assert os.read_file(os.join_path(other, '.env'))! == 'KEY=saved long ago\n'571}572573// A going-back preview lists paths only. Running diff(1) per file to draw it574// cost 27 s for 5,000 changed files, so it must not run diff at all.575fn test_a_going_back_preview_does_not_run_diff() {576	dir := temp_repo('preview-nodiff')577	home := temp_repo('preview-nodiff-home')578	defer {579		os.rmdir_all(dir) or {}580		os.rmdir_all(home) or {}581	}582	init_repo(dir)583	write(dir, 'a.txt', 'one\n')584	assert run_home(dir, home, 'save', 'one').code == 0585	write(dir, 'a.txt', 'two\n')586	assert run_home(dir, home, 'save', 'two').code == 0587	fake := os.join_path(home, 'bin')588	os.mkdir_all(fake) or { panic(err) }589	marker := os.join_path(home, 'diff-ran')590	os.write_file(os.join_path(fake, 'diff'), '#!/bin/sh\ntouch ${q(marker)}\nexit 2\n') or {591		panic(err)592	}593	os.chmod(os.join_path(fake, 'diff'), 0o755) or { panic(err) }594	assert run_home_with_path(dir, home, fake, 'undo', '--yes').code == 0595	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'596	assert !os.exists(marker)597}598599// A restore rewrites only what differs. Rewriting every file resets every600// mtime, so the next status has to hash the whole tree again.601fn test_a_restore_leaves_unchanged_files_alone() {602	dir := temp_repo('restore-skip')603	defer { os.rmdir_all(dir) or {} }604	init_repo(dir)605	write(dir, 'a.txt', 'one\n')606	write(dir, 'same.txt', 'never changes\n')607	assert run(dir, 'save', 'one').code == 0608	write(dir, 'a.txt', 'two\n')609	assert run(dir, 'save', 'two').code == 0610	long_ago := i64(1700000000)611	os.utime(os.join_path(dir, 'same.txt'), long_ago, long_ago) or { panic(err) }612	assert run(dir, 'undo', '--yes').code == 0613	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'614	assert os.file_last_mod_unix(os.join_path(dir, 'same.txt')) == long_ago615}616617// `save` records the executable bit, so `status` has to see it too, or a618// chmod would be invisible until it turned up in a save.619fn test_status_sees_an_executable_bit_change() {620	dir := temp_repo('chmod')621	defer { os.rmdir_all(dir) or {} }622	init_repo(dir)623	write(dir, 'run.sh', 'echo hi\n')624	assert run(dir, 'save', 'script').code == 0625	os.chmod(os.join_path(dir, 'run.sh'), 0o755) or { panic(err) }626	status := run(dir, 'status', '--json')627	assert status.out.contains('"dirty":true')628	assert status.out.contains('"modified":["run.sh"]')629}630631fn test_view_and_diff() {632	dir := temp_repo('history')633	defer { os.rmdir_all(dir) or {} }634	init_repo(dir)635	write(dir, 'a.txt', 'one\n')636	first := run(dir, 'save', 'one', '--session', 'alpha', '--json')637	id1 := first.out.all_after('"id":"')[..12]638	write(dir, 'a.txt', 'two\n')639	second := run(dir, 'save', 'two', '--session', 'beta', '--json')640	id2 := second.out.all_after('"id":"')[..12]641	cp := run(dir, 'checkpoint', 'checkpoint', '--json')642	assert cp.code == 0643	printed := run(dir, 'view')644	assert printed.code == 0645	assert printed.out.contains('▸')646	assert printed.out.contains('◐')647	lj := run(dir, 'view', '--json')648	assert lj.code == 0649	assert lj.out.contains('"head_id"')650	assert lj.out.contains('"saves"')651	assert run(dir, 'view', '--since', 'today').out.contains('two')652	session := run(dir, 'view', '--session', 'alpha')653	assert session.out.contains('one')654	assert !session.out.contains('two')655	assert run(dir, 'view', '--since', '9999-01-01').out.contains('no saves in that range')656	write(dir, 'a.txt', 'three\n')657	d := run(dir, 'diff')658	assert d.code == 0659	assert d.out.contains('--- a/')660	assert d.out.contains('+++ b/')661	assert run(dir, 'diff', id1).code == 0662	assert run(dir, 'diff', id1, id2).code == 0663	dj := run(dir, 'diff', '--json')664	assert dj.code == 0665	assert dj.out.contains('"from"')666	assert dj.out.contains('"to"')667	assert dj.out.contains('"files"')668	assert dj.out.contains('"change":"modified"')669	assert run(dir, 'diff', 'not-a-real-id').code == 1670	assert run(dir, 'diff', id1, id2, 'third').code == 1671	write(dir, 'blob.bin', '\x00\x01\x02')672	diff_binary := run(dir, 'diff', '--json')673	assert diff_binary.out.contains('"binary":true')674	assert diff_binary.out.contains('Binary files differ')675}676677fn test_undo_revert_and_load() {678	dir := temp_repo('restore')679	defer { os.rmdir_all(dir) or {} }680	init_repo(dir)681	write(dir, 'a.txt', 'one\n')682	one := run(dir, 'save', 'one', '--json').out683	id1 := one.all_after('"id":"')[..12]684	write(dir, 'a.txt', 'two\n')685	write(dir, 'gone.txt', 'gone\n')686	second := run(dir, 'save', 'two', '--json').out687	id2 := second.all_after('"id":"')[..12]688	write(dir, 'a.txt', 'three\n')689	third := run(dir, 'save', 'three', '--json').out690	id3 := third.all_after('"id":"')[..12]691	// Unsaved work — here a file never saved — blocks every going-back but692	// revert, as in Koh 2: a restore must never overwrite what only the disk has.693	write(dir, 'never.txt', 'keep me\n')694	view_before := run(dir, 'view').out695	for args in [['undo', '--yes'], ['load', id1, '--yes'], ['pluck', id2, '--yes']] {696		blocked := run(dir, ...args)697		assert blocked.code == 1698		assert blocked.err.contains('unsaved changes')699	}700	assert run(dir, 'view').out == view_before701	os.rm(os.join_path(dir, 'never.txt')) or { panic(err) }702	write(dir, 'a.txt', 'edited, never saved\n')703	assert run(dir, 'undo', '--yes').err.contains('unsaved changes')704	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'edited, never saved\n'705	write(dir, 'a.txt', 'three\n')706	os.rm(os.join_path(dir, 'gone.txt')) or { panic(err) }707	assert run(dir, 'load', id1, '--yes').err.contains('unsaved changes')708	write(dir, 'gone.txt', 'gone\n')709	undo := run(dir, 'undo', '--yes', '--json')710	assert undo.code == 0711	if !undo.out.contains(id2) {712		panic('undo JSON did not name ${id2}: ${undo.out}')713	}714	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'715	assert os.exists(os.join_path(dir, 'gone.txt'))716	assert run(dir, 'load', id3, '--yes').code == 0717	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'three\n'718	assert run(dir, 'undo', '2', '--yes').code == 0719	assert run(dir, 'load', id2, '--yes').code == 0720	assert run(dir, 'undo', '99', '--yes').err.contains('nothing before')721	write(dir, 'a.txt', 'dirty\n')722	before := run(dir, 'view')723	refuse := run(dir, 'revert')724	assert refuse.code == 1725	assert refuse.err.contains('needs --yes when not interactive')726	assert run(dir, 'view').out == before.out727	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'728	write(dir, 'untracked.txt', 'remove\n')729	rv := run(dir, 'revert', '--yes', '--json')730	assert rv.code == 0731	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'732	assert !os.exists(os.join_path(dir, 'untracked.txt'))733	// The way back to the discarded work is named, not left to be found.734	kept := rv.out.all_after('"checkpoint":"')[..12]735	assert run(dir, 'load', kept, '--yes').code == 0736	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'dirty\n'737	assert os.read_file(os.join_path(dir, 'untracked.txt'))! == 'remove\n'738	write(dir, 'a.txt', 'dirty again\n')739	assert run(dir, 'revert', '--yes').out.contains('koh load ')740	assert run(dir, 'revert', '--yes').out.contains('working tree already matches')741	assert run(dir, 'load', '--checkpoint', '--yes').code == 0742	assert run(dir, 'load', id2, '--json').code == 1743	assert run(dir, 'load', id2, '--json').err.contains('error')744	assert run(dir, 'load').code == 2745	assert run(dir, 'load', 'unknown-id', '--yes').code == 1746}747748fn test_flag_and_flagged_view() {749	dir := temp_repo('flag')750	defer { os.rmdir_all(dir) or {} }751	init_repo(dir)752	write(dir, 'flag.txt', 'one\n')753	saved := run(dir, 'save', 'flag me', '--json')754	id := saved.out.all_after('"id":"')[..12]755	flagged := run(dir, 'flag', id, '--reason', 'unsafe', '--json')756	assert flagged.code == 0757	assert flagged.out.contains('"flagged":true')758	assert flagged.out.contains('"reason":"unsafe"')759	list := run(dir, 'flag', '--json')760	assert list.code == 0761	assert list.out.contains(id)762	assert list.out.contains('unsafe')763	assert run(dir, 'view').out.contains('⚑')764	assert run(dir, 'flag', '--clear', id).code == 0765	assert run(dir, 'flag').out.contains('nothing is flagged')766	assert run(dir, 'flag', 'unknown-id').code == 1767	assert run(dir, 'flag').code == 0768}769770fn test_pluck_forward_reverse_dry_run_and_conflict() {771	dir := temp_repo('pluck')772	defer { os.rmdir_all(dir) or {} }773	init_repo(dir)774	write(dir, 'a.txt', 'one\n')775	first := run(dir, 'save', 'one', '--json').out776	id1 := first.all_after('"id":"')[..12]777	write(dir, 'a.txt', 'two\n')778	second := run(dir, 'save', 'two', '--json').out779	id2 := second.all_after('"id":"')[..12]780	assert run(dir, 'load', id1, '--yes').code == 0781	dry := run(dir, 'pluck', id2, '--dry-run')782	assert dry.code == 0783	assert dry.out.contains('a.txt')784	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'785	assert run(dir, 'pluck', id2, '--yes').code == 0786	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'two\n'787	assert run(dir, 'pluck', '--reverse', id2, '--yes').code == 0788	assert os.read_file(os.join_path(dir, 'a.txt'))! == 'one\n'789	write(dir, 'a.txt', 'different\n')790	assert run(dir, 'pluck', id2, '--dry-run').code == 1791	assert run(dir, 'save', 'different').code == 0792	conflict := run(dir, 'pluck', id2, '--yes')793	assert conflict.code == 1794	assert conflict.err.contains('a.txt')795	assert run(dir, 'pluck').code == 2796	assert run(dir, 'pluck', 'unknown-id').code == 1797}798799fn test_peek_and_doctor() {800	dir := temp_repo('peek-doctor')801	defer { os.rmdir_all(dir) or {} }802	init_repo(dir)803	write(dir, 'peek.txt', 'peek me\n')804	assert run(dir, 'save', 'peekable').code == 0805	id := run(dir, 'view', '--json').out.all_after('"id":"')[..12]806	before_view := run(dir, 'view', '--json').out807	peek := run(dir, 'peek', id, '--json')808	assert peek.code == 0809	peek_path := peek.out.all_after('"path":"').before('"')810	assert peek.out.contains('"id":"${id}"')811	assert os.read_file(os.join_path(peek_path, 'peek.txt'))! == 'peek me\n'812	assert run(dir, 'status').out.contains('no changes')813	assert run(dir, 'view', '--json').out == before_view814	assert run(dir, 'peek').code == 2815	assert run(dir, 'peek', 'unknown-id').code == 1816	backup := os.join_path(dir, 'doctor.backup')817	healthy := run(dir, 'doctor')818	assert healthy.code == 0819	assert healthy.out.contains('is sound')820	report := run(dir, 'doctor', '--json')821	assert report.code == 0822	for key in ['problems', 'objects', 'saves', 'checkpoints', 'cached_files', 'peek_folders_removed',823		'backup'] {824		read_json_has(report.out, key)825	}826	backed := run(dir, 'doctor', '--backup', backup)827	assert backed.code == 0828	assert os.exists(backup)829	assert backed.out.contains(backup)830	assert run(dir, 'doctor', '--backup', backup).code == 1831	assert run(dir, 'peek', id, '--json').code == 0832	// A peek made today is left for whoever is reading it.833	kept := run(dir, 'doctor', '--json')834	assert kept.code == 0835	assert os.exists(peek_path)836	os.rmdir_all(peek_path) or {}837}838839fn test_strip_refuses_without_terminal() {840	dir := temp_repo('strip')841	defer { os.rmdir_all(dir) or {} }842	init_repo(dir)843	write(dir, 'secret.txt', 'keep\n')844	assert run(dir, 'save', 'secret').code == 0845	before_view := run(dir, 'view', '--json').out846	refused := run(dir, 'strip', 'secret.txt')847	assert refused.code == 1848	assert refused.err.contains('needs a terminal')849	assert run(dir, 'view', '--json').out == before_view850	assert os.read_file(os.join_path(dir, 'secret.txt'))! == 'keep\n'851	assert run(dir, 'view', '--json').out.contains('secret')852}853854// A whole-history strip bans the path: `.kohignore` names it, once, and the file left on disk855// is never unsaved work or part of a save again.856fn test_strip_adds_the_path_to_kohignore_and_it_stays_out() {857	dir := temp_repo('strip-ignore')858	home := temp_repo('strip-ignore-home')859	defer { os.rmdir_all(dir) or {} }860	defer { os.rmdir_all(home) or {} }861	init_repo(dir)862	write(dir, 'secret.txt', 'leaked\n')863	write(dir, 'keep.txt', 'fine\n')864	assert run_home(dir, home, 'save', 'leak').code == 0865	stripped := run_pty_home(dir, home, ['y', 'secret.txt'], 'strip', 'secret.txt')866	assert stripped.code == 0, stripped.out867	assert stripped.out.contains('added /secret.txt to .kohignore')868	ignore_path := os.join_path(dir, '.kohignore')869	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1870	assert run_home(dir, home, 'save', 'ignore the stripped secret').code == 0871	write(dir, 'secret.txt', 'leaked again\n')872	assert run_home(dir, home, 'status', '--json').out.contains('"dirty":false')873	// Running the strip again (with no remote, it stays pending) adds no second line.874	again := run_pty_home(dir, home, [], 'strip', 'secret.txt')875	assert again.code == 0, again.out876	assert os.read_file(ignore_path)!.split_into_lines().filter(it == '/secret.txt').len == 1877}878879// `koh view` is the one way into the history: the whole line by default,880// checkpoints alone with the flag, and the two lists never overlap.881fn test_view_shows_the_line_and_checkpoints_apart() {882	dir := temp_repo('view')883	defer { os.rmdir_all(dir) or {} }884	init_repo(dir)885	write(dir, 'view.txt', 'one\n')886	assert run(dir, 'save', 'plain save').code == 0887	assert run(dir, 'checkpoint', 'checkpoint save').code == 0888	line := run(dir, 'view')889	assert line.code == 0890	assert line.out.contains('plain save')891	assert line.out.contains('checkpoint save')892	checkpoints := run(dir, 'view', '--checkpoints')893	assert checkpoints.code == 0894	assert checkpoints.out.contains('checkpoint save')895	assert !checkpoints.out.contains('plain save')896	json_line := run(dir, 'view', '--json')897	assert json_line.code == 0898	assert json_line.out.contains('"is_checkpoint":false')899	assert json_line.out.contains('"is_checkpoint":true')900	json_checkpoints := run(dir, 'view', '--checkpoints', '--json')901	assert json_checkpoints.code == 0902	assert json_checkpoints.out.contains('"is_checkpoint":true')903	assert !json_checkpoints.out.contains('"is_checkpoint":false')904	// `view` takes no arguments, so a stray one is a usage error, and the names905	// it replaced are gone rather than hidden: the diagnostic says which.906	assert run(dir, 'view', 'extra').code == 2907	for gone in ['log', 'saves', 'checkpoints'] {908		refused := run(dir, gone)909		assert refused.code == 2910		assert refused.err.contains('unknown command "${gone}"')911	}912	// Every save is on the whole line exactly once, as the JSON says.913	assert line.out.split_into_lines().len == json_line.out.count('"id":"')914}915916fn test_remote_configuration_is_isolated_and_atomic() {917	dir := temp_repo('remote')918	home := temp_repo('remote-home')919	defer {920		os.rmdir_all(dir) or {}921		os.rmdir_all(home) or {}922	}923	empty := run_home(dir, home, 'remote', '--json')924	assert empty.code == 0925	assert empty.out.contains('"configured":false')926	target := os.join_path(home, 'remote-store')927	set := run_home(dir, home, 'remote', 'folder', target)928	assert set.code == 0929	assert os.is_dir(target)930	state := run_home(dir, home, 'remote', '--json')931	assert state.code == 0932	assert state.out.contains('"kind":"folder"')933	assert state.out.contains(target)934	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').code == 1935	assert run_home(dir, home, 'remote', '--json').out.contains(target)936	assert run_home(dir, home, 'remote', 's3', 'http://127.0.0.1:1', 'bucket', 'region').err.contains('KOH_ACCESS_KEY')937	assert run_home(dir, home, 'remote', '--forget').code == 0938	assert run_home(dir, home, 'remote', '--json').out.contains('"configured":false')939}940941// The files under ~/.config/koh can be written by hand instead of by942// `koh remote`, and are then read the same way.943fn test_remote_written_by_hand() {944	dir := temp_repo('remote-by-hand')945	home := temp_repo('remote-by-hand-home')946	defer {947		os.rmdir_all(dir) or {}948		os.rmdir_all(home) or {}949	}950	config := os.join_path(home, '.config', 'koh')951	os.mkdir_all(config) or { panic(err) }952	target := os.join_path(home, 'remote-store')953	os.mkdir_all(target) or { panic(err) }954	os.write_file(os.join_path(config, 'remote'), 'kind = folder\npath = ${target}\n') or {955		panic(err)956	}957	assert run_home(dir, home, 'init').code == 0958	os.write_file(os.join_path(dir, 'a.txt'), 'a\n') or { panic(err) }959	assert run_home(dir, home, 'save', 'first').code == 0960	offered := run_home(dir, home, 'offer', '--json')961	assert offered.code == 0962	assert offered.out.contains('"head"')963964	// Keys anyone else can read are refused before they are ever sent.965	os.write_file(os.join_path(config, 'remote'), 'kind=s3\nendpoint=http://127.0.0.1:1\nbucket=b\nregion=r\n') or {966		panic(err)967	}968	credentials := os.join_path(config, 'credentials')969	os.write_file(credentials, 'access_key=AK\nsecret_key=SK\n') or { panic(err) }970	os.chmod(credentials, 0o644) or { panic(err) }971	loose := run_home(dir, home, 'offer')972	assert loose.code == 1973	assert loose.err.contains('chmod 600')974975	// A setting koh cannot read is replaced by setting the remote again.976	os.write_file(os.join_path(config, 'remote'), 'kind=ftp\n') or { panic(err) }977	unreadable := run_home(dir, home, 'offer')978	assert unreadable.code == 1979	assert unreadable.err.contains('not readable')980	assert run_home(dir, home, 'remote', 'folder', target).code == 0981	assert run_home(dir, home, 'offer').code == 0982}983984// A stolen repo belongs to the repo it was stolen from, whatever its folder is985// called later: renaming it must not start a second repo on the remote.986fn test_a_renamed_stolen_repo_keeps_offering_to_its_repo() {987	syncroot := temp_repo('rename-steal')988	home := temp_repo('rename-steal-home')989	defer {990		os.rmdir_all(syncroot) or {}991		os.rmdir_all(home) or {}992	}993	remote := os.join_path(syncroot, 'remote')994	a := os.join_path(syncroot, 'A', 'proj')995	b_parent := os.join_path(syncroot, 'B')996	os.mkdir_all(a) or { panic(err) }997	os.mkdir_all(b_parent) or { panic(err) }998	init_repo(a)999	write(a, 'a.txt', 'from A\n')1000	assert run_home(a, home, 'remote', 'folder', remote).code == 01001	assert run_home(a, home, 'save', 'A first').code == 01002	assert run_home(b_parent, home, 'steal', 'proj').code == 01003	renamed := os.join_path(b_parent, 'renamed')1004	os.mv(os.join_path(b_parent, 'proj'), renamed) or { panic(err) }1005	write(renamed, 'b.txt', 'from B\n')1006	assert run_home(renamed, home, 'save', 'B first').code == 01007	assert !os.exists(os.join_path(remote, 'renamed'))1008	assert run_home(a, home, 'steal').code == 01009	assert os.read_file(os.join_path(a, 'b.txt'))! == 'from B\n'1010}10111012// A damaged object on the remote stops a steal, names the object, and leaves1013// no half-made folder that would make the retry refuse.1014fn test_steal_of_a_damaged_remote_leaves_nothing() {1015	syncroot := temp_repo('damaged')1016	home := temp_repo('damaged-home')1017	defer {1018		os.rmdir_all(syncroot) or {}1019		os.rmdir_all(home) or {}1020	}1021	remote := os.join_path(syncroot, 'remote')1022	a := os.join_path(syncroot, 'A', 'proj')1023	b_parent := os.join_path(syncroot, 'B')1024	os.mkdir_all(a) or { panic(err) }1025	os.mkdir_all(b_parent) or { panic(err) }1026	init_repo(a)1027	write(a, 'a.txt', 'from A\n')1028	assert run_home(a, home, 'remote', 'folder', remote).code == 01029	assert run_home(a, home, 'save', 'A first').code == 01030	objects := os.join_path(remote, 'proj', 'objects')1031	for name in os.ls(objects) or { panic(err) } {1032		os.chmod(os.join_path(objects, name), 0o644) or {}1033		os.write_file(os.join_path(objects, name), 'junk') or { panic(err) }1034	}1035	stolen := run_home(b_parent, home, 'steal', 'proj')1036	assert stolen.code == 11037	assert stolen.err.contains('is damaged')1038	assert !os.exists(os.join_path(b_parent, 'proj'))1039}10401041fn test_steal_drops_crafted_unsafe_paths_and_lands_the_rest() {1042	syncroot := temp_repo('unsafe-remote')1043	home := temp_repo('unsafe-remote-home')1044	defer {1045		os.rmdir_all(syncroot) or {}1046		os.rmdir_all(home) or {}1047	}1048	remote := os.join_path(syncroot, 'remote')1049	a := os.join_path(syncroot, 'A', 'proj')1050	b_parent := os.join_path(syncroot, 'B')1051	os.mkdir_all(a) or { panic(err) }1052	os.mkdir_all(b_parent) or { panic(err) }1053	init_repo(a)1054	write(a, 'safe.txt', 'safe\n')1055	assert run_home(a, home, 'remote', 'folder', remote).code == 01056	id := run_home(a, home, 'save', 'crafted', '--json').out.all_after('"id":"')[..12]1057	assert run_home(a, home, 'offer').code == 01058	record_path := os.join_path(remote, 'proj', 'saves', id)1059	record := os.read_file(record_path) or { panic(err) }1060	path_at := record.index('"path":"safe.txt"') or { panic('safe path missing from ${record}') }1061	file_start := record[..path_at].last_index('{') or { panic('safe file start missing') }1062	file_end := path_at + (record[path_at..].index('}') or { panic('safe file end missing') }) + 11063	file := record[file_start..file_end]1064	mut files := [file]1065	for path in ['../outside.txt', '/etc/koh-test', 'a/../../outside.txt', 'bad\\\\name',1066		'control\\rname'] {1067		files << file.replace('safe.txt', path)1068	}1069	os.write_file(record_path, record[..file_start] + files.join(',') + record[file_end..]) or {1070		panic(err)1071	}10721073	stolen := run_home(b_parent, home, 'steal', 'proj')1074	assert stolen.code == 0, stolen.err1075	for dropped in ['../outside.txt', 'bad\\\\name', 'control\\x0dname'] {1076		assert (stolen.out + stolen.err).contains('dropped unsafe path ${dropped}'), stolen.out + stolen.err1077	}1078	assert os.read_file(os.join_path(b_parent, 'proj', 'safe.txt'))! == 'safe\n'1079	assert !os.exists(os.join_path(b_parent, 'outside.txt'))1080	assert !os.exists(os.join_path(b_parent, 'proj', 'bad', 'name'))1081	assert !os.exists('${b_parent}/proj/control\rname')1082}10831084fn test_offer_steal_folder_remote() {1085	syncroot := temp_repo('sync')1086	home := temp_repo('sync-home')1087	defer {1088		os.rmdir_all(syncroot) or {}1089		os.rmdir_all(home) or {}1090	}1091	remote := os.join_path(syncroot, 'remote')1092	a := os.join_path(syncroot, 'A', 'proj')1093	b_parent := os.join_path(syncroot, 'B')1094	os.mkdir_all(a) or { panic(err) }1095	os.mkdir_all(b_parent) or { panic(err) }1096	init_repo(a)1097	write(a, 'a.txt', 'from A\n')1098	assert run_home(a, home, 'remote', 'folder', remote).code == 01099	assert run_home(a, home, 'save', 'A first').code == 01100	stolen := run_home(b_parent, home, 'steal', 'proj')1101	assert stolen.code == 01102	b := os.join_path(b_parent, 'proj')1103	assert os.read_file(os.join_path(b, 'a.txt'))! == 'from A\n'1104	write(b, 'b.txt', 'from B\n')1105	assert run_home(b, home, 'save', 'B first').code == 01106	write(a, 'a2.txt', 'second\n')1107	assert run_home(a, home, 'save', 'A second').code == 01108	assert run_home(a, home, 'steal').code == 01109	assert os.exists(os.join_path(a, 'b.txt'))1110	assert run_home(b_parent, home, 'steal', '--list').out.contains('proj')1111	write(a, 'clash.txt', 'base\n')1112	assert run_home(a, home, 'save', 'clash base').code == 01113	assert run_home(b, home, 'steal').code == 01114	write(a, 'clash.txt', 'A version\n')1115	assert run_home(a, home, 'save', 'A clash').code == 01116	write(b, 'clash.txt', 'B version\n')1117	assert run_home(b, home, 'save', 'B clash').code == 01118	refused := run_home(b, home, 'steal')1119	assert refused.code == 11120	assert refused.err.contains('--mine') || refused.err.contains('--theirs')1121	b_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1122	theirs := run_home(b, home, 'steal', '--theirs', '--json')1123	assert theirs.code == 01124	// The pre-combine tree is off the line now; the way back must be named,1125	// or an agent without the history view cannot find it.1126	assert theirs.out.contains('"previous_head":"${b_head}"')1127	assert theirs.out.contains('"kept_versions":["clash.txt:${b_head}"]')1128	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1129	assert run_home(b, home, 'load', b_head, '--yes').code == 01130	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B version\n'1131	assert run_home(b, home, 'load', theirs.out.all_after('"head":"')[..12], '--yes').code == 01132	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'A version\n'1133	write(a, 'clash.txt', 'A second\n')1134	assert run_home(a, home, 'save', 'A second clash').code == 01135	write(b, 'clash.txt', 'B second\n')1136	assert run_home(b, home, 'save', 'B second clash').code == 01137	assert run_home(b, home, 'steal', '--mine').code == 01138	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'B second\n'1139	assert run_home(b, home, 'view').out.contains('combine: kept mine for')1140}11411142fn test_guided_steal_walks_the_terminal_and_can_cancel() {1143	syncroot := temp_repo('guided-steal')1144	home := temp_repo('guided-steal-home')1145	defer {1146		os.rmdir_all(syncroot) or {}1147		os.rmdir_all(home) or {}1148	}1149	remote := os.join_path(syncroot, 'remote')1150	a := os.join_path(syncroot, 'A', 'proj')1151	b_parent := os.join_path(syncroot, 'B')1152	os.mkdir_all(a) or { panic(err) }1153	os.mkdir_all(b_parent) or { panic(err) }1154	init_repo(a)1155	write(a, 'clash.txt', 'base\n')1156	write(a, 'other.txt', 'base\n')1157	write(a, 'same.txt', 'base\n')1158	write(a, 'remote-only.txt', 'base\n')1159	write(a, 'local-only.txt', 'base\n')1160	assert run_home(a, home, 'remote', 'folder', remote).code == 01161	assert run_home(a, home, 'save', 'base').code == 01162	assert run_home(b_parent, home, 'steal', 'proj').code == 01163	b := os.join_path(b_parent, 'proj')11641165	write(b, 'dirty.txt', 'mine\n')1166	before := run_home(b, home, 'status', '--json').out1167	quit := run_pty_home(b, home, ['q'], 'steal')1168	assert quit.out.contains('steal proj')1169	assert quit.out.contains('you have 1 unsaved file')1170	assert quit.out.contains('dirty.txt')1171	assert run_home(b, home, 'status', '--json').out == before1172	// A save needs a message; an empty one stops, says so, and saves nothing.1173	unsaid := run_pty_home(b, home, ['s', ''], 'steal')1174	assert unsaid.code == 11175	assert unsaid.out.contains('no message — nothing was saved')1176	assert run_home(b, home, 'status', '--json').out == before1177	checkpoint := run_pty_home(b, home, ['c'], 'steal')1178	assert checkpoint.code == 0, checkpoint.err1179	assert run_home(b, home, 'view', '--checkpoints').out.contains('before steal')11801181	assert run_home(a, home, 'steal').code == 01182	write(a, 'forward.txt', 'new\n')1183	assert run_home(a, home, 'save', 'fast forward').code == 01184	forward := run_pty_home(b, home, []string{}, 'steal')1185	assert forward.out.contains('proj is up to date · 1 new save')1186	assert forward.out.split_into_lines().filter(it.trim_space() != '').len == 11187	write(a, 'clash.txt', 'remote\n')1188	write(a, 'other.txt', 'remote\n')1189	write(a, 'same.txt', 'identical\n')1190	write(a, 'remote-only.txt', 'remote\n')1191	assert run_home(a, home, 'save', 'remote change').code == 01192	write(b, 'clash.txt', 'mine\n')1193	write(b, 'other.txt', 'mine\n')1194	write(b, 'same.txt', 'identical\n')1195	write(b, 'local-only.txt', 'mine\n')1196	assert run_home(b, home, 'save', 'local change').code == 01197	local_head := run_home(b, home, 'status', '--json').out.all_after('"head_id":"')[..12]1198	// `d` opens both changes in the pager, which Enter leaves; `?` explains the two sides.1199	cancel := run_pty_home(b, home, ['d', '', '?', 'm', 'b', 't', 't', 'n'], 'steal')1200	assert cancel.out.contains('your changes')1201	assert cancel.out.contains('remote changes')1202	assert cancel.out.contains('Nothing is lost either way')1203	// The shared save's age, relative: seconds old here, so `now` unless the machine is slow.1204	since := cancel.out.split_into_lines().filter(it.contains('both moved since'))1205	assert since.len == 11206	assert since[0].trim_space().ends_with(' · now') || since[0].trim_space().ends_with(' ago'), since[0]1207	assert cancel.out.contains('5 files changed')1208	assert cancel.out.contains('2 combine by themselves')1209	assert cancel.out.contains('1 changed the same way')1210	assert cancel.out.contains('2 need you')1211	assert cancel.out.contains('ready to combine')1212	assert run_home(b, home, 'status', '--json').out.contains('"head_id":"${local_head}"')1213	assert os.read_file(os.join_path(b, 'clash.txt'))! == 'mine\n'12141215	done := run_pty_home(b, home, ['y'], 'steal', '--theirs')1216	assert done.out.contains('combined · offered to proj')1217	assert done.out.contains('took theirs: clash.txt · other.txt')1218	assert !done.out.contains('kept mine')1219	assert done.out.contains('to undo all of it: koh load ${local_head}')1220	assert done.out.contains('your clash.txt is in ${local_head}')1221	assert !done.out.contains('\x1b')1222	for line in done.out.split_into_lines() {1223		assert line.runes().len <= 80, line1224	}1225}12261227// A steal brings in the whole history, flags included; both output forms must1228// say which saves came in flagged, and why.1229fn test_a_steal_reports_flagged_saves() {1230	syncroot := temp_repo('steal-flags')1231	home := temp_repo('steal-flags-home')1232	defer {1233		os.rmdir_all(syncroot) or {}1234		os.rmdir_all(home) or {}1235	}1236	a := os.join_path(syncroot, 'A', 'proj')1237	os.mkdir_all(a) or { panic(err) }1238	init_repo(a)1239	assert run_home(a, home, 'remote', 'folder', os.join_path(syncroot, 'remote')).code == 01240	write(a, 'a.txt', 'one\n')1241	id := run_home(a, home, 'save', 'risky', '--json').out.all_after('"id":"')[..12]1242	assert run_home(a, home, 'flag', id, '--reason', 'broke the build').code == 01243	assert run_home(a, home, 'offer').code == 01244	for name in ['B', 'C'] {1245		os.mkdir_all(os.join_path(syncroot, name)) or { panic(err) }1246	}1247	json_stolen := run_home(os.join_path(syncroot, 'B'), home, 'steal', 'proj', '--json')1248	assert json_stolen.code == 01249	assert json_stolen.out.contains('"flagged":["${id}"]')1250	text_stolen := run_home(os.join_path(syncroot, 'C'), home, 'steal', 'proj')1251	assert text_stolen.code == 01252	assert text_stolen.out.contains('[${id}] came in flagged — broke the build')1253}12541255// A folder remote on a disk or share that is not mounted is simply not there.1256// Creating it would put the saves in a stand-in folder the other machine never1257// sees; the offer must say what is wrong instead.1258fn test_an_unmounted_folder_remote_is_not_recreated() {1259	syncroot := temp_repo('unmounted')1260	home := temp_repo('unmounted-home')1261	defer {1262		os.rmdir_all(syncroot) or {}1263		os.rmdir_all(home) or {}1264	}1265	mount := os.join_path(syncroot, 'nas')1266	remote := os.join_path(mount, 'koh')1267	a := os.join_path(syncroot, 'proj')1268	os.mkdir_all(a) or { panic(err) }1269	init_repo(a)1270	assert run_home(a, home, 'remote', 'folder', remote).code == 01271	write(a, 'a.txt', 'one\n')1272	assert run_home(a, home, 'save', 'first').code == 01273	os.rename(mount, os.join_path(syncroot, 'nas-unplugged')) or { panic(err) }1274	os.mkdir(mount) or { panic(err) }1275	offered := run_home(a, home, 'offer')1276	assert offered.code == 11277	assert offered.err.contains('mounted')1278	assert !os.exists(remote)1279	write(a, 'a.txt', 'two\n')1280	saved := run_home(a, home, 'save', 'second')1281	assert saved.code == 01282	assert saved.out.contains('mounted')1283	assert !os.exists(remote)1284}12851286fn test_man_and_koh2_handoff() {1287	dir := temp_repo('man')1288	home := temp_repo('man-home')1289	defer {1290		os.rmdir_all(dir) or {}1291		os.rmdir_all(home) or {}1292	}1293	whole := run_home(dir, home, 'man')1294	assert whole.code == 01295	assert whole.out.contains('NAME')1296	assert whole.out.contains('COMMANDS')1297	assert whole.out.contains('STRICT KOH DISCIPLINE')1298	assert !whole.out.contains('\x1b') && !whole.out.contains('◆')1299	strip := run_home(dir, home, 'man', 'strip')1300	assert strip.code == 01301	assert strip.out.contains('strip')1302	assert !strip.out.contains('koh save ')1303	steal := run_home(dir, home, 'man', 'steal').out1304	assert steal.starts_with('    koh steal') && steal.contains('koh steal my-project')1305	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."1306	assert run_home(dir, home, 'man', 'nonsense').code == 21307	legacy := temp_repo('legacy')1308	defer { os.rmdir_all(legacy) or {} }1309	os.mkdir_all(os.join_path(legacy, '.koh')) or { panic(err) }1310	fake := os.join_path(home, 'bin')1311	os.mkdir_all(fake) or { panic(err) }1312	fake_koh := os.join_path(fake, 'koh2')1313	os.write_file(fake_koh, '#!/bin/sh\nprintf "handoff:%s\\n" "$*"\nexit 7\n') or { panic(err) }1314	os.chmod(fake_koh, 0o755) or { panic(err) }1315	handoff := run_home_with_path(legacy, home, fake, 'status', '--json')1316	assert handoff.code == 71317	assert handoff.out.contains('handoff:status --json')1318	// One notice line, on stderr, so koh2's own output stays as it was.1319	assert handoff.err.contains('Koh 2 repo')1320	assert handoff.err.trim_space().split_into_lines().len == 11321	assert handoff.out.trim_space() == 'handoff:status --json'1322}13231324fn run_home_with_path(repo string, home string, bin_dir string, args ...string) Result {1325	stamp := '${os.getpid()}-${time.now().unix_nano()}'1326	base := os.join_path(os.temp_dir(), 'koh3-cli-${stamp}')1327	out_path := '${base}.out'1328	err_path := '${base}.err'1329	code_path := '${base}.code'1330	mut command := 'HOME=${q(home)} PATH=${q(bin_dir + ':' + os.getenv('PATH'))} ${q(binary)}'1331	for arg in args {1332		command += ' ${q(arg)}'1333	}1334	shell := 'cd ${q(repo)} && ${command} </dev/null >${q(out_path)} 2>${q(err_path)}; printf "%s" \$? >${q(code_path)}'1335	result := os.execute(shell)1336	if result.exit_code != 0 {1337		panic('could not run test command: ${result.output}')1338	}1339	code := os.read_file(code_path) or { panic(err) }1340	out := os.read_file(out_path) or { '' }1341	err := os.read_file(err_path) or { '' }1342	os.rm(out_path) or {}1343	os.rm(err_path) or {}1344	os.rm(code_path) or {}1345	return Result{1346		code: code.int()1347		out:  out1348		err:  err1349	}1350}13511352// --- migration -------------------------------------------------------------13531354// koh2_binary finds Koh 2: `koh2` since the cutover, `koh` before it, and never Koh 3.1355fn koh2_binary() string {1356	for name in ['koh2', 'koh'] {1357		path := os.find_abs_path_of_executable(name) or { continue }1358		if os.execute('${os.quoted_path(path)} --version').output.starts_with('koh v2') {1359			return path1360		}1361	}1362	return ''1363}13641365// run_koh2 runs the Koh 2 binary in a fixture; its own output is not under1366// test here.1367fn run_koh2(dir string, command string) {1368	os.execute('cd ${q(dir)} && ${command} >/dev/null 2>&1')1369}13701371fn save_ids(dir string) []string {1372	mut ids := []string{}1373	for name in os.ls(os.join_path(dir, '.koh', 'snapshots')) or { []string{} } {1374		if name.ends_with('.json') {1375			ids << name.trim_right('.json')1376		}1377	}1378	ids.sort()1379	return ids1380}13811382fn test_migrate_converts_a_koh2_repo_and_keeps_every_save() {1383	koh2 := koh2_binary()1384	if koh2 == '' {1385		println('skipping the migration tests: koh (Koh 2) is not on PATH')1386		return1387	}1388	dir := temp_repo('migrate')1389	defer { os.rmdir_all(dir) or {} }1390	home := temp_repo('migrate-home')1391	defer { os.rmdir_all(home) or {} }1392	run_koh2(dir, '${q(koh2)} init')1393	// One file large enough to be an object, one small enough to be inlined.1394	write(dir, 'code.txt', 'x'.repeat(700))1395	write(dir, 'tiny.txt', 'tiny\n')1396	run_koh2(dir, '${q(koh2)} save "first save"')1397	run_koh2(dir, '${q(koh2)} checkpoint "before something"')1398	write(dir, 'code.txt', 'y'.repeat(700))1399	run_koh2(dir, '${q(koh2)} save "second save"')1400	original := save_ids(dir)1401	assert original.len == 314021403	report := run_home(dir, home, 'migrate')1404	assert report.code == 01405	assert report.out.contains('migrated 3 saves')1406	// The swap: `.koh` is a file, the old data is archived, nothing is left in the draft.1407	assert os.is_file(os.join_path(dir, '.koh'))1408	assert os.is_dir(os.join_path(dir, '.koh-v2'))1409	assert os.is_file(os.join_path(dir, '.kohignore'))1410	assert !os.exists(os.join_path(dir, '.koh-migrate'))14111412	// Every save kept its original ID, and the new repo is sound.1413	listed := run_home(dir, home, 'view', '--json')1414	assert listed.code == 01415	for id in original {1416		assert listed.out.contains(id)1417	}1418	assert run_home(dir, home, 'doctor').code == 01419	assert run_home(dir, home, 'status').code == 014201421	// Migrating again has nothing to convert.1422	assert run_home(dir, home, 'migrate').code == 11423}14241425fn test_migrate_refuses_a_tree_that_does_not_match_the_last_save() {1426	koh2 := koh2_binary()1427	if koh2 == '' {1428		return1429	}1430	dir := temp_repo('migrate-dirty')1431	defer { os.rmdir_all(dir) or {} }1432	home := temp_repo('migrate-dirty-home')1433	defer { os.rmdir_all(home) or {} }1434	run_koh2(dir, '${q(koh2)} init')1435	write(dir, 'code.txt', 'x'.repeat(700))1436	run_koh2(dir, '${q(koh2)} save "only save"')1437	write(dir, 'code.txt', 'unsaved change\n')14381439	refused := run_home(dir, home, 'migrate')1440	assert refused.code == 11441	assert refused.err.contains('save with koh2 first')1442	// Nothing moved: still Koh 2, no archive, no draft file.1443	assert os.is_dir(os.join_path(dir, '.koh'))1444	assert !os.exists(os.join_path(dir, '.koh-v2'))1445	assert !os.exists(os.join_path(dir, '.koh-migrate'))1446}14471448// Koh 2 never saved a root `.kohconfig`, root `.kohignore.<remote>` rules or1449// `*.bundle` files, so a clean Koh 2 repo may hold them. Most real repos have1450// a `.kohconfig`; migrate must not call them unsaved work.1451fn test_migrate_passes_over_the_files_koh2_never_saved() {1452	koh2 := koh2_binary()1453	if koh2 == '' {1454		return1455	}1456	dir := temp_repo('migrate-koh2-ignores')1457	defer { os.rmdir_all(dir) or {} }1458	home := temp_repo('migrate-koh2-ignores-home')1459	defer { os.rmdir_all(home) or {} }1460	run_koh2(dir, '${q(koh2)} init')1461	write(dir, 'code.txt', 'x'.repeat(700))1462	run_koh2(dir, '${q(koh2)} save "only save"')1463	write(dir, '.kohconfig', 'stable_days = 14\n')1464	write(dir, '.kohignore.public', 'private/\n')1465	write(dir, 'lib/app.bundle', 'bundle\n')1466	write(dir, 'ios/Settings.bundle/Root.plist', 'settings\n')1467	// Koh 2 keeps saving a file under a folder pattern added later, where1468	// Koh 3 reads the same rule as covering the folder: the saved file is on1469	// disk and matches, so the tree is clean.1470	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1471	run_koh2(dir, '${q(koh2)} save --agent test --session test "add the dsym"')1472	// Koh 2 skips *.bundle even when its rules no longer list it.1473	ignore_path := os.join_path(dir, '.koh', 'ignore')1474	rules := os.read_file(ignore_path)!.split_into_lines().filter(it != '*.bundle')1475	os.write_file(ignore_path, rules.join('\n') + '\nnative/*.dSYM\n')!1476	// A saved file the walk skips still has to match what was saved.1477	write(dir, 'native/t.dSYM/Info.plist', 'changed\n')1478	changed := run_home(dir, home, 'migrate')1479	assert changed.code == 11480	assert changed.err.contains('native/t.dSYM/Info.plist does not match')1481	write(dir, 'native/t.dSYM/Info.plist', 'plist\n')1482	assert os.execute('cd ${q(dir)} && ${q(koh2)} status --json').output.contains('"dirty":false')14831484	migrated := run_home(dir, home, 'migrate')1485	assert migrated.code == 0, migrated.err1486	// They stay where they were, for the user to keep or delete.1487	assert os.read_file(os.join_path(dir, '.kohconfig'))! == 'stable_days = 14\n'1488}14891490struct FakeKepr {1491	no_access bool1492	// One reply the redemption must cope with: '500', 'garbage' or 'incomplete'.1493	fail string1494	// When set, /api/connect answers 307 here instead of a code reply.1495	redirect_to string1496mut:1497	objects map[string][]u81498	// What the client asked for. A map, because the server holds its own copy of this struct.1499	seen map[string]string1500}15011502fn (mut h FakeKepr) handle(req http.Request) http.Response {1503	if req.method == .post && req.url == '/api/connect' {1504		h.seen['code'] = req.data1505		if h.redirect_to != '' {1506			return http.Response{1507				status_code: 3071508				status_msg:  'Temporary Redirect'1509				header:      http.new_header(1510					key:   .location1511					value: h.redirect_to1512				)1513			}1514		}1515		if h.fail == '500' {1516			return http.Response{ status_code: 500, status_msg: 'Internal Server Error' }1517		}1518		if h.fail == 'garbage' {1519			return http.Response{ status_code: 200, status_msg: 'OK', body: 'not json at all' }1520		}1521		if h.fail == 'incomplete' {1522			return http.Response{ status_code: 200, status_msg: 'OK', body: '{"endpoint":"http://x","bucket":"","region":"","access_key_id":"","secret_access_key":""}' }1523		}1524		if req.data == 'code=good' && !h.no_access {1525			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"}' }1526		}1527		return http.Response{ status_code: 404, status_msg: 'Not Found', body: '{"error":"no_code","message":"no code"}' }1528	}1529	if req.method == .get && req.url.starts_with('/connect') {1530		h.seen['connect'] = req.url1531		return http.Response{ status_code: if h.no_access { 404 } else { 302 }, status_msg: 'Found' }1532	}1533	key := req.url1534	if key.starts_with('/bucket/') {1535		match req.method {1536			.put {1537				if req.header.get_custom('If-None-Match', http.HeaderQueryConfig{}) or { '' } == '*' && key in h.objects {1538					return http.Response{ status_code: 412, status_msg: 'Precondition Failed' }1539				}1540				h.objects[key] = req.data.bytes()1541				return http.Response{ status_code: 200, status_msg: 'OK' }1542			}1543			.get {1544				if body := h.objects[key] {1545					return http.Response{1546						status_code: 2001547						status_msg:  'OK'1548						body:        body.bytestr()1549						header:      http.new_header(1550							key:   .etag1551							value: '"tag"'1552						)1553					}1554				}1555				return http.Response{ status_code: 404, status_msg: 'Not Found' }1556			}1557			.delete {1558				h.objects.delete(key)1559				return http.Response{ status_code: 204, status_msg: 'No Content' }1560			}1561			else {}1562		}1563	}1564	return http.Response{ status_code: 404, status_msg: 'Not Found' }1565}15661567fn start_fake_kepr(no_access bool, fail string, redirect_to string) !(int, &http.Server, &FakeKepr) {1568	for port in 19401 .. 19411 {1569		listener := net.listen_tcp(.ip, '127.0.0.1:${port}') or { continue }1570		fake := &FakeKepr{1571			no_access:   no_access1572			fail:        fail1573			redirect_to: redirect_to1574			seen:        map[string]string{}1575		}1576		mut server := &http.Server{1577			listener:             listener1578			handler:              fake1579			show_startup_message: false1580		}1581		spawn server.listen_and_serve()1582		server.wait_till_running()!1583		return port, server, fake1584	}1585	return error('no free fake Kepr port')1586}15871588// A slash makes an argument an address, so half an address is an error and never a repo name.1589fn test_steal_refuses_an_address_that_is_not_one() {1590	outside := temp_repo('steal-address')1591	home := temp_repo('steal-address-home')1592	defer { os.rmdir_all(outside) or {} }1593	defer { os.rmdir_all(home) or {} }1594	// The repo half becomes a URL path segment and a folder here, so it is a name Kepr serves.1595	for bad in ['kepr.uk/', '/shipped', 'kepr.uk/..', 'kepr.uk/.', 'kepr.uk/a b', 'kepr.uk/nina?x',1596		'kepr.uk/nina#x', 'kepr.uk/nína'] {1597		refused := run_home(outside, home, 'steal', bad)1598		assert refused.code == 1, bad1599		assert refused.err.contains('is not <host>/<repo>'), '${bad}: ${refused.err}'1600	}1601	assert run_home(outside, home, 'steal', 'one', 'two').code == 21602	assert run_home(outside, home, 'steal', '--list', 'extra').code == 21603}16041605fn test_remote_kepr_saves_and_refuses_without_changes() {1606	repo := temp_repo('kepr')1607	home := temp_repo('kepr-home')1608	defer { os.rmdir_all(repo) or {} }1609	defer { os.rmdir_all(home) or {} }1610	init_repo(repo)1611	port, mut server, fake := start_fake_kepr(false, '', '')!1612	defer { server.stop() }1613	host := 'http://127.0.0.1:${port}'1614	// A trailing slash is the same host, and the saved line keeps the normalised form.1615	good := run_home(repo, home, 'remote', '${host}/', '--code', 'good')1616	assert good.code == 0, good.err1617	remote_path := os.join_path(home, '.config', 'koh', 'remote')1618	credentials_path := os.join_path(home, '.config', 'koh', 'credentials')1619	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'1620	assert os.read_file(credentials_path)! == '# written by koh remote — keep this file private\naccess_key=access\nsecret_key=secret\n'1621	// The code went as a form field, and the connect page was never asked for: there was a code.1622	assert (fake.seen['code'] or { '' }) == 'code=good'1623	assert (fake.seen['connect'] or { '' }) == ''1624	// A refused code, a missing terminal and a wrong reply all leave both files as they were.1625	before := os.read_file(remote_path)!1626	before_keys := os.read_file(credentials_path)!1627	bad := run_home(repo, home, 'remote', host, '--code', 'bad')1628	assert bad.code == 11629	assert bad.err.contains('wrong or has expired')1630	// The 404 could also mean a Kepr that hands out nothing, so the connect page is asked for1631	// with this machine's name. (This machine's name holds no character needing an escape, so1632	// that part of the query cannot be exercised here.)1633	// `machine.name()` is `os.hostname() or { 'unknown' }`, so the query carries the same text.1634	assert (fake.seen['connect'] or { '' }).contains('machine=${os.hostname() or { 'unknown' }}')1635	no_terminal := run_home(repo, home, 'remote', host)1636	assert no_terminal.code == 11637	assert no_terminal.err.contains('needs a terminal')1638	assert os.read_file(remote_path)! == before1639	assert os.read_file(credentials_path)! == before_keys1640}16411642fn test_remote_kepr_refuses_hosts_that_are_not_hosts() {1643	repo := temp_repo('kepr-host')1644	home := temp_repo('kepr-host-home')1645	defer { os.rmdir_all(repo) or {} }1646	defer { os.rmdir_all(home) or {} }1647	init_repo(repo)1648	for host in ['kepr.uk/foo', 'https://kepr.uk?x=1', 'kepr.uk#frag', '[email protected]', 'kepr uk',1649		'http://127.0.0.1:1/foo', 'https://'] {1650		refused := run_home(repo, home, 'remote', host, '--code', 'good')1651		assert refused.code == 1, host1652		assert refused.err.contains('is not a Kepr address'), '${host}: ${refused.err}'1653	}1654	// The reply carries the bucket's secret key, so plain http is only for this machine's own Kepr.1655	for host in ['http://kepr.uk', 'http://10.0.0.2:3000', 'http://KEPR.uk:80'] {1656		refused := run_home(repo, home, 'remote', host, '--code', 'good')1657		assert refused.code == 1, host1658		assert refused.err.contains('needs https'), '${host}: ${refused.err}'1659		stolen := run_home(home, home, 'steal', '${host}/nina')1660		assert stolen.code == 1, host1661		assert stolen.err.contains('needs https'), '${host}: ${stolen.err}'1662	}1663	// --code belongs to the host form alone.1664	assert run_home(repo, home, 'remote', 's3', 'https://x', 'b', 'r', '--code', 'good').code == 21665	assert run_home(repo, home, 'remote', 'folder', '/tmp', '--code', 'good').code == 21666	assert run_home(repo, home, 'remote', '--code', 'good').code == 21667	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1668}16691670fn test_remote_kepr_refuses_what_is_not_a_code_reply() {1671	repo := temp_repo('kepr-reply')1672	home := temp_repo('kepr-reply-home')1673	defer { os.rmdir_all(repo) or {} }1674	defer { os.rmdir_all(home) or {} }1675	init_repo(repo)1676	remote_path := os.join_path(home, '.config', 'koh', 'remote')1677	for mode in ['500', 'garbage', 'incomplete'] {1678		port, mut server, _ := start_fake_kepr(false, mode, '')!1679		refused := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1680		server.stop()1681		assert refused.code == 1, mode1682		assert refused.err.contains('nothing was changed'), '${mode}: ${refused.err}'1683		assert !os.exists(remote_path)1684	}1685	// A redirect would hand the code to wherever it points, so it is refused and never followed.1686	target_port, mut target, target_fake := start_fake_kepr(false, '', '')!1687	port, mut server, _ := start_fake_kepr(false, '', 'http://127.0.0.1:${target_port}/api/connect')!1688	redirected := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'good')1689	server.stop()1690	target.stop()1691	assert redirected.code == 11692	assert redirected.err.contains('refused the code')1693	assert target_fake.seen.len == 0, 'the code was forwarded: ${target_fake.seen}'1694	assert !os.exists(remote_path)1695}16961697// An unreachable Kepr is a refusal too, and the settings are still untouched.1698fn test_remote_kepr_that_cannot_be_reached_changes_nothing() {1699	repo := temp_repo('kepr-down')1700	home := temp_repo('kepr-down-home')1701	defer { os.rmdir_all(repo) or {} }1702	defer { os.rmdir_all(home) or {} }1703	init_repo(repo)1704	refused := run_home(repo, home, 'remote', 'http://127.0.0.1:1', '--code', 'good')1705	assert refused.code == 11706	assert refused.err.contains('could not reach Kepr')1707	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1708}17091710fn test_remote_kepr_without_bucket_access_is_explained() {1711	repo := temp_repo('kepr-no-access')1712	home := temp_repo('kepr-no-access-home')1713	defer { os.rmdir_all(repo) or {} }1714	defer { os.rmdir_all(home) or {} }1715	init_repo(repo)1716	port, mut server, _ := start_fake_kepr(true, '', '')!1717	defer { server.stop() }1718	r := run_home(repo, home, 'remote', 'http://127.0.0.1:${port}', '--code', 'bad')1719	assert r.code == 11720	assert r.err.contains("doesn't hand out bucket access")1721	assert !os.exists(os.join_path(home, '.config', 'koh', 'remote'))1722}