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};
const REFUSED: i32 = 126;
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,
})
}
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(())
}
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))
}
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
}
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}...")
}