kaeru 0.1.1

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! The OS's process table, read with sysinfo, which uses each OS's native
//! process APIs.

use std::path::Path;

use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};

use super::{ProcInfo, ProcessTable, lineage};

/// A snapshot of the processes that run on this computer.
///
/// The snapshot reads every process's id, parent, name and start time at
/// once, which is fast. The slower details, the executable path, the command
/// line and the working folder, are read only for the processes that
/// [`SystemTable::lineage`] walks or [`SystemTable::find`] finds.
pub struct SystemTable {
    system: System,
}

impl SystemTable {
    /// Returns a snapshot of the processes that run now.
    pub fn snapshot() -> Self {
        let mut system = System::new();
        system.refresh_processes_specifics(
            ProcessesToUpdate::All,
            true,
            ProcessRefreshKind::nothing(),
        );
        SystemTable { system }
    }

    /// Returns the process and its ancestors, nearest first, with their
    /// executable paths and command lines.
    pub fn lineage(&mut self, pid: u32) -> Vec<ProcInfo> {
        let pids: Vec<Pid> = lineage(self, pid)
            .iter()
            .map(|process| Pid::from_u32(process.pid))
            .collect();
        self.system.refresh_processes_specifics(
            ProcessesToUpdate::Some(&pids),
            false,
            ProcessRefreshKind::nothing()
                .with_exe(UpdateKind::Always)
                .with_cmd(UpdateKind::Always),
        );
        lineage(self, pid)
    }

    /// Returns the processes whose executable name `wanted` accepts, with
    /// their executable paths, command lines and working folders.
    pub fn find(&mut self, wanted: impl Fn(&str) -> bool) -> Vec<ProcInfo> {
        let pids: Vec<Pid> = self
            .system
            .processes()
            .iter()
            .filter(|(_, process)| wanted(&process.name().to_string_lossy()))
            .map(|(&pid, _)| pid)
            .collect();
        self.system.refresh_processes_specifics(
            ProcessesToUpdate::Some(&pids),
            false,
            ProcessRefreshKind::nothing()
                .with_exe(UpdateKind::Always)
                .with_cmd(UpdateKind::Always)
                .with_cwd(UpdateKind::Always),
        );
        pids.iter()
            .filter_map(|pid| self.get(pid.as_u32()))
            .collect()
    }
}

impl ProcessTable for SystemTable {
    fn get(&self, pid: u32) -> Option<ProcInfo> {
        let process = self.system.process(Pid::from_u32(pid))?;
        let arguments: Vec<String> = process
            .cmd()
            .iter()
            .map(|argument| argument.to_string_lossy().into_owned())
            .collect();
        Some(ProcInfo {
            pid,
            parent: process.parent().map(Pid::as_u32),
            name: process.name().to_string_lossy().into_owned(),
            exe: process.exe().map(Path::to_path_buf),
            // sysinfo reports start times in whole seconds, and 0 when it
            // can't read them.
            started_ms: Some(process.start_time())
                .filter(|&seconds| seconds > 0)
                .map(|seconds| seconds * 1000),
            command_line: (!arguments.is_empty()).then(|| arguments.join(" ")),
            arguments,
            cwd: process.cwd().map(Path::to_path_buf),
        })
    }
}

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

    #[test]
    fn finds_this_test_process() {
        let me = SystemTable::snapshot().get(std::process::id()).unwrap();
        assert!(me.started_ms.is_some());
        assert!(me.parent.is_some());
    }

    #[test]
    fn the_lineage_has_details() {
        let chain = SystemTable::snapshot().lineage(std::process::id());
        let me = chain.first().unwrap();
        assert_eq!(me.pid, std::process::id());
        assert!(me.exe.is_some());
        assert!(me.command_line.is_some());
        assert!(!me.arguments.is_empty());
    }

    #[test]
    fn found_processes_have_their_working_folder() {
        let mut table = SystemTable::snapshot();
        let me = table.get(std::process::id()).unwrap();
        let found = table.find(|name| name == me.name);
        let me = found
            .iter()
            .find(|process| process.pid == std::process::id())
            .unwrap();
        assert_eq!(me.cwd, Some(std::env::current_dir().unwrap()));
    }
}