kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! AppleScript, which the adapters of macOS terminals use to open tabs,
//! because those terminals have no command-line tool for it. A script is
//! constant, and the values it needs, such as a folder, are passed to it as
//! arguments, so that no value is ever quoted inside a script.

use anyhow::Result;

/// Runs `script`, an AppleScript whose `run` handler takes `arguments` as
/// its `argv`, with `osascript`, and waits for it to finish.
///
/// # Errors
///
/// Fails when `osascript` can't start, or the script fails, with what
/// `osascript` printed.
#[cfg(target_os = "macos")]
pub fn run(script: &str, arguments: &[String]) -> Result<()> {
    use anyhow::{Context, bail};

    // `--` ends osascript's options, so that an argument that starts with
    // a dash is passed on as it is.
    let output = std::process::Command::new("osascript")
        .arg("-e")
        .arg(script)
        .arg("--")
        .args(arguments)
        .output()
        .context("can't start osascript")?;
    if !output.status.success() {
        bail!(
            "AppleScript failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

/// Fails, because AppleScript runs only on macOS.
#[cfg(not(target_os = "macos"))]
pub fn run(_script: &str, _arguments: &[String]) -> Result<()> {
    anyhow::bail!("AppleScript runs only on macOS")
}

/// Runs `script` as [`run`] does, and returns what it printed, or ends it
/// and fails when it takes longer than `limit`, so that a terminal that
/// doesn't answer can't hold up a new tab.
///
/// # Errors
///
/// Fails when `osascript` can't start, the script fails, or it takes too
/// long.
#[cfg(target_os = "macos")]
pub fn output(script: &str, arguments: &[String], limit: std::time::Duration) -> Result<String> {
    use std::io::Read;
    use std::process::Stdio;
    use std::time::Instant;

    use anyhow::{Context, bail};

    let mut child = std::process::Command::new("osascript")
        .arg("-e")
        .arg(script)
        .arg("--")
        .args(arguments)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .context("can't start osascript")?;
    let started = Instant::now();
    let status = loop {
        if let Some(status) = child.try_wait()? {
            break status;
        }
        if started.elapsed() > limit {
            let _ = child.kill();
            let _ = child.wait();
            bail!("AppleScript took longer than {limit:?}");
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    };
    let mut printed = String::new();
    if let Some(mut stdout) = child.stdout.take() {
        stdout.read_to_string(&mut printed)?;
    }
    if !status.success() {
        bail!("AppleScript failed");
    }
    Ok(printed)
}