use std::path::{Path, PathBuf};
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::tools::fs::{FsError, scoped_path};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub struct ListDirTool {
working_dir: PathBuf,
}
impl ListDirTool {
pub fn new(working_dir: impl Into<PathBuf>) -> Self {
Self {
working_dir: working_dir.into(),
}
}
fn list_inner(&self, sub_path: Option<&str>) -> Result<String, FsError> {
let target = match sub_path {
Some(p) => scoped_path(&self.working_dir, Path::new(p))?,
None => scoped_path(&self.working_dir, Path::new("."))?,
};
let meta = std::fs::metadata(&target).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
FsError::NotFound(target.clone())
} else {
FsError::io(&target, e)
}
})?;
if !meta.is_dir() {
return Err(FsError::NotADirectory(target));
}
let read = std::fs::read_dir(&target).map_err(|e| FsError::io(&target, e))?;
let mut entries = Vec::new();
for dirent in read {
let dirent = dirent.map_err(|e| FsError::io(&target, e))?;
let name = dirent.file_name().to_string_lossy().into_owned();
let is_dir = dirent.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
if is_dir {
entries.push(format!("{name}/"));
} else {
entries.push(name);
}
}
if entries.is_empty() {
return Ok("(empty directory)".to_string());
}
entries.sort();
Ok(entries.join("\n"))
}
}
#[async_trait]
impl ToolExecutor for ListDirTool {
fn name(&self) -> &str {
"list_dir"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "list_dir",
"description": "List the immediate entries of a directory (non-recursive). Directories are suffixed with '/'. Defaults to the project root. Prefer this over shelling out to 'ls'.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Directory to list, relative to the working directory. Defaults to the project root."
}
},
"required": [],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
let sub_path = args.get("path").and_then(Value::as_str);
match self.list_inner(sub_path) {
Ok(listing) => ToolResult::ok(listing),
Err(e) => ToolResult::err(e.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use serde_json::json;
use super::*;
use crate::tools::traits::ToolExecutor;
#[tokio::test]
async fn list_dir_lists_entries() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::write(tmp.path().join("main.py"), "x\n").expect("write");
fs::create_dir_all(tmp.path().join("pkg")).expect("mkdir");
let tool = ListDirTool::new(tmp.path());
let result = tool.execute(json!({})).await;
assert!(!result.is_error(), "unexpected error: {}", result.content());
let out = result.content();
assert!(out.contains("main.py"), "file missing: {out}");
assert!(out.contains("pkg/"), "dir must be tagged with '/': {out}");
}
#[tokio::test]
async fn list_dir_scoped_to_subdirectory() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::write(tmp.path().join("main.py"), "x\n").expect("write");
fs::create_dir_all(tmp.path().join("pkg")).expect("mkdir");
fs::write(tmp.path().join("pkg/mod.py"), "y\n").expect("write");
let tool = ListDirTool::new(tmp.path());
let result = tool.execute(json!({"path": "pkg"})).await;
assert!(!result.is_error());
let out = result.content();
assert!(out.contains("mod.py"), "pkg/mod.py entry missing: {out}");
assert!(!out.contains("main.py"), "root file must not appear: {out}");
}
#[tokio::test]
async fn list_dir_empty_directory() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::create_dir_all(tmp.path().join("empty")).expect("mkdir");
let tool = ListDirTool::new(tmp.path());
let result = tool.execute(json!({"path": "empty"})).await;
assert!(!result.is_error());
assert!(
result.content().contains("empty directory"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn list_dir_missing_directory_errors() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = ListDirTool::new(tmp.path());
let result = tool.execute(json!({"path": "does_not_exist"})).await;
assert!(result.is_error());
assert!(
result.content().contains("not found"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn list_dir_on_file_errors() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::write(tmp.path().join("f.txt"), "x\n").expect("write");
let tool = ListDirTool::new(tmp.path());
let result = tool.execute(json!({"path": "f.txt"})).await;
assert!(result.is_error());
assert!(
result.content().contains("not a directory"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn list_dir_path_traversal_is_rejected() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = ListDirTool::new(tmp.path());
let result = tool.execute(json!({"path": "../../etc"})).await;
assert!(result.is_error());
assert!(
result.content().contains("escapes"),
"unexpected message: {}",
result.content()
);
}
#[test]
fn schema_has_no_required_fields() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = ListDirTool::new(tmp.path());
let schema = tool.schema();
let required = schema["function"]["parameters"]["required"]
.as_array()
.expect("required array");
assert!(required.is_empty(), "list_dir must have no required fields");
}
}