kaeru 0.1.7

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! `kaeru install`, `kaeru uninstall` and `kaeru doctor`: the line in the
//! shell profiles and the agents' hooks. These files aren't kaeru's, so
//! kaeru asks before it changes each one, and `kaeru uninstall` takes out
//! exactly what `kaeru install` put in.

mod doctor;
mod hooks;
mod profile;

pub use doctor::doctor;

use std::ffi::OsString;
use std::fs;
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use ratatui::crossterm::style::{Color, Print, ResetColor, SetForegroundColor};
use ratatui::crossterm::{queue, terminal};
use serde_json::{Value, json};
use unicode_width::UnicodeWidthStr;

use crate::agents::{claude, codex};
use crate::store::Store;
use profile::Profile;

/// The command that Claude Code's hook runs.
const CLAUDE_HOOK: &str = "kaeru hook claude";

/// The command that Codex's hook runs.
const CODEX_HOOK: &str = "kaeru hook codex";

/// The name of Codex's hook, which Codex shows when it asks you to trust the
/// hook.
const CODEX_HOOK_NAME: &str = "kaeru: remember this session's tab";

/// An agent's hook file.
struct HookFile {
    /// The agent, as kaeru names it to you.
    agent: &'static str,
    /// The file.
    path: PathBuf,
    /// The command that kaeru's hook runs.
    command: &'static str,
    /// The name of kaeru's hook, for an agent that shows hooks by name.
    name: Option<&'static str>,
}

impl HookFile {
    /// Returns whether the agent is set up on this computer: its folder
    /// exists. An agent that never ran here has nothing to hook into.
    fn agent_is_set_up(&self) -> bool {
        self.path.parent().is_some_and(Path::is_dir)
    }
}

/// Returns the agents' hook files: Claude Code's `settings.json`, and Codex's
/// `hooks.json`.
fn hook_files() -> Vec<HookFile> {
    let mut files = Vec::new();
    if let Some(dir) = claude::config_dir() {
        files.push(HookFile {
            agent: "Claude Code",
            path: dir.join("settings.json"),
            command: CLAUDE_HOOK,
            name: None,
        });
    }
    if let Some(home) = codex::home_dir() {
        files.push(HookFile {
            agent: "Codex",
            path: home.join("hooks.json"),
            command: CODEX_HOOK,
            name: Some(CODEX_HOOK_NAME),
        });
    }
    files
}

/// What happened to one part of the setup, which `kaeru install` prints as a
/// colored label, as `kaeru doctor` does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Outcome {
    /// It was set up already.
    Ok,
    /// kaeru set it up now.
    Added,
    /// You answered no.
    Skipped,
    /// Something is worth knowing.
    Note,
    /// Something needs fixing.
    Problem,
}

impl Outcome {
    /// Returns the label, as printed before the part's name.
    fn label(self) -> &'static str {
        match self {
            Outcome::Ok => "ok",
            Outcome::Added => "added",
            Outcome::Skipped => "skipped",
            Outcome::Note => "note",
            Outcome::Problem => "problem",
        }
    }

    /// Returns the label's color.
    fn color(self) -> Color {
        match self {
            Outcome::Ok | Outcome::Added => Color::Green,
            Outcome::Skipped | Outcome::Note => Color::Yellow,
            Outcome::Problem => Color::Red,
        }
    }
}

/// What `kaeru install` set up, or what `kaeru doctor` found, printed one
/// line per part: a label, the part's name in a column, and what that means.
struct Checklist {
    /// Whether the labels are printed in color.
    color: bool,
    /// How wide the column of names is.
    width: usize,
    /// How wide the terminal is, which long lines wrap at, or `None` when
    /// the output isn't a terminal.
    columns: Option<usize>,
    /// How many lines said that something needs fixing.
    problems: usize,
    /// How many parts there are, how many are set up, and how many kaeru set
    /// up now.
    parts: usize,
    set_up: usize,
    added: usize,
}

impl Checklist {
    /// Returns an empty checklist whose column of names fits `names`. It
    /// prints in color when the output is a terminal and `NO_COLOR` doesn't
    /// turn colors off.
    fn new(names: &[&str]) -> Self {
        let terminal = io::stdout().is_terminal();
        Self {
            color: crate::tui::colors_wanted() && terminal,
            width: name_column(names),
            columns: terminal
                .then(|| terminal::size().ok())
                .flatten()
                .map(|(columns, _)| usize::from(columns)),
            problems: 0,
            parts: 0,
            set_up: 0,
            added: 0,
        }
    }

    /// Prints the line of a part, and counts it.
    fn part(&mut self, outcome: Outcome, name: &str, text: &str) {
        self.parts += 1;
        if matches!(outcome, Outcome::Ok | Outcome::Added) {
            self.set_up += 1;
        }
        if outcome == Outcome::Added {
            self.added += 1;
        }
        self.line(outcome, name, text);
    }

    /// Prints a line that isn't counted as a part, such as a note. A text
    /// too long for the terminal wraps, and its further lines, and those
    /// after a line break in it, go on under its start.
    fn line(&mut self, outcome: Outcome, name: &str, text: &str) {
        if outcome == Outcome::Problem {
            self.problems += 1;
        }
        let label = format!("{:<9}", outcome.label());
        let indent = LABEL_WIDTH + self.width;
        let room = self
            .columns
            .map_or(usize::MAX, |columns| columns.saturating_sub(indent + 1));
        let lines: Vec<String> = text.split('\n').flat_map(|part| wrap(part, room)).collect();
        let text = lines.join(&format!("\n{}", " ".repeat(indent)));
        let rest = format!("{name:<width$}{text}\n", width = self.width);
        let mut out = io::stdout().lock();
        // A line that can't be printed is lost, as with println.
        let _ = if self.color {
            queue!(
                out,
                SetForegroundColor(outcome.color()),
                Print(label),
                ResetColor,
                Print(rest)
            )
        } else {
            queue!(out, Print(label), Print(rest))
        };
        let _ = out.flush();
    }
}

/// How wide the column of labels is.
const LABEL_WIDTH: usize = 9;

/// Returns the lines of a text wrapped at spaces to `width` columns. A word
/// longer than that, such as a path, gets a line of its own. A width too
/// small to read leaves the text whole.
fn wrap(text: &str, width: usize) -> Vec<String> {
    if width < 20 {
        return vec![text.to_string()];
    }
    let mut lines = Vec::new();
    let mut line = String::new();
    for word in text.split(' ') {
        if !line.is_empty() && line.width() + 1 + word.width() > width {
            lines.push(std::mem::take(&mut line));
        }
        if !line.is_empty() {
            line.push(' ');
        }
        line.push_str(word);
    }
    lines.push(line);
    lines
}

/// Returns how wide the column of names is: the longest name and two spaces.
fn name_column(names: &[&str]) -> usize {
    names
        .iter()
        .map(|name| name.chars().count())
        .max()
        .unwrap_or(0)
        + 2
}

/// Returns the line that ends `kaeru install`, after `parts` parts, of which
/// `set_up` are set up, `added` of them now.
fn summary(parts: usize, set_up: usize, added: usize) -> String {
    let check = "Open a new tab and run kaeru doctor to check it.";
    if set_up < parts {
        format!("Set up {set_up} of {parts}. To add the rest, run kaeru install again. {check}")
    } else if added == 0 {
        format!("Everything was set up already. {check}")
    } else {
        format!("Everything is set up. {check}")
    }
}

/// Returns what a profile that loads kaeru means, for its line.
fn loads_kaeru(kind: profile::Kind) -> &'static str {
    match kind {
        profile::Kind::PowerShell => "the profile loads kaeru",
        profile::Kind::Bash => "~/.bashrc loads kaeru",
        profile::Kind::Zsh => "~/.zshrc loads kaeru",
        profile::Kind::Fish => "config.fish loads kaeru",
    }
}

/// Prints the question about one part: its name, what kaeru would change,
/// and in which file, with the home folder written as `~`.
fn explain(name: &str, change: &str, path: &Path) {
    println!(
        "\n{name}: {change}\n  {}",
        crate::tui::home_as_tilde(&path.display().to_string())
    );
}

/// Sets kaeru up, for `kaeru install`: the line in each PowerShell profile
/// and in Git Bash's `~/.bashrc`, and a hook for each agent. It starts with
/// kaeru's frog, asks before each change, and prints a line for each part.
///
/// # Errors
///
/// Fails when it doesn't run in a terminal, so that it can't ask, or when a
/// file can't be read or written.
pub fn install() -> Result<()> {
    require_terminal("kaeru install")?;
    crate::tui::greet()?;
    let profiles = profile::profiles();
    let files = hook_files();
    let names: Vec<&str> = profiles
        .iter()
        .map(|profile| profile.shell)
        .chain(files.iter().map(|file| file.agent))
        .collect();
    let mut list = Checklist::new(&names);
    if profiles.is_empty() {
        list.line(
            Outcome::Note,
            "Shells",
            "none that kaeru sets up: PowerShell, bash, zsh or fish",
        );
    }
    for profile in &profiles {
        install_profile(&mut list, profile)?;
    }
    for file in &files {
        if !file.agent_is_set_up() {
            list.line(Outcome::Note, file.agent, "isn't set up on this computer");
            continue;
        }
        if file.command == CODEX_HOOK
            && let Some(config) = codex_config_with_hooks()
        {
            explain_codex_config(&mut list, &config);
            continue;
        }
        if install_hook(&mut list, file)? && file.command == CODEX_HOOK {
            list.line(
                Outcome::Note,
                file.agent,
                &format!("trust the hook {CODEX_HOOK_NAME:?} when Codex asks about it"),
            );
        }
    }
    if files
        .iter()
        .any(|file| file.command == CODEX_HOOK && file.agent_is_set_up())
    {
        install_codex_no_daemon(&mut list)?;
    }
    println!("\n{}", summary(list.parts, list.set_up, list.added));
    Ok(())
}

/// Asks whether the tabs that kaeru tracks should start Codex with
/// `--no-daemon`, and keeps the answer in kaeru's options. It is a choice,
/// not a part that has to be set up, so it isn't counted.
fn install_codex_no_daemon(list: &mut Checklist) -> Result<()> {
    let store = Store::open()?;
    let mut config = store.config();
    let started = "tracked tabs start it with --no-daemon";
    if config.codex_no_daemon {
        list.line(Outcome::Ok, "Codex", started);
        return Ok(());
    }
    println!(
        "\nCodex: started with --no-daemon, a session runs in its tab, so kaeru knows exactly \
         where it is.\n  Codex's remote control doesn't work in those sessions."
    );
    if ask("  Start Codex with --no-daemon in the tabs that kaeru tracks?")? {
        config.codex_no_daemon = true;
        store.save_config(&config)?;
        list.line(Outcome::Added, "Codex", started);
    } else {
        list.line(
            Outcome::Skipped,
            "Codex",
            "kaeru works out a session's tab from when and where it started",
        );
    }
    Ok(())
}

/// Removes what `kaeru install` added, for `kaeru uninstall`. It asks before
/// each change, and also offers to delete kaeru's notes and options.
///
/// # Errors
///
/// Fails when it doesn't run in a terminal, so that it can't ask, or when a
/// file can't be read or written.
pub fn uninstall() -> Result<()> {
    require_terminal("kaeru uninstall")?;
    for profile in profile::profiles() {
        let bytes = read_or_empty(&profile.path)?;
        if profile::has_line(&bytes, profile.kind)?
            && ask(&format!(
                "Remove kaeru's lines from the {} profile, {}?",
                profile.shell,
                profile.path.display()
            ))?
        {
            write_file(&profile.path, &profile::remove_line(&bytes, profile.kind)?)?;
            println!("Removed.");
        }
    }
    for file in hook_files() {
        let mut root = read_json(&file.path)?;
        if hooks::has_hook(&root, file.command)
            && ask(&format!(
                "Remove kaeru's hook from {}'s {}?",
                file.agent,
                file.path.display()
            ))?
        {
            hooks::remove_hook(&mut root, file.command);
            write_json(&file.path, &root)?;
            let _ = fs::remove_file(backup_of(&file.path));
            println!("Removed.");
        }
    }
    if let Some(config) = codex_config_with_hooks()
        && fs::read_to_string(&config).is_ok_and(|text| text.contains(CODEX_HOOK))
    {
        println!(
            "{} runs kaeru's hook. Take out its [[hooks.SessionStart]] entry with {CODEX_HOOK:?} \
             yourself.",
            config.display()
        );
    }
    let store = Store::open()?;
    if ask_default_no(&format!(
        "Also delete kaeru's notes, log and options, in {}?",
        store.dir().display()
    ))? {
        store.delete_all()?;
        println!("Deleted.");
    }
    Ok(())
}

/// Adds kaeru's lines to a shell profile, after asking, and prints its line.
fn install_profile(list: &mut Checklist, profile: &Profile) -> Result<()> {
    let bytes = read_or_empty(&profile.path)?;
    let loads = loads_kaeru(profile.kind);
    if profile::has_line(&bytes, profile.kind)? {
        list.part(Outcome::Ok, profile.shell, loads);
    } else {
        explain(
            profile.shell,
            "kaeru adds 2 lines to the end of",
            &profile.path,
        );
        if ask("  Add them?")? {
            write_file(&profile.path, &profile::add_line(&bytes, profile.kind)?)?;
            list.part(Outcome::Added, profile.shell, loads);
        } else {
            list.part(
                Outcome::Skipped,
                profile.shell,
                "kaeru won't know about its tabs",
            );
        }
    }
    if let Some(problem) = bash_profile_problem(profile) {
        list.line(Outcome::Problem, profile.shell, &problem);
    }
    Ok(())
}

/// Returns what is wrong when bash wouldn't run kaeru's line in
/// `~/.bashrc`: its `~/.bash_profile`, which login shells read instead,
/// doesn't read `~/.bashrc`. Git Bash and some terminals start login shells.
/// When there is no `~/.bash_profile`, Git Bash writes one that does.
fn bash_profile_problem(profile: &Profile) -> Option<String> {
    if profile.kind != profile::Kind::Bash {
        return None;
    }
    let bash_profile = profile.path.parent()?.join(".bash_profile");
    let text = fs::read_to_string(&bash_profile).ok()?;
    (!profile::reads_bashrc(&text)).then(|| {
        format!(
            "{} doesn't read ~/.bashrc, and login shells, such as Git Bash's, read only that file, so add this line to \
             it:\n    test -f ~/.bashrc && . ~/.bashrc",
            bash_profile.display()
        )
    })
}

/// Adds kaeru's hook to an agent's hook file, after asking, prints its line,
/// and returns whether it added the hook. It keeps a copy of the file as it
/// was, next to it.
fn install_hook(list: &mut Checklist, file: &HookFile) -> Result<bool> {
    let mut root = read_json(&file.path)?;
    let runs = "runs kaeru's hook";
    if hooks::has_hook(&root, file.command) {
        list.part(Outcome::Ok, file.agent, runs);
        return Ok(false);
    }
    explain(
        file.agent,
        &format!(
            "kaeru adds a SessionStart hook that runs {:?} to",
            file.command
        ),
        &file.path,
    );
    if !ask("  Add it?")? {
        list.part(
            Outcome::Skipped,
            file.agent,
            "no hook, so its sessions won't come back",
        );
        return Ok(false);
    }
    hooks::add_hook(&mut root, file.command, file.name)
        .with_context(|| format!("can't add the hook to {}", file.path.display()))?;
    if file.path.exists() {
        fs::copy(&file.path, backup_of(&file.path))?;
        println!(
            "  The file as it was is kept as {}.",
            crate::tui::home_as_tilde(&backup_of(&file.path).display().to_string())
        );
    }
    write_json(&file.path, &root)?;
    list.part(Outcome::Added, file.agent, runs);
    Ok(true)
}

/// Returns Codex's `config.toml` when it declares hooks itself. Codex warns
/// when one folder has hooks in both `config.toml` and `hooks.json`, so then
/// kaeru leaves the hook for you to add there.
fn codex_config_with_hooks() -> Option<PathBuf> {
    let config = codex::home_dir()?.join("config.toml");
    let text = fs::read_to_string(&config).ok()?;
    declares_hooks(&text).then_some(config)
}

/// Returns whether the text of a Codex `config.toml` declares hooks: whether
/// its `hooks` table lists hooks for an event, as `[[hooks.SessionStart]]`
/// does. Codex also keeps which hooks you trust in that table, under
/// `[hooks.state]`, which declares none. A file that isn't valid TOML declares
/// none either, since Codex can't read it.
fn declares_hooks(config: &str) -> bool {
    let Ok(config) = config.parse::<toml::Table>() else {
        return false;
    };
    config
        .get("hooks")
        .and_then(toml::Value::as_table)
        .is_some_and(|hooks| {
            hooks.iter().any(|(key, value)| {
                key != "state" && value.as_array().is_some_and(|groups| !groups.is_empty())
            })
        })
}

/// Tells you how to add kaeru's hook to a Codex `config.toml` that declares
/// hooks itself, and prints its line.
fn explain_codex_config(list: &mut Checklist, config: &Path) {
    if fs::read_to_string(config).is_ok_and(|text| text.contains(CODEX_HOOK)) {
        list.part(Outcome::Ok, "Codex", "runs kaeru's hook, from config.toml");
        return;
    }
    println!(
        "\nCodex: declares hooks in {} already, and warns when hooks.json has hooks too. \
         Add this to it yourself, and trust the hook when Codex asks about it:\n\n\
         [[hooks.SessionStart]]\n\n[[hooks.SessionStart.hooks]]\ntype = \"command\"\n\
         command = {CODEX_HOOK:?}\nstatusMessage = {CODEX_HOOK_NAME:?}\n",
        crate::tui::home_as_tilde(&config.display().to_string())
    );
    list.part(
        Outcome::Skipped,
        "Codex",
        "add the hook to config.toml yourself, as shown above",
    );
}

/// Fails unless standard input is a terminal, since `command` asks questions.
fn require_terminal(command: &str) -> Result<()> {
    if !io::stdin().is_terminal() {
        bail!("{command} asks before each change, so run it in a terminal.");
    }
    Ok(())
}

/// Asks a yes or no question, where yes is the default.
fn ask(question: &str) -> Result<bool> {
    Ok(answer(question, "[Y/n]")?.is_none_or(|yes| yes))
}

/// Asks a yes or no question, where no is the default.
fn ask_default_no(question: &str) -> Result<bool> {
    Ok(answer(question, "[y/N]")?.is_some_and(|yes| yes))
}

/// Asks a question until the answer is yes, no or empty, and returns it:
/// `None` for an empty answer, which means the default.
fn answer(question: &str, choices: &str) -> Result<Option<bool>> {
    loop {
        print!("{question} {choices} ");
        io::stdout().flush()?;
        let mut line = String::new();
        if io::stdin().lock().read_line(&mut line)? == 0 {
            return Ok(Some(false));
        }
        match line.trim().to_ascii_lowercase().as_str() {
            "" => return Ok(None),
            "y" | "yes" => return Ok(Some(true)),
            "n" | "no" => return Ok(Some(false)),
            _ => {}
        }
    }
}

/// Returns a file's bytes, or nothing when the file doesn't exist yet.
fn read_or_empty(path: &Path) -> Result<Vec<u8>> {
    match fs::read(path) {
        Ok(bytes) => Ok(bytes),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
        Err(error) => Err(error).with_context(|| format!("can't read {}", path.display())),
    }
}

/// Returns a JSON file's contents, or an empty object when the file doesn't
/// exist yet.
fn read_json(path: &Path) -> Result<Value> {
    let bytes = read_or_empty(path)?;
    if bytes.iter().all(u8::is_ascii_whitespace) {
        return Ok(json!({}));
    }
    serde_json::from_slice(&bytes).with_context(|| {
        format!(
            "can't read {} as JSON, so kaeru leaves it alone",
            path.display()
        )
    })
}

/// Writes a JSON file, indented as these files usually are.
fn write_json(path: &Path, value: &Value) -> Result<()> {
    let mut text = serde_json::to_string_pretty(value)?;
    text.push('\n');
    write_file(path, text.as_bytes())
}

/// Writes a file, creating its folder when needed. The bytes go to a
/// temporary file that is then renamed, to avoid a half-written file. When
/// the path is a symbolic link, as in many dotfiles setups, the file it
/// points to is written, so that the link stays a link.
fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {
    let linked;
    let path = if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink())
    {
        linked = fs::canonicalize(path)
            .with_context(|| format!("can't follow the link {}", path.display()))?;
        linked.as_path()
    } else {
        path
    };
    if let Some(folder) = path.parent() {
        fs::create_dir_all(folder).with_context(|| format!("can't create {}", folder.display()))?;
    }
    let mut temp = path.as_os_str().to_owned();
    temp.push(".kaeru-tmp");
    let temp = PathBuf::from(temp);
    fs::write(&temp, bytes).with_context(|| format!("can't write {}", temp.display()))?;
    fs::rename(&temp, path).with_context(|| format!("can't write {}", path.display()))
}

/// Returns the path of the copy that `kaeru install` keeps of a file it
/// changes.
fn backup_of(path: &Path) -> PathBuf {
    let mut name: OsString = path.as_os_str().to_owned();
    name.push(".kaeru-backup");
    PathBuf::from(name)
}

/// Returns where a program is on the PATH, if it is.
fn on_path(program: &str) -> Option<PathBuf> {
    std::env::split_paths(&std::env::var_os("PATH")?)
        .map(|folder| folder.join(program))
        .find(|candidate| candidate.is_file())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_summary_says_how_much_is_set_up() {
        assert!(summary(4, 4, 0).starts_with("Everything was set up already."));
        assert!(summary(4, 4, 2).starts_with("Everything is set up."));
        assert!(summary(4, 3, 1).starts_with("Set up 3 of 4."));
        assert!(summary(4, 3, 1).ends_with("run kaeru doctor to check it."));
    }

    #[test]
    fn long_lines_wrap_at_spaces() {
        assert_eq!(
            wrap("one two three four five six seven eight", 20),
            ["one two three four", "five six seven eight"]
        );
        assert_eq!(wrap("short", 40), ["short"]);
        assert_eq!(wrap("a b", 5), ["a b"], "too narrow to wrap");
    }

    #[test]
    fn names_line_up_in_a_column() {
        assert_eq!(
            name_column(&["Git Bash", "Windows PowerShell", "Codex"]),
            20
        );
        assert_eq!(name_column(&[]), 2);
    }

    #[test]
    fn labels_have_the_doctor_s_colors() {
        assert_eq!(Outcome::Ok.color(), Color::Green);
        assert_eq!(Outcome::Added.color(), Color::Green);
        assert_eq!(Outcome::Skipped.color(), Color::Yellow);
        assert_eq!(Outcome::Problem.color(), Color::Red);
        assert!(Outcome::Skipped.label().len() < 9);
    }

    #[test]
    fn codex_s_trust_records_declare_no_hooks() {
        let trust = r#"
[hooks.state]

[hooks.state.'C:\Users\demo\.codex\hooks.json:session_start:0:0']
trusted_hash = "sha256:0000"
enabled = true
"#;
        let inline = r#"
[[hooks.SessionStart]]

[[hooks.SessionStart.hooks]]
type = "command"
command = "kaeru hook codex"
"#;
        assert!(!declares_hooks(trust));
        assert!(declares_hooks(inline));
        assert!(declares_hooks(&format!("{trust}{inline}")));
        assert!(!declares_hooks("model = \"some-model\"\n"));
        assert!(!declares_hooks("[hooks\n"));
    }

    #[test]
    fn a_file_that_doesn_t_exist_reads_as_empty() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("missing.json");
        assert!(read_or_empty(&missing).unwrap().is_empty());
        assert_eq!(read_json(&missing).unwrap(), json!({}));
    }

    #[test]
    fn json_is_written_and_read_back() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("new folder").join("settings.json");
        write_json(&path, &json!({ "a": 1 })).unwrap();
        assert_eq!(read_json(&path).unwrap(), json!({ "a": 1 }));
        assert!(fs::read_to_string(&path).unwrap().ends_with("}\n"));
    }

    #[test]
    fn broken_json_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, "{ not json").unwrap();
        assert!(read_json(&path).is_err());
        assert_eq!(fs::read_to_string(&path).unwrap(), "{ not json");
    }

    #[test]
    fn writing_through_a_link_keeps_the_link() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("dotfiles-profile.ps1");
        let link = dir.path().join("profile.ps1");
        fs::write(&target, "old").unwrap();
        #[cfg(unix)]
        let made = std::os::unix::fs::symlink(&target, &link);
        #[cfg(windows)]
        let made = std::os::windows::fs::symlink_file(&target, &link);
        if made.is_err() {
            // Windows lets only some users make links, such as in developer
            // mode, so the check can't run everywhere.
            return;
        }
        write_file(&link, b"new").unwrap();
        assert!(
            fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(fs::read_to_string(&target).unwrap(), "new");
    }

    #[test]
    fn the_backup_sits_next_to_the_file() {
        assert_eq!(
            backup_of(Path::new("settings.json")),
            Path::new("settings.json.kaeru-backup")
        );
    }
}