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        arguments: &[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(
135            arguments.last().cloned().unwrap_or_default(),
136            cancellation_flag,
137            &workspace,
138            cx,
139        );
140        let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
141        cx.background_executor().spawn(async move {
142            Ok(paths
143                .await
144                .into_iter()
145                .filter_map(|path_match| {
146                    let text = format!(
147                        "{}{}",
148                        path_match.path_prefix,
149                        path_match.path.to_string_lossy()
150                    );
151
152                    let mut label = CodeLabel::default();
153                    let file_name = path_match.path.file_name()?.to_string_lossy();
154                    let label_text = if path_match.is_dir {
155                        format!("{}/ ", file_name)
156                    } else {
157                        format!("{} ", file_name)
158                    };
159
160                    label.push_str(label_text.as_str(), None);
161                    label.push_str(&text, comment_id);
162                    label.filter_range = 0..file_name.len();
163
164                    Some(ArgumentCompletion {
165                        label,
166                        new_text: text,
167                        run_command: true,
168                    })
169                })
170                .collect())
171        })
172    }
173
174    fn run(
175        self: Arc<Self>,
176        arguments: &[String],
177        workspace: WeakView<Workspace>,
178        _delegate: Option<Arc<dyn LspAdapterDelegate>>,
179        cx: &mut WindowContext,
180    ) -> Task<Result<SlashCommandOutput>> {
181        let Some(workspace) = workspace.upgrade() else {
182            return Task::ready(Err(anyhow!("workspace was dropped")));
183        };
184
185        let Some(argument) = arguments.first() else {
186            return Task::ready(Err(anyhow!("missing path")));
187        };
188
189        let task = collect_files(workspace.read(cx).project().clone(), argument, cx);
190
191        cx.foreground_executor().spawn(async move {
192            let (text, ranges) = task.await?;
193            Ok(SlashCommandOutput {
194                text,
195                sections: ranges
196                    .into_iter()
197                    .map(|(range, path, entry_type)| {
198                        build_entry_output_section(
199                            range,
200                            Some(&path),
201                            entry_type == EntryType::Directory,
202                            None,
203                        )
204                    })
205                    .collect(),
206                run_commands_in_text: true,
207            })
208        })
209    }
210}
211
212#[derive(Clone, Copy, PartialEq)]
213enum EntryType {
214    File,
215    Directory,
216}
217
218fn collect_files(
219    project: Model<Project>,
220    glob_input: &str,
221    cx: &mut AppContext,
222) -> Task<Result<(String, Vec<(Range<usize>, PathBuf, EntryType)>)>> {
223    let Ok(matcher) = PathMatcher::new(&[glob_input.to_owned()]) else {
224        return Task::ready(Err(anyhow!("invalid path")));
225    };
226
227    let project_handle = project.downgrade();
228    let snapshots = project
229        .read(cx)
230        .worktrees(cx)
231        .map(|worktree| worktree.read(cx).snapshot())
232        .collect::<Vec<_>>();
233    cx.spawn(|mut cx| async move {
234        let mut text = String::new();
235        let mut ranges = Vec::new();
236        for snapshot in snapshots {
237            let worktree_id = snapshot.id();
238            let mut directory_stack: Vec<(Arc<Path>, String, usize)> = Vec::new();
239            let mut folded_directory_names_stack = Vec::new();
240            let mut is_top_level_directory = true;
241            for entry in snapshot.entries(false, 0) {
242                let mut path_including_worktree_name = PathBuf::new();
243                path_including_worktree_name.push(snapshot.root_name());
244                path_including_worktree_name.push(&entry.path);
245                if !matcher.is_match(&path_including_worktree_name) {
246                    continue;
247                }
248
249                while let Some((dir, _, _)) = directory_stack.last() {
250                    if entry.path.starts_with(dir) {
251                        break;
252                    }
253                    let (_, entry_name, start) = directory_stack.pop().unwrap();
254                    ranges.push((
255                        start..text.len().saturating_sub(1),
256                        PathBuf::from(entry_name),
257                        EntryType::Directory,
258                    ));
259                }
260
261                let filename = entry
262                    .path
263                    .file_name()
264                    .unwrap_or_default()
265                    .to_str()
266                    .unwrap_or_default()
267                    .to_string();
268
269                if entry.is_dir() {
270                    // Auto-fold directories that contain no files
271                    let mut child_entries = snapshot.child_entries(&entry.path);
272                    if let Some(child) = child_entries.next() {
273                        if child_entries.next().is_none() && child.kind.is_dir() {
274                            if is_top_level_directory {
275                                is_top_level_directory = false;
276                                folded_directory_names_stack.push(
277                                    path_including_worktree_name.to_string_lossy().to_string(),
278                                );
279                            } else {
280                                folded_directory_names_stack.push(filename.to_string());
281                            }
282                            continue;
283                        }
284                    } else {
285                        // Skip empty directories
286                        folded_directory_names_stack.clear();
287                        continue;
288                    }
289                    let prefix_paths = folded_directory_names_stack.drain(..).as_slice().join("/");
290                    let entry_start = text.len();
291                    if prefix_paths.is_empty() {
292                        if is_top_level_directory {
293                            text.push_str(&path_including_worktree_name.to_string_lossy());
294                            is_top_level_directory = false;
295                        } else {
296                            text.push_str(&filename);
297                        }
298                        directory_stack.push((entry.path.clone(), filename, entry_start));
299                    } else {
300                        let entry_name = format!("{}/{}", prefix_paths, &filename);
301                        text.push_str(&entry_name);
302                        directory_stack.push((entry.path.clone(), entry_name, entry_start));
303                    }
304                    text.push('\n');
305                } else if entry.is_file() {
306                    let Some(open_buffer_task) = project_handle
307                        .update(&mut cx, |project, cx| {
308                            project.open_buffer((worktree_id, &entry.path), cx)
309                        })
310                        .ok()
311                    else {
312                        continue;
313                    };
314                    if let Some(buffer) = open_buffer_task.await.log_err() {
315                        let buffer_snapshot =
316                            cx.read_model(&buffer, |buffer, _| buffer.snapshot())?;
317                        let prev_len = text.len();
318                        collect_file_content(
319                            &mut text,
320                            &buffer_snapshot,
321                            path_including_worktree_name.to_string_lossy().to_string(),
322                        );
323                        text.push('\n');
324                        if !write_single_file_diagnostics(
325                            &mut text,
326                            Some(&path_including_worktree_name),
327                            &buffer_snapshot,
328                        ) {
329                            text.pop();
330                        }
331                        ranges.push((
332                            prev_len..text.len(),
333                            path_including_worktree_name,
334                            EntryType::File,
335                        ));
336                        text.push('\n');
337                    }
338                }
339            }
340
341            while let Some((dir, _, start)) = directory_stack.pop() {
342                let mut root_path = PathBuf::new();
343                root_path.push(snapshot.root_name());
344                root_path.push(&dir);
345                ranges.push((start..text.len(), root_path, EntryType::Directory));
346            }
347        }
348        Ok((text, ranges))
349    })
350}
351
352fn collect_file_content(buffer: &mut String, snapshot: &BufferSnapshot, filename: String) {
353    let mut content = snapshot.text();
354    LineEnding::normalize(&mut content);
355    buffer.reserve(filename.len() + content.len() + 9);
356    buffer.push_str(&codeblock_fence_for_path(
357        Some(&PathBuf::from(filename)),
358        None,
359    ));
360    buffer.push_str(&content);
361    if !buffer.ends_with('\n') {
362        buffer.push('\n');
363    }
364    buffer.push_str("```");
365}
366
367pub fn codeblock_fence_for_path(path: Option<&Path>, row_range: Option<Range<u32>>) -> String {
368    let mut text = String::new();
369    write!(text, "```").unwrap();
370
371    if let Some(path) = path {
372        if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
373            write!(text, "{} ", extension).unwrap();
374        }
375
376        write!(text, "{}", path.display()).unwrap();
377    } else {
378        write!(text, "untitled").unwrap();
379    }
380
381    if let Some(row_range) = row_range {
382        write!(text, ":{}-{}", row_range.start + 1, row_range.end + 1).unwrap();
383    }
384
385    text.push('\n');
386    text
387}
388
389pub fn build_entry_output_section(
390    range: Range<usize>,
391    path: Option<&Path>,
392    is_directory: bool,
393    line_range: Option<Range<u32>>,
394) -> SlashCommandOutputSection<usize> {
395    let mut label = if let Some(path) = path {
396        path.to_string_lossy().to_string()
397    } else {
398        "untitled".to_string()
399    };
400    if let Some(line_range) = line_range {
401        write!(label, ":{}-{}", line_range.start, line_range.end).unwrap();
402    }
403
404    let icon = if is_directory {
405        IconName::Folder
406    } else {
407        IconName::File
408    };
409
410    SlashCommandOutputSection {
411        range,
412        icon,
413        label: label.into(),
414    }
415}