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
//! Shell profiles: PowerShell's profiles, bash's `~/.bashrc`, zsh's
//! `~/.zshrc` and fish's `config.fish`, where they are, and adding the line
//! that loads kaeru's snippet, or taking it out again, without touching
//! anything else.
//!
//! The lines are changed byte by byte, so that a profile keeps its encoding,
//! whatever code page it was saved in. Only a UTF-16 profile is decoded.

use std::path::PathBuf;

use anyhow::{Result, bail};

/// The line that loads kaeru's snippet in PowerShell.
pub const LINE: &str = "Invoke-Expression (& kaeru init powershell | Out-String)";

/// The line that loads kaeru's snippet in bash.
pub const BASH_LINE: &str = "eval \"$(kaeru init bash)\"";

/// The line that loads kaeru's snippet in zsh.
pub const ZSH_LINE: &str = "eval \"$(kaeru init zsh)\"";

/// The line that loads kaeru's snippet in fish.
pub const FISH_LINE: &str = "kaeru init fish | source";

/// The comment that `kaeru install` puts above the line, in either shell.
pub const COMMENT: &str =
    "# kaeru brings your tabs back after the terminal closes. `kaeru uninstall` removes this.";

/// The byte order mark of UTF-16, low byte first.
const UTF16_BOM: [u8; 2] = [0xFF, 0xFE];

/// The byte order mark of a UTF-16 big-endian file, which kaeru doesn't
/// edit: PowerShell doesn't write profiles that way, and adding a line to it
/// safely would need converting the whole file.
const UTF16_BE_BOM: [u8; 2] = [0xFE, 0xFF];

/// The byte order mark that a UTF-8 file can start with.
const UTF8_BOM: [u8; 3] = [0xEF, 0xBB, 0xBF];

/// Fails for a profile in an encoding that kaeru doesn't edit.
fn check_encoding(profile: &[u8]) -> Result<()> {
    if profile.starts_with(&UTF16_BE_BOM) {
        bail!(
            "the profile is UTF-16 big-endian, which kaeru doesn't edit; add kaeru's line to it yourself"
        );
    }
    Ok(())
}

/// The shell that a profile belongs to, which decides kaeru's line in it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// A PowerShell profile, with Windows line endings.
    PowerShell,
    /// A bash rc file, with Unix line endings, which bash needs.
    Bash,
    /// A zsh rc file, with Unix line endings.
    Zsh,
    /// fish's `config.fish`, with Unix line endings.
    Fish,
}

impl Kind {
    /// Returns the line that loads kaeru's snippet.
    pub fn line(self) -> &'static str {
        match self {
            Kind::PowerShell => LINE,
            Kind::Bash => BASH_LINE,
            Kind::Zsh => ZSH_LINE,
            Kind::Fish => FISH_LINE,
        }
    }

    /// Returns the line ending that kaeru writes.
    fn newline(self) -> &'static str {
        match self {
            Kind::PowerShell => "\r\n",
            Kind::Bash | Kind::Zsh | Kind::Fish => "\n",
        }
    }
}

/// A shell profile that `kaeru install` sets up.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Profile {
    /// The shell it belongs to, as `kaeru install` names it.
    pub shell: &'static str,
    /// The profile's path.
    pub path: PathBuf,
    /// Which shell's line goes in it.
    pub kind: Kind,
}

/// Returns the profiles that `kaeru install` sets up. On Windows, they are
/// the current user's console profile of Windows PowerShell, and of
/// PowerShell 7 when that is installed, and `~/.bashrc` when Git Bash is
/// installed. The PowerShell profiles are in the Documents folder, wherever
/// Windows keeps it, which is where PowerShell's `$PROFILE` points. On other
/// systems, they are `~/.zshrc` when zsh is installed, as it is on macOS,
/// fish's `config.fish` when fish is installed, and on Linux, `~/.bashrc`.
pub fn profiles() -> Vec<Profile> {
    if !cfg!(windows) {
        let mut found = Vec::new();
        if cfg!(target_os = "linux")
            && super::on_path("bash").is_some()
            && let Some(home) = dirs::home_dir()
        {
            found.push(Profile {
                shell: "bash",
                path: home.join(".bashrc"),
                kind: Kind::Bash,
            });
        }
        if let Some(path) = super::on_path("zsh").and(zsh_rc()) {
            found.push(Profile {
                shell: "zsh",
                path,
                kind: Kind::Zsh,
            });
        }
        if let Some(path) = super::on_path("fish").and(fish_config()) {
            found.push(Profile {
                shell: "fish",
                path,
                kind: Kind::Fish,
            });
        }
        return found;
    }
    let mut found = Vec::new();
    if let Some(documents) = dirs::document_dir() {
        found.push(Profile {
            shell: "Windows PowerShell",
            path: documents
                .join("WindowsPowerShell")
                .join("Microsoft.PowerShell_profile.ps1"),
            kind: Kind::PowerShell,
        });
        if super::on_path("pwsh.exe").is_some() {
            found.push(Profile {
                shell: "PowerShell 7",
                path: documents
                    .join("PowerShell")
                    .join("Microsoft.PowerShell_profile.ps1"),
                kind: Kind::PowerShell,
            });
        }
    }
    if git_bash_is_installed()
        && let Some(home) = bash_home()
    {
        found.push(Profile {
            shell: "Git Bash",
            path: home.join(".bashrc"),
            kind: Kind::Bash,
        });
    }
    found
}

/// Returns the `.zshrc` that zsh reads: in `ZDOTDIR` when it is set, and in
/// the home folder otherwise.
fn zsh_rc() -> Option<PathBuf> {
    std::env::var_os("ZDOTDIR")
        .map(PathBuf::from)
        .filter(|folder| folder.is_absolute())
        .or_else(dirs::home_dir)
        .map(|folder| folder.join(".zshrc"))
}

/// Returns the `config.fish` that fish reads: in `XDG_CONFIG_HOME` when it
/// is set, and in `~/.config` otherwise.
fn fish_config() -> Option<PathBuf> {
    std::env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .filter(|folder| folder.is_absolute())
        .or_else(|| dirs::home_dir().map(|home| home.join(".config")))
        .map(|folder| folder.join("fish").join("config.fish"))
}

/// Returns the home folder that Git Bash uses: `HOME` when it is set to a
/// Windows path, and the user's folder otherwise.
pub fn bash_home() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .filter(|home| home.is_absolute())
        .or_else(dirs::home_dir)
}

/// Returns whether Git for Windows, with Git Bash, is installed: next to the
/// `git.exe` on the PATH, or in its default folder.
fn git_bash_is_installed() -> bool {
    let near_git = super::on_path("git.exe").is_some_and(|git| {
        git.ancestors()
            .skip(1)
            .take(3)
            .any(|folder| folder.join("git-bash.exe").is_file())
    });
    let default = std::env::var_os("ProgramFiles")
        .map(PathBuf::from)
        .is_some_and(|programs| programs.join("Git").join("git-bash.exe").is_file());
    near_git || default
}

/// Returns whether a `~/.bash_profile` reads `~/.bashrc`. Git Bash starts
/// bash as a login shell, which reads `~/.bash_profile` and not `~/.bashrc`,
/// so kaeru's line in `~/.bashrc` runs only when the first reads the second.
/// Git Bash writes such a `~/.bash_profile` when there is none.
pub fn reads_bashrc(bash_profile: &str) -> bool {
    bash_profile.lines().any(|line| {
        let line = line.trim();
        !line.starts_with('#') && line.contains(".bashrc")
    })
}

/// Returns whether a profile loads kaeru.
///
/// # Errors
///
/// Fails for a UTF-16 profile that isn't valid UTF-16.
pub fn has_line(profile: &[u8], kind: Kind) -> Result<bool> {
    Ok(lines(profile)?
        .iter()
        .any(|line| line.trim() == kind.line()))
}

/// Returns the profile with kaeru's comment and line added at its end.
///
/// # Errors
///
/// Fails for a UTF-16 profile that isn't valid UTF-16.
pub fn add_line(profile: &[u8], kind: Kind) -> Result<Vec<u8>> {
    check_encoding(profile)?;
    let newline = kind.newline();
    let added = format!("{COMMENT}{newline}{}{newline}", kind.line());
    if profile.starts_with(&UTF16_BOM) {
        let mut text = utf16(profile)?;
        if !text.is_empty() && !text.ends_with('\n') {
            text.push_str(newline);
        }
        text.push_str(&added);
        return Ok(to_utf16(&text));
    }
    let mut bytes = profile.to_vec();
    if !bytes.is_empty() && !bytes.ends_with(b"\n") {
        bytes.extend_from_slice(newline.as_bytes());
    }
    bytes.extend_from_slice(added.as_bytes());
    Ok(bytes)
}

/// Returns the profile without kaeru's comment and line.
///
/// # Errors
///
/// Fails for a UTF-16 profile that isn't valid UTF-16.
pub fn remove_line(profile: &[u8], kind: Kind) -> Result<Vec<u8>> {
    check_encoding(profile)?;
    let ours = |line: &str| {
        let line = line.trim();
        line == kind.line() || line == COMMENT
    };
    if profile.starts_with(&UTF16_BOM) {
        let text = utf16(profile)?;
        let kept: String = text
            .split_inclusive('\n')
            .filter(|line| !ours(line))
            .collect();
        return Ok(to_utf16(&kept));
    }
    // A UTF-8 byte order mark stays at the start, but doesn't hide kaeru's
    // comment when that is the first line.
    let (mark, rest) = match profile.strip_prefix(&UTF8_BOM) {
        Some(rest) => (&UTF8_BOM[..], rest),
        None => (&[][..], profile),
    };
    // ASCII lines can be found in the bytes of any code page except UTF-16.
    let kept = rest
        .split_inclusive(|&byte| byte == b'\n')
        .filter(|line| !std::str::from_utf8(line).is_ok_and(ours))
        .flatten()
        .copied();
    Ok(mark.iter().copied().chain(kept).collect())
}

/// Returns a profile's lines, as far as kaeru needs them: lines that aren't
/// valid UTF-8 can't be kaeru's, so they come back empty.
fn lines(profile: &[u8]) -> Result<Vec<String>> {
    check_encoding(profile)?;
    if profile.starts_with(&UTF16_BOM) {
        return Ok(utf16(profile)?.lines().map(String::from).collect());
    }
    let profile = profile.strip_prefix(&UTF8_BOM).unwrap_or(profile);
    Ok(profile
        .split(|&byte| byte == b'\n')
        .map(|line| std::str::from_utf8(line).unwrap_or_default().to_string())
        .collect())
}

/// Decodes a UTF-16 profile, which starts with its byte order mark.
fn utf16(profile: &[u8]) -> Result<String> {
    let units: Vec<u16> = profile[UTF16_BOM.len()..]
        .chunks(2)
        .map(|pair| u16::from_le_bytes([pair[0], pair.get(1).copied().unwrap_or(0)]))
        .collect();
    match String::from_utf16(&units) {
        Ok(text) => Ok(text),
        Err(_) => bail!("the profile isn't valid UTF-16"),
    }
}

/// Encodes text as UTF-16, low byte first, with its byte order mark.
fn to_utf16(text: &str) -> Vec<u8> {
    UTF16_BOM
        .into_iter()
        .chain(text.encode_utf16().flat_map(u16::to_le_bytes))
        .collect()
}

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

    #[test]
    fn the_line_goes_at_the_end_of_a_profile() {
        let profile = b"Set-Alias ll Get-ChildItem";
        let added = add_line(profile, Kind::PowerShell).unwrap();
        let text = String::from_utf8(added.clone()).unwrap();
        assert!(text.starts_with("Set-Alias ll Get-ChildItem\r\n# kaeru"));
        assert!(text.ends_with(&format!("{LINE}\r\n")));
        assert!(has_line(&added, Kind::PowerShell).unwrap());
        assert!(!has_line(profile, Kind::PowerShell).unwrap());
    }

    #[test]
    fn an_empty_profile_gets_only_kaeru_s_lines() {
        let added = add_line(b"", Kind::PowerShell).unwrap();
        assert_eq!(added, format!("{COMMENT}\r\n{LINE}\r\n").into_bytes());
    }

    #[test]
    fn removing_the_line_leaves_the_rest_as_it_was() {
        let profile = b"Set-Alias ll Get-ChildItem\r\n";
        let added = add_line(profile, Kind::PowerShell).unwrap();
        assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), profile);
    }

    #[test]
    fn a_profile_in_another_code_page_keeps_its_bytes() {
        // "# " followed by bytes that aren't UTF-8, as a profile saved in a
        // Korean code page has.
        let profile = [b'#', b' ', 0xC7, 0xD1, 0xB1, 0xDB, b'\r', b'\n'];
        let added = add_line(&profile, Kind::PowerShell).unwrap();
        assert!(added.starts_with(&profile));
        assert!(has_line(&added, Kind::PowerShell).unwrap());
        assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), profile);
    }

    #[test]
    fn a_utf16_profile_stays_utf16() {
        let profile = to_utf16("Set-Alias ll Get-ChildItem\r\n");
        let added = add_line(&profile, Kind::PowerShell).unwrap();
        assert!(added.starts_with(&UTF16_BOM));
        assert!(has_line(&added, Kind::PowerShell).unwrap());
        assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), profile);
    }

    #[test]
    fn a_utf8_mark_doesnt_hide_kaeru_s_first_line() {
        // kaeru's lines were all the profile had, and an editor then saved
        // it with a byte order mark in front.
        let added = [&UTF8_BOM[..], &add_line(b"", Kind::PowerShell).unwrap()].concat();
        assert!(has_line(&added, Kind::PowerShell).unwrap());
        assert_eq!(remove_line(&added, Kind::PowerShell).unwrap(), UTF8_BOM);
    }

    #[test]
    fn a_bashrc_gets_bash_s_line_with_unix_line_endings() {
        let bashrc = b"alias ll='ls -l'";
        let added = add_line(bashrc, Kind::Bash).unwrap();
        let text = String::from_utf8(added.clone()).unwrap();
        assert_eq!(text, format!("alias ll='ls -l'\n{COMMENT}\n{BASH_LINE}\n"));
        assert!(has_line(&added, Kind::Bash).unwrap());
        assert!(!has_line(&added, Kind::PowerShell).unwrap());
        assert_eq!(
            remove_line(&added, Kind::Bash).unwrap(),
            b"alias ll='ls -l'\n"
        );
    }

    #[test]
    fn a_zshrc_gets_zsh_s_line_with_unix_line_endings() {
        let added = add_line(b"setopt autocd\n", Kind::Zsh).unwrap();
        let text = String::from_utf8(added.clone()).unwrap();
        assert_eq!(text, format!("setopt autocd\n{COMMENT}\n{ZSH_LINE}\n"));
        assert!(has_line(&added, Kind::Zsh).unwrap());
        assert!(!has_line(&added, Kind::Bash).unwrap());
        assert_eq!(remove_line(&added, Kind::Zsh).unwrap(), b"setopt autocd\n");
    }

    #[test]
    fn a_config_fish_gets_fish_s_line_with_unix_line_endings() {
        let added = add_line(b"set -g fish_greeting\n", Kind::Fish).unwrap();
        let text = String::from_utf8(added.clone()).unwrap();
        assert_eq!(
            text,
            format!("set -g fish_greeting\n{COMMENT}\n{FISH_LINE}\n")
        );
        assert!(has_line(&added, Kind::Fish).unwrap());
        assert!(!has_line(&added, Kind::Zsh).unwrap());
        assert_eq!(
            remove_line(&added, Kind::Fish).unwrap(),
            b"set -g fish_greeting\n"
        );
    }

    #[test]
    fn a_bash_profile_that_reads_bashrc_is_recognized() {
        assert!(reads_bashrc("test -f ~/.bashrc && . ~/.bashrc\n"));
        assert!(reads_bashrc(
            "if [ -f \"$HOME/.bashrc\" ]; then\n  source \"$HOME/.bashrc\"\nfi\n"
        ));
        assert!(!reads_bashrc("# . ~/.bashrc\nexport EDITOR=vim\n"));
    }

    #[test]
    fn a_utf16_big_endian_profile_is_left_alone() {
        let profile = [&UTF16_BE_BOM[..], &[0x00, 0x23]].concat();
        assert!(add_line(&profile, Kind::PowerShell).is_err());
        assert!(remove_line(&profile, Kind::PowerShell).is_err());
    }
}