kaeru 0.1.0

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! PowerShell profiles: 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.
pub const LINE: &str = "Invoke-Expression (& kaeru init powershell | Out-String)";

/// The comment that `kaeru install` puts above the line.
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];

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

/// Returns the profiles that `kaeru install` sets up: the current user's
/// console profile of Windows PowerShell, and of PowerShell 7 when that is
/// installed. Both are in the Documents folder, wherever Windows keeps it,
/// which is where PowerShell's `$PROFILE` points.
pub fn profiles() -> Vec<Profile> {
    if !cfg!(windows) {
        return Vec::new();
    }
    let Some(documents) = dirs::document_dir() else {
        return Vec::new();
    };
    let mut found = vec![Profile {
        shell: "Windows PowerShell",
        path: documents
            .join("WindowsPowerShell")
            .join("Microsoft.PowerShell_profile.ps1"),
    }];
    if super::on_path("pwsh.exe").is_some() {
        found.push(Profile {
            shell: "PowerShell 7",
            path: documents
                .join("PowerShell")
                .join("Microsoft.PowerShell_profile.ps1"),
        });
    }
    found
}

/// 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]) -> Result<bool> {
    Ok(lines(profile)?.iter().any(|line| line.trim() == 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]) -> Result<Vec<u8>> {
    let added = format!("{COMMENT}\r\n{LINE}\r\n");
    if profile.starts_with(&UTF16_BOM) {
        let mut text = utf16(profile)?;
        if !text.is_empty() && !text.ends_with('\n') {
            text.push_str("\r\n");
        }
        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(b"\r\n");
    }
    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]) -> Result<Vec<u8>> {
    let ours = |line: &str| {
        let line = line.trim();
        line == 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));
    }
    // ASCII lines can be found in the bytes of any code page except UTF-16.
    Ok(profile
        .split_inclusive(|&byte| byte == b'\n')
        .filter(|line| !std::str::from_utf8(line).is_ok_and(ours))
        .flatten()
        .copied()
        .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>> {
    if profile.starts_with(&UTF16_BOM) {
        return Ok(utf16(profile)?.lines().map(String::from).collect());
    }
    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).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).unwrap());
        assert!(!has_line(profile).unwrap());
    }

    #[test]
    fn an_empty_profile_gets_only_kaeru_s_lines() {
        let added = add_line(b"").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).unwrap();
        assert_eq!(remove_line(&added).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).unwrap();
        assert!(added.starts_with(&profile));
        assert!(has_line(&added).unwrap());
        assert_eq!(remove_line(&added).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).unwrap();
        assert!(added.starts_with(&UTF16_BOM));
        assert!(has_line(&added).unwrap());
        assert_eq!(remove_line(&added).unwrap(), profile);
    }
}