file_command.rs

  1use super::{diagnostics_command::write_single_file_diagnostics, SlashCommand, SlashCommandOutput};
  2use anyhow::{anyhow, Context as _, 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: false,
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        if arguments.is_empty() {
186            return Task::ready(Err(anyhow!("missing path")));
187        };
188
189        let task = collect_files(workspace.read(cx).project().clone(), arguments, 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_inputs: &[String],
221    cx: &mut AppContext,
222) -> Task<Result<(String, Vec<(Range<usize>, PathBuf, EntryType)>)>> {
223    let Ok(matchers) = glob_inputs
224        .into_iter()
225        .map(|glob_input| {
226            PathMatcher::new(&[glob_input.to_owned()])
227                .with_context(|| format!("invalid path {glob_input}"))
228        })
229        .collect::<anyhow::Result<Vec<PathMatcher>>>()
230    else {
231        return Task::ready(Err(anyhow!("invalid path")));
232    };
233
234    let project_handle = project.downgrade();
235    let snapshots = project
236        .read(cx)
237        .worktrees(cx)
238        .map(|worktree| worktree.read(cx).snapshot())
239        .collect::<Vec<_>>();
240    cx.spawn(|mut cx| async move {
241        let mut text = String::new();
242        let mut ranges = Vec::new();
243        for snapshot in snapshots {
244            let worktree_id = snapshot.id();
245            let mut directory_stack: Vec<(Arc<Path>, String, usize)> = Vec::new();
246            let mut folded_directory_names_stack = Vec::new();
247            let mut is_top_level_directory = true;
248            for entry in snapshot.entries(false, 0) {
249                let mut path_including_worktree_name = PathBuf::new();
250                path_including_worktree_name.push(snapshot.root_name());
251                path_including_worktree_name.push(&entry.path);
252                if !matchers
253                    .iter()
254                    .any(|matcher| matcher.is_match(&path_including_worktree_name))
255                {
256                    continue;
257                }
258
259                while let Some((dir, _, _)) = directory_stack.last() {
260                    if entry.path.starts_with(dir) {
261                        break;
262                    }
263                    let (_, entry_name, start) = directory_stack.pop().unwrap();
264                    ranges.push((
265                        start..text.len().saturating_sub(1),
266                        PathBuf::from(entry_name),
267                        EntryType::Directory,
268                    ));
269                }
270
271                let filename = entry
272                    .path
273                    .file_name()
274                    .unwrap_or_default()
275                    .to_str()
276                    .unwrap_or_default()
277                    .to_string();
278
279                if entry.is_dir() {
280                    // Auto-fold directories that contain no files
281                    let mut child_entries = snapshot.child_entries(&entry.path);
282                    if let Some(child) = child_entries.next() {
283                        if child_entries.next().is_none() && child.kind.is_dir() {
284                            if is_top_level_directory {
285                                is_top_level_directory = false;
286                                folded_directory_names_stack.push(
287                                    path_including_worktree_name.to_string_lossy().to_string(),
288                                );
289                            } else {
290                                folded_directory_names_stack.push(filename.to_string());
291                            }
292                            continue;
293                        }
294                    } else {
295                        // Skip empty directories
296                        folded_directory_names_stack.clear();
297                        continue;
298                    }
299                    let prefix_paths = folded_directory_names_stack.drain(..).as_slice().join("/");
300                    let entry_start = text.len();
301                    if prefix_paths.is_empty() {
302                        if is_top_level_directory {
303                            text.push_str(&path_including_worktree_name.to_string_lossy());
304                            is_top_level_directory = false;
305                        } else {
306                            text.push_str(&filename);
307                        }
308                        directory_stack.push((entry.path.clone(), filename, entry_start));
309                    } else {
310                        let entry_name = format!("{}/{}", prefix_paths, &filename);
311                        text.push_str(&entry_name);
312                        directory_stack.push((entry.path.clone(), entry_name, entry_start));
313                    }
314                    text.push('\n');
315                } else if entry.is_file() {
316                    let Some(open_buffer_task) = project_handle
317                        .update(&mut cx, |project, cx| {
318                            project.open_buffer((worktree_id, &entry.path), cx)
319                        })
320                        .ok()
321                    else {
322                        continue;
323                    };
324                    if let Some(buffer) = open_buffer_task.await.log_err() {
325                        let buffer_snapshot =
326                            cx.read_model(&buffer, |buffer, _| buffer.snapshot())?;
327                        let prev_len = text.len();
328                        collect_file_content(
329                            &mut text,
330                            &buffer_snapshot,
331                            path_including_worktree_name.to_string_lossy().to_string(),
332                        );
333                        text.push('\n');
334                        if !write_single_file_diagnostics(
335                            &mut text,
336                            Some(&path_including_worktree_name),
337                            &buffer_snapshot,
338                        ) {
339                            text.pop();
340                        }
341                        ranges.push((
342                            prev_len..text.len(),
343                            path_including_worktree_name,
344                            EntryType::File,
345                        ));
346                        text.push('\n');
347                    }
348                }
349            }
350
351            while let Some((dir, _, start)) = directory_stack.pop() {
352                let mut root_path = PathBuf::new();
353                root_path.push(snapshot.root_name());
354                root_path.push(&dir);
355                ranges.push((start..text.len(), root_path, EntryType::Directory));
356            }
357        }
358        Ok((text, ranges))
359    })
360}
361
362fn collect_file_content(buffer: &mut String, snapshot: &BufferSnapshot, filename: String) {
363    let mut content = snapshot.text();
364    LineEnding::normalize(&mut content);
365    buffer.reserve(filename.len() + content.len() + 9);
366    buffer.push_str(&codeblock_fence_for_path(
367        Some(&PathBuf::from(filename)),
368        None,
369    ));
370    buffer.push_str(&content);
371    if !buffer.ends_with('\n') {
372        buffer.push('\n');
373    }
374    buffer.push_str("```");
375}
376
377pub fn codeblock_fence_for_path(path: Option<&Path>, row_range: Option<Range<u32>>) -> String {
378    let mut text = String::new();
379    write!(text, "```").unwrap();
380
381    if let Some(path) = path {
382        if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
383            write!(text, "{} ", extension).unwrap();
384        }
385
386        write!(text, "{}", path.display()).unwrap();
387    } else {
388        write!(text, "untitled").unwrap();
389    }
390
391    if let Some(row_range) = row_range {
392        write!(text, ":{}-{}", row_range.start + 1, row_range.end + 1).unwrap();
393    }
394
395    text.push('\n');
396    text
397}
398
399pub fn build_entry_output_section(
400    range: Range<usize>,
401    path: Option<&Path>,
402    is_directory: bool,
403    line_range: Option<Range<u32>>,
404) -> SlashCommandOutputSection<usize> {
405    let mut label = if let Some(path) = path {
406        path.to_string_lossy().to_string()
407    } else {
408        "untitled".to_string()
409    };
410    if let Some(line_range) = line_range {
411        write!(label, ":{}-{}", line_range.start, line_range.end).unwrap();
412    }
413
414    let icon = if is_directory {
415        IconName::Folder
416    } else {
417        IconName::File
418    };
419
420    SlashCommandOutputSection {
421        range,
422        icon,
423        label: label.into(),
424    }
425}