eclipse-cli 0.13.4

Command-line interface for eclipse
//! `eclipse scripts list | run | cat`: the scripts the agent has written, for the person who has
//! to trust them.
//!
//! These go through the same functions the `script` tool uses ([`tools_script::list_scripts`],
//! [`tools_script::resolve`], [`tools_script::command`]), so the listing cannot describe a script
//! the tool would not run and `run` applies the tool's refusals and gives the script the tool's
//! environment. The differences are the point of having a CLI: `run` hands the script this
//! terminal's stdio, so it works in a pipeline, and exits with the script's own exit code; and it
//! has no timeout, because the timeout exists to limit an agent and a person can press Ctrl-C.

use crate::ui::Style;
use anyhow::{bail, Context, Result};
use eclipse_core::config::{process_env, Config};
use eclipse_core::tools_script::{self, ScriptInfo};
use serde_json::json;
use std::io::{Read, Write};

/// The exit code for a script that was refused, as a shell uses it for "found, but cannot be
/// executed": distinct from anything a script is likely to return on purpose.
const REFUSED: i32 = 126;

/// The most `cat` will read. A script is a short text file; this is a bound on a file the agent
/// wrote, not a limit anyone should meet.
const MAX_CAT_BYTES: u64 = 1024 * 1024;

fn describe(info: &ScriptInfo) -> serde_json::Value {
    json!({
        "name": info.name,
        "description": info.description,
        "path": info.path,
        "executable": info.executable,
        "escapes": info.escapes,
    })
}

/// `eclipse scripts list`: the directory, then each script's name, description and path.
pub fn list(cfg: &Config, style: &Style, as_json: bool) -> Result<()> {
    let dir = scripts_dir(cfg)?;
    let listing = tools_script::list_scripts(&dir).map_err(anyhow::Error::msg)?;
    if listing.omitted > 0 {
        eprintln!(
            "{} {} more scripts are not shown",
            style.yellow("warning:"),
            listing.omitted
        );
    }
    if as_json {
        let all: Vec<_> = listing.scripts.iter().map(describe).collect();
        println!("{}", serde_json::to_string_pretty(&all)?);
        return Ok(());
    }
    println!("{} {}", style.dim("scripts directory:"), dir.display());
    if listing.scripts.is_empty() {
        println!();
        if listing.exists {
            println!("no scripts: the directory is empty");
        } else {
            println!("no scripts: the directory does not exist yet");
        }
        return Ok(());
    }
    println!(
        "{} {}",
        style.dim("scripts:"),
        listing.scripts.len() + listing.omitted
    );
    println!();
    let width = listing
        .scripts
        .iter()
        .map(|s| s.name.chars().count())
        .chain(std::iter::once(4))
        .max()
        .unwrap_or(4);
    println!(
        "{}",
        style.dim(&format!("{:<width$}  {:<40}  PATH", "NAME", "DESCRIPTION"))
    );
    for info in &listing.scripts {
        let description = info.description.as_deref().unwrap_or("");
        let name = format!("{:<width$}", info.name);
        let name = if info.executable && !info.escapes {
            name
        } else {
            style.red(&name)
        };
        println!(
            "{name}  {:<40}  {}",
            truncate(description, 40),
            info.path.display()
        );
        if info.escapes {
            println!(
                "  {} a symlink that leaves the directory; it will not be run",
                style.red("REFUSED:")
            );
        } else if !info.executable {
            println!(
                "  {} not executable; `chmod +x` it before it can be run",
                style.red("NOTE:")
            );
        }
    }
    Ok(())
}

/// `eclipse scripts run <name> [args...]`: the exit code to exit with.
///
/// A refusal is reported on stderr and is [`REFUSED`], not `1`, so a pipeline can tell "the
/// script said no" from "eclipse would not run it".
pub fn run(cfg: &Config, name: &str, args: &[String]) -> Result<i32> {
    let dir = scripts_dir(cfg)?;
    let script = match tools_script::resolve(&dir, name) {
        Ok(path) => path,
        Err(why) => {
            eprintln!("script {name:?} refused: {why}");
            return Ok(REFUSED);
        }
    };
    let status = tools_script::command(&dir, &script, args)
        .status()
        .map_err(|e| anyhow::anyhow!(tools_script::start_error(&e)))
        .with_context(|| format!("script {name:?}"))?;
    Ok(exit_code(status))
}

/// The code to exit with for `status`: the script's own, or `128 + n` when a signal ended it,
/// which is what a shell reports.
fn exit_code(status: std::process::ExitStatus) -> i32 {
    if let Some(code) = status.code() {
        return code;
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(signal) = status.signal() {
            return 128 + signal;
        }
    }
    1
}

/// `eclipse scripts cat <name>`: the file as it is, shebang included. It need not be executable
/// to be read, and is read up to [`MAX_CAT_BYTES`].
pub fn cat(cfg: &Config, name: &str) -> Result<()> {
    let dir = scripts_dir(cfg)?;
    let path = match tools_script::locate_file(&dir, name) {
        Ok(path) => path,
        Err(why) => bail!("script {name:?} refused: {why}"),
    };
    let mut bytes = Vec::new();
    std::fs::File::open(&path)
        .with_context(|| path.display().to_string())?
        .take(MAX_CAT_BYTES + 1)
        .read_to_end(&mut bytes)
        .with_context(|| path.display().to_string())?;
    let cut = bytes.len() as u64 > MAX_CAT_BYTES;
    bytes.truncate(MAX_CAT_BYTES as usize);
    std::io::stdout().write_all(&bytes)?;
    if cut {
        eprintln!("[truncated: only the first {MAX_CAT_BYTES} bytes are shown]");
    }
    Ok(())
}

fn scripts_dir(cfg: &Config) -> Result<std::path::PathBuf> {
    match cfg.scripts_dir(&process_env) {
        Some(dir) => Ok(dir),
        None => bail!("cannot work out the scripts directory: no config directory (set HOME or XDG_CONFIG_HOME)"),
    }
}

fn truncate(text: &str, width: usize) -> String {
    if text.chars().count() <= width {
        return text.to_string();
    }
    let kept: String = text.chars().take(width.saturating_sub(3)).collect();
    format!("{kept}...")
}