1use crate::schema::json_schema_for;
2use anyhow::{Context as _, Result, anyhow};
3use assistant_tool::{ActionLog, Tool, ToolResult};
4use gpui::{AnyWindowHandle, App, AppContext, Entity, Task};
5use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
6use project::Project;
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use std::{path::Path, sync::Arc};
10use ui::IconName;
11use util::markdown::MarkdownInlineCode;
12
13#[derive(Debug, Serialize, Deserialize, JsonSchema)]
14pub struct MovePathToolInput {
15 /// The source path of the file or directory to move/rename.
16 ///
17 /// <example>
18 /// If the project has the following files:
19 ///
20 /// - directory1/a/something.txt
21 /// - directory2/a/things.txt
22 /// - directory3/a/other.txt
23 ///
24 /// You can move the first file by providing a source_path of "directory1/a/something.txt"
25 /// </example>
26 pub source_path: String,
27
28 /// The destination path where the file or directory should be moved/renamed to.
29 /// If the paths are the same except for the filename, then this will be a rename.
30 ///
31 /// <example>
32 /// To move "directory1/a/something.txt" to "directory2/b/renamed.txt",
33 /// provide a destination_path of "directory2/b/renamed.txt"
34 /// </example>
35 pub destination_path: String,
36}
37
38pub struct MovePathTool;
39
40impl Tool for MovePathTool {
41 fn name(&self) -> String {
42 "move_path".into()
43 }
44
45 fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
46 false
47 }
48
49 fn description(&self) -> String {
50 include_str!("./move_path_tool/description.md").into()
51 }
52
53 fn icon(&self) -> IconName {
54 IconName::ArrowRightLeft
55 }
56
57 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
58 json_schema_for::<MovePathToolInput>(format)
59 }
60
61 fn ui_text(&self, input: &serde_json::Value) -> String {
62 match serde_json::from_value::<MovePathToolInput>(input.clone()) {
63 Ok(input) => {
64 let src = MarkdownInlineCode(&input.source_path);
65 let dest = MarkdownInlineCode(&input.destination_path);
66 let src_path = Path::new(&input.source_path);
67 let dest_path = Path::new(&input.destination_path);
68
69 match dest_path
70 .file_name()
71 .and_then(|os_str| os_str.to_os_string().into_string().ok())
72 {
73 Some(filename) if src_path.parent() == dest_path.parent() => {
74 let filename = MarkdownInlineCode(&filename);
75 format!("Rename {src} to {filename}")
76 }
77 _ => {
78 format!("Move {src} to {dest}")
79 }
80 }
81 }
82 Err(_) => "Move path".to_string(),
83 }
84 }
85
86 fn run(
87 self: Arc<Self>,
88 input: serde_json::Value,
89 _request: Arc<LanguageModelRequest>,
90 project: Entity<Project>,
91 _action_log: Entity<ActionLog>,
92 _model: Arc<dyn LanguageModel>,
93 _window: Option<AnyWindowHandle>,
94 cx: &mut App,
95 ) -> ToolResult {
96 let input = match serde_json::from_value::<MovePathToolInput>(input) {
97 Ok(input) => input,
98 Err(err) => return Task::ready(Err(anyhow!(err))).into(),
99 };
100 let rename_task = project.update(cx, |project, cx| {
101 match project
102 .find_project_path(&input.source_path, cx)
103 .and_then(|project_path| project.entry_for_path(&project_path, cx))
104 {
105 Some(entity) => match project.find_project_path(&input.destination_path, cx) {
106 Some(project_path) => project.rename_entry(entity.id, project_path.path, cx),
107 None => Task::ready(Err(anyhow!(
108 "Destination path {} was outside the project.",
109 input.destination_path
110 ))),
111 },
112 None => Task::ready(Err(anyhow!(
113 "Source path {} was not found in the project.",
114 input.source_path
115 ))),
116 }
117 });
118
119 cx.background_spawn(async move {
120 let _ = rename_task.await.with_context(|| {
121 format!("Moving {} to {}", input.source_path, input.destination_path)
122 })?;
123 Ok(format!("Moved {} to {}", input.source_path, input.destination_path).into())
124 })
125 .into()
126 }
127}