use std::path::{Path, PathBuf};
use crate::domain::ToolDef;
use crate::script;
pub fn resolve(dir: &Path, name: &str) -> Result<ToolDef, String> {
let path = find(dir, name)?;
let script = std::fs::canonicalize(&path)
.map_err(|e| format!("tool '{name}' script {} can't be read: {e}", path.display()))?;
let summary = script::summarize(&script).map_err(|e| {
format!(
"tool '{name}' script {} can't be read: {e}",
script.display()
)
})?;
Ok(ToolDef {
name: name.to_string(),
script,
description: summary.desc.unwrap_or_default(),
params: summary.params,
output: summary.output,
exits: summary.exits,
})
}
pub fn resolve_all(dir: &Path, names: &[String]) -> Result<Vec<ToolDef>, String> {
names.iter().map(|name| resolve(dir, name)).collect()
}
pub fn exists(dir: &Path, name: &str) -> bool {
entries_with_stem(dir, name).is_ok_and(|m| !m.is_empty())
}
pub fn list(dir: &Path) -> Result<Vec<String>, String> {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(format!("can't read tools dir {}: {e}", dir.display())),
};
let mut names = std::collections::BTreeSet::new();
for entry in read.flatten() {
let path = entry.path();
if path.is_dir() {
continue;
}
if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
if is_valid_tool_name(stem) {
names.insert(stem.to_string());
}
}
}
Ok(names.into_iter().collect())
}
pub fn remove(dir: &Path, name: &str) -> Result<bool, String> {
let mut removed = false;
for path in entries_with_stem(dir, name)? {
std::fs::remove_file(&path)
.map_err(|e| format!("failed to remove {}: {e}", path.display()))?;
removed = true;
}
Ok(removed)
}
pub fn is_valid_tool_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
fn find(dir: &Path, name: &str) -> Result<PathBuf, String> {
let mut matches = entries_with_stem(dir, name)?;
match matches.len() {
0 => Err(format!("unknown tool: {name}")),
1 => Ok(matches.pop().expect("len checked")),
n => Err(format!(
"tool '{name}' is ambiguous: {n} files in {} share that name; keep one",
dir.display()
)),
}
}
fn entries_with_stem(dir: &Path, name: &str) -> Result<Vec<PathBuf>, String> {
crate::store::entries_with_stem(dir, name)
.map_err(|e| format!("can't read tools dir {}: {e}", dir.display()))
}
#[cfg(test)]
#[path = "tools_tests.rs"]
mod tests;