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::sync::Arc;
9use ui::IconName;
10use util::markdown::MarkdownString;
11
12#[derive(Debug, Serialize, Deserialize, JsonSchema)]
13pub struct CreateDirectoryToolInput {
14 /// The path of the new directory.
15 ///
16 /// <example>
17 /// If the project has the following structure:
18 ///
19 /// - directory1/
20 /// - directory2/
21 ///
22 /// You can create a new directory by providing a path of "directory1/new_directory"
23 /// </example>
24 pub path: String,
25}
26
27pub struct CreateDirectoryTool;
28
29impl Tool for CreateDirectoryTool {
30 fn name(&self) -> String {
31 "create-directory".into()
32 }
33
34 fn needs_confirmation(&self) -> bool {
35 true
36 }
37
38 fn description(&self) -> String {
39 include_str!("./create_directory_tool/description.md").into()
40 }
41
42 fn icon(&self) -> IconName {
43 IconName::Folder
44 }
45
46 fn input_schema(&self) -> serde_json::Value {
47 let schema = schemars::schema_for!(CreateDirectoryToolInput);
48 serde_json::to_value(&schema).unwrap()
49 }
50
51 fn ui_text(&self, input: &serde_json::Value) -> String {
52 match serde_json::from_value::<CreateDirectoryToolInput>(input.clone()) {
53 Ok(input) => {
54 format!("Create directory `{}`", MarkdownString::escape(&input.path))
55 }
56 Err(_) => "Create 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::<CreateDirectoryToolInput>(input) {
69 Ok(input) => input,
70 Err(err) => return Task::ready(Err(anyhow!(err))),
71 };
72 let project_path = match project.read(cx).find_project_path(&input.path, cx) {
73 Some(project_path) => project_path,
74 None => return Task::ready(Err(anyhow!("Path to create was outside the project"))),
75 };
76 let destination_path: Arc<str> = input.path.as_str().into();
77
78 cx.spawn(async move |cx| {
79 project
80 .update(cx, |project, cx| {
81 project.create_entry(project_path.clone(), true, cx)
82 })?
83 .await
84 .map_err(|err| anyhow!("Unable to create directory {destination_path}: {err}"))?;
85
86 Ok(format!("Created directory {destination_path}"))
87 })
88 }
89}