kaeru 0.1.8

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Starting the programs that open tabs, for the terminals that kaeru opens
//! from the command line.

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use anyhow::{Context, Result, bail};

use super::TabToOpen;
use crate::shells;

/// Runs `program` with `args` and waits for it, for a program that hands the
/// tab to a terminal that already runs and then ends, such as
/// `gnome-terminal`. It fails when the program fails.
pub fn run(program: &Path, args: &[String]) -> Result<()> {
    let status = Command::new(program)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .with_context(|| format!("can't start {}", program.display()))?;
    if !status.success() {
        bail!("{} failed: {status}", program.display());
    }
    Ok(())
}

/// Starts `program` with `args` without waiting for it, for a terminal that
/// kaeru starts anew. It runs in a process group of its own, with no input
/// or output, so that it keeps running when the tab that started it closes:
/// a terminal that closes a tab hangs up the programs in the tab's process
/// group, as when the picker's tab closes after the other tabs came back.
pub fn start(program: &Path, args: &[String]) -> Result<()> {
    let mut command = Command::new(program);
    command
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    command
        .spawn()
        .with_context(|| format!("can't start {}", program.display()))?;
    Ok(())
}

/// Returns the program next to `exe`, the terminal's executable, that is
/// named `name`, when it is there, and `name` otherwise, which the PATH
/// finds. A terminal's helper programs are installed together with it.
pub fn beside(exe: Option<&Path>, name: &str) -> PathBuf {
    exe.and_then(Path::parent)
        .map(|folder| folder.join(name))
        .filter(|program| program.is_file())
        .unwrap_or_else(|| PathBuf::from(name))
}

/// Returns the command that a reopened tab runs, as the program and its
/// arguments, or an empty list for a tab that runs nothing, which starts
/// the terminal's own shell. A tab that runs something starts its shell
/// with the code to run, as [`shells::shell_with_run`] says. When kaeru
/// can't hand that shell the code, the tab starts the terminal's own shell,
/// so that it still comes back in its folder.
pub fn command(tab: &TabToOpen) -> Vec<String> {
    shells::shell_with_run(tab).unwrap_or_default()
}