file_command.rs

  1use super::{diagnostics_command::write_single_file_diagnostics, SlashCommand, SlashCommandOutput};
  2use anyhow::{anyhow, Result};
  3use assistant_slash_command::{ArgumentCompletion, SlashCommandOutputSection};
  4use fuzzy::PathMatch;
  5use gpui::{AppContext, Model, Task, View, WeakView};
  6use language::{BufferSnapshot, CodeLabel, HighlightId, LineEnding, LspAdapterDelegate};
  7use project::{PathMatchCandidateSet, Project};
  8use std::{
  9    fmt::Write,
 10    ops::Range,
 11    path::{Path, PathBuf},
 12    sync::{atomic::AtomicBool, Arc},
 13};
 14use ui::prelude::*;
 15use util::{paths::PathMatcher, ResultExt};
 16use workspace::Workspace;
 17
 18pub(crate) struct FileSlashCommand;
 19
 20impl FileSlashCommand {
 21    fn search_paths(
 22        &self,
 23        query: String,
 24        cancellation_flag: Arc<AtomicBool>,
 25        workspace: &View<Workspace>,
 26        cx: &mut AppContext,
 27    ) -> Task<Vec<PathMatch>> {
 28        if query.is_empty() {
 29            let workspace = workspace.read(cx);
 30            let project = workspace.project().read(cx);
 31            let entries = workspace.recent_navigation_history(Some(10), cx);
 32
 33            let entries = entries
 34                .into_iter()
 35                .map(|entries| (entries.0, false))
 36                .chain(project.worktrees(cx).flat_map(|worktree| {
 37                    let worktree = worktree.read(cx);
 38                    let id = worktree.id();
 39                    worktree.child_entries(Path::new("")).map(move |entry| {
 40                        (
 41                            project::ProjectPath {
 42                                worktree_id: id,
 43                                path: entry.path.clone(),
 44                            },
 45                            entry.kind.is_dir(),
 46                        )
 47                    })
 48                }))
 49                .collect::<Vec<_>>();
 50
 51            let path_prefix: Arc<str> = Arc::default();
 52            Task::ready(
 53                entries
 54                    .into_iter()
 55                    .filter_map(|(entry, is_dir)| {
 56                        let worktree = project.worktree_for_id(entry.worktree_id, cx)?;
 57                        let mut full_path = PathBuf::from(worktree.read(cx).root_name());
 58                        full_path.push(&entry.path);
 59                        Some(PathMatch {
 60                            score: 0.,
 61                            positions: Vec::new(),
 62                            worktree_id: entry.worktree_id.to_usize(),
 63                            path: full_path.into(),
 64                            path_prefix: path_prefix.clone(),
 65                            distance_to_relative_ancestor: 0,
 66                            is_dir,
 67                        })
 68                    })
 69                    .collect(),
 70            )
 71        } else {
 72            let worktrees = workspace.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 73            let candidate_sets = worktrees
 74                .into_iter()
 75                .map(|worktree| {
 76                    let worktree = worktree.read(cx);
 77
 78                    PathMatchCandidateSet {
 79                        snapshot: worktree.snapshot(),
 80                        include_ignored: worktree
 81                            .root_entry()
 82                            .map_or(false, |entry| entry.is_ignored),
 83                        include_root_name: true,
 84                        candidates: project::Candidates::Entries,
 85                    }
 86                })
 87                .collect::<Vec<_>>();
 88
 89            let executor = cx.background_executor().clone();
 90            cx.foreground_executor().spawn(async move {
 91                fuzzy::match_path_sets(
 92                    candidate_sets.as_slice(),
 93                    query.as_str(),
 94                    None,
 95                    false,
 96                    100,
 97                    &cancellation_flag,
 98                    executor,
 99                )
100                .await
101            })
102        }
103    }
104}
105
106impl SlashCommand for FileSlashCommand {
107    fn name(&self) -> String {
108        "file".into()
109    }
110
111    fn description(&self) -> String {
112        "insert file".into()
113    }
114
115    fn menu_text(&self) -> String {
116        "Insert File".into()
117    }
118
119    fn requires_argument(&self) -> bool {
120        true
121    }
122
123    fn complete_argument(
124        self: Arc<Self>,
125        query: String,
126        cancellation_flag: Arc<AtomicBool>,
127        workspace: Option<WeakView<Workspace>>,
128        cx: &mut WindowContext,
129    ) -> Task<Result<Vec<ArgumentCompletion>>> {
130        let Some(workspace) = workspace.and_then(|workspace| workspace.upgrade()) else {
131            return Task::ready(Err(anyhow!("workspace was dropped")));
132        };
133
134        let paths = self.search_paths(query, cancellation_flag, &workspace, cx);
135        let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
136        cx.background_executor().spawn(async move {
137            Ok(paths
138                .await
139                .into_iter()
140                .filter_map(|path_match| {
141                    let text = format!(
142                        "{}{}",
143                        path_match.path_prefix,
144                        path_match.path.to_string_lossy()
145                    );
146
147                    let mut label = CodeLabel::default();
148                    let file_name = path_match.path.file_name()?.to_string_lossy();
149                    let label_text = if path_match.is_dir {
150                        format!("{}/ ", file_name)
151                    } else {
152                        format!("{} ", file_name)
153                    };
154
155                    label.push_str(label_text.as_str(), None);
156                    label.push_str(&text, comment_id);
157                    label.filter_range = 0..file_name.len();
158
159                    Some(ArgumentCompletion {
160                        label,
161                        new_text: text,
162                        run_command: true,
163                    })
164                })
165                .collect())
166        })
167    }
168
169    fn run(
170        self: Arc<Self>,
171        argument: Option<&str>,
172        workspace: WeakView<Workspace>,
173        _delegate: Option<Arc<dyn LspAdapterDelegate>>,
174        cx: &mut WindowContext,
175    ) -> Task<Result<SlashCommandOutput>> {
176        let Some(workspace) = workspace.upgrade() else {
177            return Task::ready(Err(anyhow!("workspace was dropped")));
178        };
179
180        let Some(argument) = argument else {
181            return Task::ready(Err(anyhow!("missing path")));
182        };
183
184        let task = collect_files(workspace.read(cx).project().clone(), argument, cx);
185
186        cx.foreground_executor().spawn(async move {
187            let (text, ranges) = task.await?;
188            Ok(SlashCommandOutput {
189                text,
190                sections: ranges
191                    .into_iter()
192                    .map(|(range, path, entry_type)| {
193                        build_entry_output_section(
194                            range,
195                            Some(&path),
196                            entry_type == EntryType::Directory,
197                            None,
198                        )
199                    })
200                    .collect(),
201                run_commands_in_text: true,
202            })
203        })
204    }
205}
206
207#[derive(Clone, Copy, PartialEq)]
208enum EntryType {
209    File,
210    Directory,
211}
212
213fn collect_files(
214    project: Model<Project>,
215    glob_input: &str,
216    cx: &mut AppContext,
217) -> Task<Result<(String, Vec<(Range<usize>, PathBuf, EntryType)>)>> {
218    let Ok(matcher) = PathMatcher::new(&[glob_input.to_owned()]) else {
219        return Task::ready(Err(anyhow!("invalid path")));
220    };
221
222    let project_handle = project.downgrade();
223    let snapshots = project
224        .read(cx)
225        .worktrees(cx)
226        .map(|worktree| worktree.read(cx).snapshot())
227        .collect::<Vec<_>>();
228    cx.spawn(|mut cx| async move {
229        let mut text = String::new();
230        let mut ranges = Vec::new();
231        for snapshot in snapshots {
232            let worktree_id = snapshot.id();
233            let mut directory_stack: Vec<(Arc<Path>, String, usize)> = Vec::new();
234            let mut folded_directory_names_stack = Vec::new();
235            let mut is_top_level_directory = true;
236            for entry in snapshot.entries(false, 0) {
237                let mut path_including_worktree_name = PathBuf::new();
238                path_including_worktree_name.push(snapshot.root_name());
239                path_including_worktree_name.push(&entry.path);
240                if !matcher.is_match(&path_including_worktree_name) {
241                    continue;
242                }
243
244                while let Some((dir, _, _)) = directory_stack.last() {
245                    if entry.path.starts_with(dir) {
246                        break;
247                    }
248                    let (_, entry_name, start) = directory_stack.pop().unwrap();
249                    ranges.push((
250                        start..text.len().saturating_sub(1),
251                        PathBuf::from(entry_name),
252                        EntryType::Directory,
253                    ));
254                }
255
256                let filename = entry
257                    .path
258                    .file_name()
259                    .unwrap_or_default()
260                    .to_str()
261                    .unwrap_or_default()
262                    .to_string();
263
264                if entry.is_dir() {
265                    // Auto-fold directories that contain no files
266                    let mut child_entries = snapshot.child_entries(&entry.path);
267                    if let Some(child) = child_entries.next() {
268                        if child_entries.next().is_none() && child.kind.is_dir() {
269                            if is_top_level_directory {
270                                is_top_level_directory = false;
271                                folded_directory_names_stack.push(
272                                    path_including_worktree_name.to_string_lossy().to_string(),
273                                );
274                            } else {
275                                folded_directory_names_stack.push(filename.to_string());
276                            }
277                            continue;
278                        }
279                    } else {
280                        // Skip empty directories
281                        folded_directory_names_stack.clear();
282                        continue;
283                    }
284                    let prefix_paths = folded_directory_names_stack.drain(..).as_slice().join("/");
285                    let entry_start = text.len();
286                    if prefix_paths.is_empty() {
287                        if is_top_level_directory {
288                            text.push_str(&path_including_worktree_name.to_string_lossy());
289                            is_top_level_directory = false;
290                        } else {
291                            text.push_str(&filename);
292                        }
293                        directory_stack.push((entry.path.clone(), filename, entry_start));
294                    } else {
295                        let entry_name = format!("{}/{}", prefix_paths, &filename);
296                        text.push_str(&entry_name);
297                        directory_stack.push((entry.path.clone(), entry_name, entry_start));
298                    }
299                    text.push('\n');
300                } else if entry.is_file() {
301                    let Some(open_buffer_task) = project_handle
302                        .update(&mut cx, |project, cx| {
303                            project.open_buffer((worktree_id, &entry.path), cx)
304                        })
305                        .ok()
306                    else {
307                        continue;
308                    };
309                    if let Some(buffer) = open_buffer_task.await.log_err() {
310                        let buffer_snapshot =
311                            cx.read_model(&buffer, |buffer, _| buffer.snapshot())?;
312                        let prev_len = text.len();
313                        collect_file_content(
314                            &mut text,
315                            &buffer_snapshot,
316                            path_including_worktree_name.to_string_lossy().to_string(),
317                        );
318                        text.push('\n');
319                        if !write_single_file_diagnostics(
320                            &mut text,
321                            Some(&path_including_worktree_name),
322                            &buffer_snapshot,
323                        ) {
324                            text.pop();
325                        }
326                        ranges.push((
327                            prev_len..text.len(),
328                            path_including_worktree_name,
329                            EntryType::File,
330                        ));
331                        text.push('\n');
332                    }
333                }
334            }
335
336            while let Some((dir, _, start)) = directory_stack.pop() {
337                let mut root_path = PathBuf::new();
338                root_path.push(snapshot.root_name());
339                root_path.push(&dir);
340                ranges.push((start..text.len(), root_path, EntryType::Directory));
341            }
342        }
343        Ok((text, ranges))
344    })
345}
346
347fn collect_file_content(buffer: &mut String, snapshot: &BufferSnapshot, filename: String) {
348    let mut content = snapshot.text();
349    LineEnding::normalize(&mut content);
350    buffer.reserve(filename.len() + content.len() + 9);
351    buffer.push_str(&codeblock_fence_for_path(
352        Some(&PathBuf::from(filename)),
353        None,
354    ));
355    buffer.push_str(&content);
356    if !buffer.ends_with('\n') {
357        buffer.push('\n');
358    }
359    buffer.push_str("```");
360}
361
362pub fn codeblock_fence_for_path(path: Option<&Path>, row_range: Option<Range<u32>>) -> String {
363    let mut text = String::new();
364    write!(text, "```").unwrap();
365
366    if let Some(path) = path {
367        if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
368            write!(text, "{} ", extension).unwrap();
369        }
370
371        write!(text, "{}", path.display()).unwrap();
372    } else {
373        write!(text, "untitled").unwrap();
374    }
375
376    if let Some(row_range) = row_range {
377        write!(text, ":{}-{}", row_range.start + 1, row_range.end + 1).unwrap();
378    }
379
380    text.push('\n');
381    text
382}
383
384pub fn build_entry_output_section(
385    range: Range<usize>,
386    path: Option<&Path>,
387    is_directory: bool,
388    line_range: Option<Range<u32>>,
389) -> SlashCommandOutputSection<usize> {
390    let mut label = if let Some(path) = path {
391        path.to_string_lossy().to_string()
392    } else {
393        "untitled".to_string()
394    };
395    if let Some(line_range) = line_range {
396        write!(label, ":{}-{}", line_range.start, line_range.end).unwrap();
397    }
398
399    let icon = if is_directory {
400        IconName::Folder
401    } else {
402        IconName::File
403    };
404
405    SlashCommandOutputSection {
406        range,
407        icon,
408        label: label.into(),
409    }
410}