Skip to main content

tinyharness_lib/tools/
ls.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::Path;
4
5use crate::extract_args;
6use crate::path_guard::PathGuard;
7use crate::tools::tool::{BoxFuture, ToolCategory, build_string_params_schema, make_tool};
8
9pub fn ls_tool_entry(guard: Option<PathGuard>) -> crate::tools::tool::Tool {
10    make_tool(
11        "ls",
12        "List directory contents. Returns a newline-separated list of files and directories in the specified path.",
13        ToolCategory::ReadOnly,
14        build_string_params_schema(&[("path", "The directory path to list")], &[]),
15        move |args| {
16            let guard = guard.clone();
17            Box::pin(ls_tool_inner(args, guard))
18        },
19    )
20}
21
22pub fn ls_tool(args: HashMap<String, String>) -> BoxFuture<'static, String> {
23    Box::pin(ls_tool_inner(args, None))
24}
25
26async fn ls_tool_inner(args: HashMap<String, String>, guard: Option<PathGuard>) -> String {
27    extract_args!(args, path);
28
29    let dir_path = Path::new(&path);
30
31    if !dir_path.exists() {
32        return format!("Error: Path '{}' does not exist", path);
33    }
34
35    if !dir_path.is_dir() {
36        return format!("Error: '{}' is not a directory", path);
37    }
38
39    // When a guard is active, verify the open descriptor before listing, so a
40    // symlink swapped in after the argument check cannot turn this into a
41    // listing of a directory outside the allowed roots.
42    if let Some(g) = &guard
43        && let Err(e) = g.open_dir_contained(dir_path)
44    {
45        return e;
46    }
47
48    let entries = match fs::read_dir(&path) {
49        Ok(e) => e,
50        Err(e) => return format!("Error: Failed to read directory: {}", e),
51    };
52
53    let mut files: Vec<String> = entries
54        .filter_map(|entry| entry.ok())
55        .map(|entry| {
56            let file_name = entry.file_name();
57            let name = file_name.to_string_lossy().to_string();
58            let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
59            if is_dir { format!("{}/", name) } else { name }
60        })
61        .collect();
62
63    files.sort();
64
65    if files.is_empty() {
66        return "Directory is empty".to_string();
67    }
68
69    files.join("\n")
70}