1use anyhow::{anyhow, Result};
2use assistant_tool::{ActionLog, Tool};
3use gpui::{App, Entity, Task};
4use language_model::LanguageModelRequestMessage;
5use project::Project;
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use std::{fmt::Write, path::Path, sync::Arc};
9
10#[derive(Debug, Serialize, Deserialize, JsonSchema)]
11pub struct ListDirectoryToolInput {
12 /// The relative path of the directory to list.
13 ///
14 /// This path should never be absolute, and the first component
15 /// of the path should always be a root directory in a project.
16 ///
17 /// <example>
18 /// If the project has the following root directories:
19 ///
20 /// - directory1
21 /// - directory2
22 ///
23 /// You can list the contents of `directory1` by using the path `directory1`.
24 /// </example>
25 ///
26 /// <example>
27 /// If the project has the following root directories:
28 ///
29 /// - foo
30 /// - bar
31 ///
32 /// If you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.
33 /// </example>
34 pub path: Arc<Path>,
35}
36
37pub struct ListDirectoryTool;
38
39impl Tool for ListDirectoryTool {
40 fn name(&self) -> String {
41 "list-directory".into()
42 }
43
44 fn description(&self) -> String {
45 include_str!("./list_directory_tool/description.md").into()
46 }
47
48 fn input_schema(&self) -> serde_json::Value {
49 let schema = schemars::schema_for!(ListDirectoryToolInput);
50 serde_json::to_value(&schema).unwrap()
51 }
52
53 fn ui_text(&self, input: &serde_json::Value) -> String {
54 match serde_json::from_value::<ListDirectoryToolInput>(input.clone()) {
55 Ok(input) => format!("List the `{}` directory's contents", input.path.display()),
56 Err(_) => "List directory".to_string(),
57 }
58 }
59
60 fn run(
61 self: Arc<Self>,
62 input: serde_json::Value,
63 _messages: &[LanguageModelRequestMessage],
64 project: Entity<Project>,
65 _action_log: Entity<ActionLog>,
66 cx: &mut App,
67 ) -> Task<Result<String>> {
68 let input = match serde_json::from_value::<ListDirectoryToolInput>(input) {
69 Ok(input) => input,
70 Err(err) => return Task::ready(Err(anyhow!(err))),
71 };
72
73 let Some(project_path) = project.read(cx).find_project_path(&input.path, cx) else {
74 return Task::ready(Err(anyhow!(
75 "Path {} not found in project",
76 input.path.display()
77 )));
78 };
79 let Some(worktree) = project
80 .read(cx)
81 .worktree_for_id(project_path.worktree_id, cx)
82 else {
83 return Task::ready(Err(anyhow!("Worktree not found")));
84 };
85 let worktree = worktree.read(cx);
86
87 let Some(entry) = worktree.entry_for_path(&project_path.path) else {
88 return Task::ready(Err(anyhow!("Path not found: {}", input.path.display())));
89 };
90
91 if !entry.is_dir() {
92 return Task::ready(Err(anyhow!("{} is not a directory.", input.path.display())));
93 }
94
95 let mut output = String::new();
96 for entry in worktree.child_entries(&project_path.path) {
97 writeln!(
98 output,
99 "{}",
100 Path::new(worktree.root_name()).join(&entry.path).display(),
101 )
102 .unwrap();
103 }
104 if output.is_empty() {
105 return Task::ready(Ok(format!("{} is empty.", input.path.display())));
106 }
107 Task::ready(Ok(output))
108 }
109}