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, _: &Entity<Project>, _: &App) -> bool {
46 false
47 }
48
49 fn may_perform_edits(&self) -> bool {
50 true
51 }
52
53 fn description(&self) -> String {
54 include_str!("./move_path_tool/description.md").into()
55 }
56
57 fn icon(&self) -> IconName {
58 IconName::ArrowRightLeft
59 }
60
61 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
62 json_schema_for::<MovePathToolInput>(format)
63 }
64
65 fn ui_text(&self, input: &serde_json::Value) -> String {
66 match serde_json::from_value::<MovePathToolInput>(input.clone()) {
67 Ok(input) => {
68 let src = MarkdownInlineCode(&input.source_path);
69 let dest = MarkdownInlineCode(&input.destination_path);
70 let src_path = Path::new(&input.source_path);
71 let dest_path = Path::new(&input.destination_path);
72
73 match dest_path
74 .file_name()
75 .and_then(|os_str| os_str.to_os_string().into_string().ok())
76 {
77 Some(filename) if src_path.parent() == dest_path.parent() => {
78 let filename = MarkdownInlineCode(&filename);
79 format!("Rename {src} to {filename}")
80 }
81 _ => {
82 format!("Move {src} to {dest}")
83 }
84 }
85 }
86 Err(_) => "Move path".to_string(),
87 }
88 }
89
90 fn run(
91 self: Arc<Self>,
92 input: serde_json::Value,
93 _request: Arc<LanguageModelRequest>,
94 project: Entity<Project>,
95 _action_log: Entity<ActionLog>,
96 _model: Arc<dyn LanguageModel>,
97 _window: Option<AnyWindowHandle>,
98 cx: &mut App,
99 ) -> ToolResult {
100 let input = match serde_json::from_value::<MovePathToolInput>(input) {
101 Ok(input) => input,
102 Err(err) => return Task::ready(Err(anyhow!(err))).into(),
103 };
104 let rename_task = project.update(cx, |project, cx| {
105 match project
106 .find_project_path(&input.source_path, cx)
107 .and_then(|project_path| project.entry_for_path(&project_path, cx))
108 {
109 Some(entity) => match project.find_project_path(&input.destination_path, cx) {
110 Some(project_path) => project.rename_entry(entity.id, project_path.path, cx),
111 None => Task::ready(Err(anyhow!(
112 "Destination path {} was outside the project.",
113 input.destination_path
114 ))),
115 },
116 None => Task::ready(Err(anyhow!(
117 "Source path {} was not found in the project.",
118 input.source_path
119 ))),
120 }
121 });
122
123 cx.background_spawn(async move {
124 let _ = rename_task.await.with_context(|| {
125 format!("Moving {} to {}", input.source_path, input.destination_path)
126 })?;
127 Ok(format!("Moved {} to {}", input.source_path, input.destination_path).into())
128 })
129 .into()
130 }
131}