1use anyhow::{Context as _, Result, anyhow};
2use assistant_tool::{ActionLog, Tool};
3use gpui::{App, Entity, Task};
4use language::{self, Buffer, ToPointUtf16};
5use language_model::LanguageModelRequestMessage;
6use project::Project;
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use std::sync::Arc;
10use ui::IconName;
11
12use crate::schema::json_schema_for;
13
14#[derive(Debug, Serialize, Deserialize, JsonSchema)]
15pub struct RenameToolInput {
16 /// The relative path to the file containing the symbol to rename.
17 ///
18 /// WARNING: you MUST start this path with one of the project's root directories.
19 pub path: String,
20
21 /// The new name to give to the symbol.
22 pub new_name: String,
23
24 /// The text that comes immediately before the symbol in the file.
25 pub context_before_symbol: String,
26
27 /// The symbol to rename. This text must appear in the file right between
28 /// `context_before_symbol` and `context_after_symbol`.
29 ///
30 /// The file must contain exactly one occurrence of `context_before_symbol` followed by
31 /// `symbol` followed by `context_after_symbol`. If the file contains zero occurrences,
32 /// or if it contains more than one occurrence, the tool will fail, so it is absolutely
33 /// critical that you verify ahead of time that the string is unique. You can search
34 /// the file's contents to verify this ahead of time.
35 ///
36 /// To make the string more likely to be unique, include a minimum of 1 line of context
37 /// before the symbol, as well as a minimum of 1 line of context after the symbol.
38 /// If these lines of context are not enough to obtain a string that appears only once
39 /// in the file, then double the number of context lines until the string becomes unique.
40 /// (Start with 1 line before and 1 line after though, because too much context is
41 /// needlessly costly.)
42 ///
43 /// Do not alter the context lines of code in any way, and make sure to preserve all
44 /// whitespace and indentation for all lines of code. The combined string must be exactly
45 /// as it appears in the file, or else this tool call will fail.
46 pub symbol: String,
47
48 /// The text that comes immediately after the symbol in the file.
49 pub context_after_symbol: String,
50}
51
52pub struct RenameTool;
53
54impl Tool for RenameTool {
55 fn name(&self) -> String {
56 "rename".into()
57 }
58
59 fn needs_confirmation(&self, _input: &serde_json::Value, _cx: &App) -> bool {
60 false
61 }
62
63 fn description(&self) -> String {
64 include_str!("./rename_tool/description.md").into()
65 }
66
67 fn icon(&self) -> IconName {
68 IconName::Pencil
69 }
70
71 fn input_schema(
72 &self,
73 format: language_model::LanguageModelToolSchemaFormat,
74 ) -> serde_json::Value {
75 json_schema_for::<RenameToolInput>(format)
76 }
77
78 fn ui_text(&self, input: &serde_json::Value) -> String {
79 match serde_json::from_value::<RenameToolInput>(input.clone()) {
80 Ok(input) => {
81 format!("Rename '{}' to '{}'", input.symbol, input.new_name)
82 }
83 Err(_) => "Rename symbol".to_string(),
84 }
85 }
86
87 fn run(
88 self: Arc<Self>,
89 input: serde_json::Value,
90 _messages: &[LanguageModelRequestMessage],
91 project: Entity<Project>,
92 action_log: Entity<ActionLog>,
93 cx: &mut App,
94 ) -> Task<Result<String>> {
95 let input = match serde_json::from_value::<RenameToolInput>(input) {
96 Ok(input) => input,
97 Err(err) => return Task::ready(Err(anyhow!(err))),
98 };
99
100 cx.spawn(async move |cx| {
101 let buffer = {
102 let project_path = project.read_with(cx, |project, cx| {
103 project
104 .find_project_path(&input.path, cx)
105 .context("Path not found in project")
106 })??;
107
108 project.update(cx, |project, cx| project.open_buffer(project_path, cx))?.await?
109 };
110
111 action_log.update(cx, |action_log, cx| {
112 action_log.buffer_read(buffer.clone(), cx);
113 })?;
114
115 let position = {
116 let Some(position) = buffer.read_with(cx, |buffer, _cx| {
117 find_symbol_position(&buffer, &input.context_before_symbol, &input.symbol, &input.context_after_symbol)
118 })? else {
119 return Err(anyhow!(
120 "Failed to locate the symbol specified by context_before_symbol, symbol, and context_after_symbol. Make sure context_before_symbol and context_after_symbol each match exactly once in the file."
121 ));
122 };
123
124 buffer.read_with(cx, |buffer, _| {
125 position.to_point_utf16(&buffer.snapshot())
126 })?
127 };
128
129 project
130 .update(cx, |project, cx| {
131 project.perform_rename(buffer.clone(), position, input.new_name.clone(), cx)
132 })?
133 .await?;
134
135 project
136 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
137 .await?;
138
139 action_log.update(cx, |log, cx| {
140 log.buffer_edited(buffer.clone(), cx)
141 })?;
142
143 Ok(format!("Renamed '{}' to '{}'", input.symbol, input.new_name))
144 })
145 }
146}
147
148/// Finds the position of the symbol in the buffer, if it appears between context_before_symbol
149/// and context_after_symbol, and if that combined string has one unique result in the buffer.
150///
151/// If an exact match fails, it tries adding a newline to the end of context_before_symbol and
152/// to the beginning of context_after_symbol to accommodate line-based context matching.
153fn find_symbol_position(
154 buffer: &Buffer,
155 context_before_symbol: &str,
156 symbol: &str,
157 context_after_symbol: &str,
158) -> Option<language::Anchor> {
159 let snapshot = buffer.snapshot();
160 let text = snapshot.text();
161
162 // First try with exact match
163 let search_string = format!("{context_before_symbol}{symbol}{context_after_symbol}");
164 let mut positions = text.match_indices(&search_string);
165 let position_result = positions.next();
166
167 if let Some(position) = position_result {
168 // Check if the matched string is unique
169 if positions.next().is_none() {
170 let symbol_start = position.0 + context_before_symbol.len();
171 let symbol_start_anchor =
172 snapshot.anchor_before(snapshot.offset_to_point(symbol_start));
173
174 return Some(symbol_start_anchor);
175 }
176 }
177
178 // If exact match fails or is not unique, try with line-based context
179 // Add a newline to the end of before context and beginning of after context
180 let line_based_before = if context_before_symbol.ends_with('\n') {
181 context_before_symbol.to_string()
182 } else {
183 format!("{context_before_symbol}\n")
184 };
185
186 let line_based_after = if context_after_symbol.starts_with('\n') {
187 context_after_symbol.to_string()
188 } else {
189 format!("\n{context_after_symbol}")
190 };
191
192 let line_search_string = format!("{line_based_before}{symbol}{line_based_after}");
193 let mut line_positions = text.match_indices(&line_search_string);
194 let line_position = line_positions.next()?;
195
196 // The line-based search string must also appear exactly once
197 if line_positions.next().is_some() {
198 return None;
199 }
200
201 let line_symbol_start = line_position.0 + line_based_before.len();
202 let line_symbol_start_anchor =
203 snapshot.anchor_before(snapshot.offset_to_point(line_symbol_start));
204
205 Some(line_symbol_start_anchor)
206}