move_path_tool.rs

  1use anyhow::{anyhow, Result};
  2use assistant_tool::{ActionLog, Tool};
  3use gpui::{App, AppContext, Entity, Task};
  4use language_model::LanguageModelRequestMessage;
  5use project::Project;
  6use schemars::JsonSchema;
  7use serde::{Deserialize, Serialize};
  8use std::{path::Path, sync::Arc};
  9use ui::IconName;
 10use util::markdown::MarkdownString;
 11
 12#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 13pub struct MovePathToolInput {
 14    /// The source path of the file or directory to move/rename.
 15    ///
 16    /// <example>
 17    /// If the project has the following files:
 18    ///
 19    /// - directory1/a/something.txt
 20    /// - directory2/a/things.txt
 21    /// - directory3/a/other.txt
 22    ///
 23    /// You can move the first file by providing a source_path of "directory1/a/something.txt"
 24    /// </example>
 25    pub source_path: String,
 26
 27    /// The destination path where the file or directory should be moved/renamed to.
 28    /// If the paths are the same except for the filename, then this will be a rename.
 29    ///
 30    /// <example>
 31    /// To move "directory1/a/something.txt" to "directory2/b/renamed.txt",
 32    /// provide a destination_path of "directory2/b/renamed.txt"
 33    /// </example>
 34    pub destination_path: String,
 35}
 36
 37pub struct MovePathTool;
 38
 39impl Tool for MovePathTool {
 40    fn name(&self) -> String {
 41        "move-path".into()
 42    }
 43
 44    fn needs_confirmation(&self) -> bool {
 45        true
 46    }
 47
 48    fn description(&self) -> String {
 49        include_str!("./move_path_tool/description.md").into()
 50    }
 51
 52    fn icon(&self) -> IconName {
 53        IconName::ArrowRightLeft
 54    }
 55
 56    fn input_schema(&self) -> serde_json::Value {
 57        let schema = schemars::schema_for!(MovePathToolInput);
 58        serde_json::to_value(&schema).unwrap()
 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 = MarkdownString::inline_code(&input.source_path);
 65                let dest = MarkdownString::inline_code(&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 = MarkdownString::inline_code(&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        cx: &mut App,
 93    ) -> Task<Result<String>> {
 94        let input = match serde_json::from_value::<MovePathToolInput>(input) {
 95            Ok(input) => input,
 96            Err(err) => return Task::ready(Err(anyhow!(err))),
 97        };
 98        let rename_task = project.update(cx, |project, cx| {
 99            match project
100                .find_project_path(&input.source_path, cx)
101                .and_then(|project_path| project.entry_for_path(&project_path, cx))
102            {
103                Some(entity) => match project.find_project_path(&input.destination_path, cx) {
104                    Some(project_path) => project.rename_entry(entity.id, project_path.path, cx),
105                    None => Task::ready(Err(anyhow!(
106                        "Destination path {} was outside the project.",
107                        input.destination_path
108                    ))),
109                },
110                None => Task::ready(Err(anyhow!(
111                    "Source path {} was not found in the project.",
112                    input.source_path
113                ))),
114            }
115        });
116
117        cx.background_spawn(async move {
118            match rename_task.await {
119                Ok(_) => Ok(format!(
120                    "Moved {} to {}",
121                    input.source_path, input.destination_path
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    }
132}