move_path_tool.rs

  1use crate::schema::json_schema_for;
  2use anyhow::{Result, anyhow};
  3use assistant_tool::{ActionLog, Tool, ToolResult};
  4use gpui::{AnyWindowHandle, App, AppContext, Entity, Task};
  5use language_model::{LanguageModelRequestMessage, 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        _messages: &[LanguageModelRequestMessage],
 90        project: Entity<Project>,
 91        _action_log: Entity<ActionLog>,
 92        _window: Option<AnyWindowHandle>,
 93        cx: &mut App,
 94    ) -> ToolResult {
 95        let input = match serde_json::from_value::<MovePathToolInput>(input) {
 96            Ok(input) => input,
 97            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
 98        };
 99        let rename_task = project.update(cx, |project, cx| {
100            match project
101                .find_project_path(&input.source_path, cx)
102                .and_then(|project_path| project.entry_for_path(&project_path, cx))
103            {
104                Some(entity) => match project.find_project_path(&input.destination_path, cx) {
105                    Some(project_path) => project.rename_entry(entity.id, project_path.path, cx),
106                    None => Task::ready(Err(anyhow!(
107                        "Destination path {} was outside the project.",
108                        input.destination_path
109                    ))),
110                },
111                None => Task::ready(Err(anyhow!(
112                    "Source path {} was not found in the project.",
113                    input.source_path
114                ))),
115            }
116        });
117
118        cx.background_spawn(async move {
119            match rename_task.await {
120                Ok(_) => {
121                    Ok(format!("Moved {} to {}", input.source_path, input.destination_path).into())
122                }
123                Err(err) => Err(anyhow!(
124                    "Failed to move {} to {}: {}",
125                    input.source_path,
126                    input.destination_path,
127                    err
128                )),
129            }
130        })
131        .into()
132    }
133}