file_command.rs

  1use super::{diagnostics_command::write_single_file_diagnostics, SlashCommand, SlashCommandOutput};
  2use anyhow::{anyhow, Context as _, Result};
  3use assistant_slash_command::{AfterCompletion, 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::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                        after_completion: if path_match.is_dir {
168                            AfterCompletion::Compose
169                        } else {
170                            AfterCompletion::Run
171                        },
172                        replace_previous_arguments: false,
173                    })
174                })
175                .collect())
176        })
177    }
178
179    fn run(
180        self: Arc<Self>,
181        arguments: &[String],
182        workspace: WeakView<Workspace>,
183        _delegate: Option<Arc<dyn LspAdapterDelegate>>,
184        cx: &mut WindowContext,
185    ) -> Task<Result<SlashCommandOutput>> {
186        let Some(workspace) = workspace.upgrade() else {
187            return Task::ready(Err(anyhow!("workspace was dropped")));
188        };
189
190        if arguments.is_empty() {
191            return Task::ready(Err(anyhow!("missing path")));
192        };
193
194        let task = collect_files(workspace.read(cx).project().clone(), arguments, cx);
195
196        cx.foreground_executor().spawn(async move {
197            let output = task.await?;
198            Ok(SlashCommandOutput {
199                text: output.completion_text,
200                sections: output
201                    .files
202                    .into_iter()
203                    .map(|file| {
204                        build_entry_output_section(
205                            file.range_in_text,
206                            Some(&file.path),
207                            file.entry_type == EntryType::Directory,
208                            None,
209                        )
210                    })
211                    .collect(),
212                run_commands_in_text: true,
213            })
214        })
215    }
216}
217
218#[derive(Clone, Copy, PartialEq, Debug)]
219enum EntryType {
220    File,
221    Directory,
222}
223
224#[derive(Clone, PartialEq, Debug)]
225struct FileCommandOutput {
226    completion_text: String,
227    files: Vec<OutputFile>,
228}
229
230#[derive(Clone, PartialEq, Debug)]
231struct OutputFile {
232    range_in_text: Range<usize>,
233    path: PathBuf,
234    entry_type: EntryType,
235}
236
237fn collect_files(
238    project: Model<Project>,
239    glob_inputs: &[String],
240    cx: &mut AppContext,
241) -> Task<Result<FileCommandOutput>> {
242    let Ok(matchers) = glob_inputs
243        .into_iter()
244        .map(|glob_input| {
245            custom_path_matcher::PathMatcher::new(&[glob_input.to_owned()])
246                .with_context(|| format!("invalid path {glob_input}"))
247        })
248        .collect::<anyhow::Result<Vec<custom_path_matcher::PathMatcher>>>()
249    else {
250        return Task::ready(Err(anyhow!("invalid path")));
251    };
252
253    let project_handle = project.downgrade();
254    let snapshots = project
255        .read(cx)
256        .worktrees(cx)
257        .map(|worktree| worktree.read(cx).snapshot())
258        .collect::<Vec<_>>();
259
260    cx.spawn(|mut cx| async move {
261        let mut text = String::new();
262        let mut ranges = Vec::new();
263        for snapshot in snapshots {
264            let worktree_id = snapshot.id();
265            let mut directory_stack: Vec<(Arc<Path>, String, usize)> = Vec::new();
266            let mut folded_directory_names_stack = Vec::new();
267            let mut is_top_level_directory = true;
268
269            for entry in snapshot.entries(false, 0) {
270                let mut path_including_worktree_name = PathBuf::new();
271                path_including_worktree_name.push(snapshot.root_name());
272                path_including_worktree_name.push(&entry.path);
273
274                if !matchers
275                    .iter()
276                    .any(|matcher| matcher.is_match(&path_including_worktree_name))
277                {
278                    continue;
279                }
280
281                while let Some((dir, _, _)) = directory_stack.last() {
282                    if entry.path.starts_with(dir) {
283                        break;
284                    }
285                    let (_, entry_name, start) = directory_stack.pop().unwrap();
286                    ranges.push(OutputFile {
287                        range_in_text: start..text.len().saturating_sub(1),
288                        path: PathBuf::from(entry_name),
289                        entry_type: EntryType::Directory,
290                    });
291                }
292
293                let filename = entry
294                    .path
295                    .file_name()
296                    .unwrap_or_default()
297                    .to_str()
298                    .unwrap_or_default()
299                    .to_string();
300
301                if entry.is_dir() {
302                    // Auto-fold directories that contain no files
303                    let mut child_entries = snapshot.child_entries(&entry.path);
304                    if let Some(child) = child_entries.next() {
305                        if child_entries.next().is_none() && child.kind.is_dir() {
306                            if is_top_level_directory {
307                                is_top_level_directory = false;
308                                folded_directory_names_stack.push(
309                                    path_including_worktree_name.to_string_lossy().to_string(),
310                                );
311                            } else {
312                                folded_directory_names_stack.push(filename.to_string());
313                            }
314                            continue;
315                        }
316                    } else {
317                        // Skip empty directories
318                        folded_directory_names_stack.clear();
319                        continue;
320                    }
321                    let prefix_paths = folded_directory_names_stack.drain(..).as_slice().join("/");
322                    let entry_start = text.len();
323                    if prefix_paths.is_empty() {
324                        if is_top_level_directory {
325                            text.push_str(&path_including_worktree_name.to_string_lossy());
326                            is_top_level_directory = false;
327                        } else {
328                            text.push_str(&filename);
329                        }
330                        directory_stack.push((entry.path.clone(), filename, entry_start));
331                    } else {
332                        let entry_name = format!("{}/{}", prefix_paths, &filename);
333                        text.push_str(&entry_name);
334                        directory_stack.push((entry.path.clone(), entry_name, entry_start));
335                    }
336                    text.push('\n');
337                } else if entry.is_file() {
338                    let Some(open_buffer_task) = project_handle
339                        .update(&mut cx, |project, cx| {
340                            project.open_buffer((worktree_id, &entry.path), cx)
341                        })
342                        .ok()
343                    else {
344                        continue;
345                    };
346                    if let Some(buffer) = open_buffer_task.await.log_err() {
347                        let buffer_snapshot =
348                            cx.read_model(&buffer, |buffer, _| buffer.snapshot())?;
349                        let prev_len = text.len();
350                        collect_file_content(
351                            &mut text,
352                            &buffer_snapshot,
353                            path_including_worktree_name.to_string_lossy().to_string(),
354                        );
355                        text.push('\n');
356                        if !write_single_file_diagnostics(
357                            &mut text,
358                            Some(&path_including_worktree_name),
359                            &buffer_snapshot,
360                        ) {
361                            text.pop();
362                        }
363                        ranges.push(OutputFile {
364                            range_in_text: prev_len..text.len(),
365                            path: path_including_worktree_name,
366                            entry_type: EntryType::File,
367                        });
368                        text.push('\n');
369                    }
370                }
371            }
372
373            while let Some((dir, entry, start)) = directory_stack.pop() {
374                if directory_stack.is_empty() {
375                    let mut root_path = PathBuf::new();
376                    root_path.push(snapshot.root_name());
377                    root_path.push(&dir);
378                    ranges.push(OutputFile {
379                        range_in_text: start..text.len(),
380                        path: root_path,
381                        entry_type: EntryType::Directory,
382                    });
383                } else {
384                    ranges.push(OutputFile {
385                        range_in_text: start..text.len(),
386                        path: PathBuf::from(entry.as_str()),
387                        entry_type: EntryType::Directory,
388                    });
389                }
390            }
391        }
392        Ok(FileCommandOutput {
393            completion_text: text,
394            files: ranges,
395        })
396    })
397}
398
399fn collect_file_content(buffer: &mut String, snapshot: &BufferSnapshot, filename: String) {
400    let mut content = snapshot.text();
401    LineEnding::normalize(&mut content);
402    buffer.reserve(filename.len() + content.len() + 9);
403    buffer.push_str(&codeblock_fence_for_path(
404        Some(&PathBuf::from(filename)),
405        None,
406    ));
407    buffer.push_str(&content);
408    if !buffer.ends_with('\n') {
409        buffer.push('\n');
410    }
411    buffer.push_str("```");
412}
413
414pub fn codeblock_fence_for_path(path: Option<&Path>, row_range: Option<Range<u32>>) -> String {
415    let mut text = String::new();
416    write!(text, "```").unwrap();
417
418    if let Some(path) = path {
419        if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
420            write!(text, "{} ", extension).unwrap();
421        }
422
423        write!(text, "{}", path.display()).unwrap();
424    } else {
425        write!(text, "untitled").unwrap();
426    }
427
428    if let Some(row_range) = row_range {
429        write!(text, ":{}-{}", row_range.start + 1, row_range.end + 1).unwrap();
430    }
431
432    text.push('\n');
433    text
434}
435
436pub fn build_entry_output_section(
437    range: Range<usize>,
438    path: Option<&Path>,
439    is_directory: bool,
440    line_range: Option<Range<u32>>,
441) -> SlashCommandOutputSection<usize> {
442    let mut label = if let Some(path) = path {
443        path.to_string_lossy().to_string()
444    } else {
445        "untitled".to_string()
446    };
447    if let Some(line_range) = line_range {
448        write!(label, ":{}-{}", line_range.start, line_range.end).unwrap();
449    }
450
451    let icon = if is_directory {
452        IconName::Folder
453    } else {
454        IconName::File
455    };
456
457    SlashCommandOutputSection {
458        range,
459        icon,
460        label: label.into(),
461    }
462}
463
464/// This contains a small fork of the util::paths::PathMatcher, that is stricter about the prefix
465/// check. Only subpaths pass the prefix check, rather than any prefix.
466mod custom_path_matcher {
467    use std::{fmt::Debug as _, path::Path};
468
469    use globset::{Glob, GlobSet, GlobSetBuilder};
470
471    #[derive(Clone, Debug, Default)]
472    pub struct PathMatcher {
473        sources: Vec<String>,
474        sources_with_trailing_slash: Vec<String>,
475        glob: GlobSet,
476    }
477
478    impl std::fmt::Display for PathMatcher {
479        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480            self.sources.fmt(f)
481        }
482    }
483
484    impl PartialEq for PathMatcher {
485        fn eq(&self, other: &Self) -> bool {
486            self.sources.eq(&other.sources)
487        }
488    }
489
490    impl Eq for PathMatcher {}
491
492    impl PathMatcher {
493        pub fn new(globs: &[String]) -> Result<Self, globset::Error> {
494            let globs = globs
495                .into_iter()
496                .map(|glob| Glob::new(&glob))
497                .collect::<Result<Vec<_>, _>>()?;
498            let sources = globs.iter().map(|glob| glob.glob().to_owned()).collect();
499            let sources_with_trailing_slash = globs
500                .iter()
501                .map(|glob| glob.glob().to_string() + std::path::MAIN_SEPARATOR_STR)
502                .collect();
503            let mut glob_builder = GlobSetBuilder::new();
504            for single_glob in globs {
505                glob_builder.add(single_glob);
506            }
507            let glob = glob_builder.build()?;
508            Ok(PathMatcher {
509                glob,
510                sources,
511                sources_with_trailing_slash,
512            })
513        }
514
515        pub fn is_match<P: AsRef<Path>>(&self, other: P) -> bool {
516            let other_path = other.as_ref();
517            self.sources
518                .iter()
519                .zip(self.sources_with_trailing_slash.iter())
520                .any(|(source, with_slash)| {
521                    let as_bytes = other_path.as_os_str().as_encoded_bytes();
522                    let with_slash = if source.ends_with("/") {
523                        source.as_bytes()
524                    } else {
525                        with_slash.as_bytes()
526                    };
527
528                    as_bytes.starts_with(with_slash) || as_bytes.ends_with(source.as_bytes())
529                })
530                || self.glob.is_match(other_path)
531                || self.check_with_end_separator(other_path)
532        }
533
534        fn check_with_end_separator(&self, path: &Path) -> bool {
535            let path_str = path.to_string_lossy();
536            let separator = std::path::MAIN_SEPARATOR_STR;
537            if path_str.ends_with(separator) {
538                return false;
539            } else {
540                self.glob.is_match(path_str.to_string() + separator)
541            }
542        }
543    }
544}
545
546#[cfg(test)]
547mod test {
548    use fs::FakeFs;
549    use gpui::TestAppContext;
550    use project::Project;
551    use serde_json::json;
552    use settings::SettingsStore;
553
554    use crate::slash_command::file_command::collect_files;
555
556    pub fn init_test(cx: &mut gpui::TestAppContext) {
557        if std::env::var("RUST_LOG").is_ok() {
558            env_logger::try_init().ok();
559        }
560
561        cx.update(|cx| {
562            let settings_store = SettingsStore::test(cx);
563            cx.set_global(settings_store);
564            // release_channel::init(SemanticVersion::default(), cx);
565            language::init(cx);
566            Project::init_settings(cx);
567        });
568    }
569
570    #[gpui::test]
571    async fn test_file_exact_matching(cx: &mut TestAppContext) {
572        init_test(cx);
573        let fs = FakeFs::new(cx.executor());
574
575        fs.insert_tree(
576            "/root",
577            json!({
578                "dir": {
579                    "subdir": {
580                       "file_0": "0"
581                    },
582                    "file_1": "1",
583                    "file_2": "2",
584                    "file_3": "3",
585                },
586                "dir.rs": "4"
587            }),
588        )
589        .await;
590
591        let project = Project::test(fs, ["/root".as_ref()], cx).await;
592
593        let result_1 = cx
594            .update(|cx| collect_files(project.clone(), &["root/dir".to_string()], cx))
595            .await
596            .unwrap();
597
598        assert!(result_1.completion_text.starts_with("root/dir"));
599        // 4 files + 2 directories
600        assert_eq!(6, result_1.files.len());
601
602        let result_2 = cx
603            .update(|cx| collect_files(project.clone(), &["root/dir/".to_string()], cx))
604            .await
605            .unwrap();
606
607        assert_eq!(result_1, result_2);
608
609        let result = cx
610            .update(|cx| collect_files(project.clone(), &["root/dir*".to_string()], cx))
611            .await
612            .unwrap();
613
614        assert!(result.completion_text.starts_with("root/dir"));
615        // 5 files + 2 directories
616        assert_eq!(7, result.files.len());
617
618        // Ensure that the project lasts until after the last await
619        drop(project);
620    }
621
622    #[gpui::test]
623    async fn test_file_sub_directory_rendering(cx: &mut TestAppContext) {
624        init_test(cx);
625        let fs = FakeFs::new(cx.executor());
626
627        fs.insert_tree(
628            "/zed",
629            json!({
630                "assets": {
631                    "dir1": {
632                        ".gitkeep": ""
633                    },
634                    "dir2": {
635                        ".gitkeep": ""
636                    },
637                    "themes": {
638                        "ayu": {
639                            "LICENSE": "1",
640                        },
641                        "andromeda": {
642                            "LICENSE": "2",
643                        },
644                        "summercamp": {
645                            "LICENSE": "3",
646                        },
647                    },
648                },
649            }),
650        )
651        .await;
652
653        let project = Project::test(fs, ["/zed".as_ref()], cx).await;
654
655        let result = cx
656            .update(|cx| collect_files(project.clone(), &["zed/assets/themes".to_string()], cx))
657            .await
658            .unwrap();
659
660        // Sanity check
661        assert!(result.completion_text.starts_with("zed/assets/themes\n"));
662        assert_eq!(7, result.files.len());
663
664        // Ensure that full file paths are included in the real output
665        assert!(result
666            .completion_text
667            .contains("zed/assets/themes/andromeda/LICENSE"));
668        assert!(result
669            .completion_text
670            .contains("zed/assets/themes/ayu/LICENSE"));
671        assert!(result
672            .completion_text
673            .contains("zed/assets/themes/summercamp/LICENSE"));
674
675        assert_eq!("summercamp", result.files[5].path.to_string_lossy());
676
677        // Ensure that things are in descending order, with properly relativized paths
678        assert_eq!(
679            "zed/assets/themes/andromeda/LICENSE",
680            result.files[0].path.to_string_lossy()
681        );
682        assert_eq!("andromeda", result.files[1].path.to_string_lossy());
683        assert_eq!(
684            "zed/assets/themes/ayu/LICENSE",
685            result.files[2].path.to_string_lossy()
686        );
687        assert_eq!("ayu", result.files[3].path.to_string_lossy());
688        assert_eq!(
689            "zed/assets/themes/summercamp/LICENSE",
690            result.files[4].path.to_string_lossy()
691        );
692
693        // Ensure that the project lasts until after the last await
694        drop(project);
695    }
696
697    #[gpui::test]
698    async fn test_file_deep_sub_directory_rendering(cx: &mut TestAppContext) {
699        init_test(cx);
700        let fs = FakeFs::new(cx.executor());
701
702        fs.insert_tree(
703            "/zed",
704            json!({
705                "assets": {
706                    "themes": {
707                        "LICENSE": "1",
708                        "summercamp": {
709                            "LICENSE": "1",
710                            "subdir": {
711                                "LICENSE": "1",
712                                "subsubdir": {
713                                    "LICENSE": "3",
714                                }
715                            }
716                        },
717                    },
718                },
719            }),
720        )
721        .await;
722
723        let project = Project::test(fs, ["/zed".as_ref()], cx).await;
724
725        let result = cx
726            .update(|cx| collect_files(project.clone(), &["zed/assets/themes".to_string()], cx))
727            .await
728            .unwrap();
729
730        assert!(result.completion_text.starts_with("zed/assets/themes\n"));
731        assert_eq!(
732            "zed/assets/themes/LICENSE",
733            result.files[0].path.to_string_lossy()
734        );
735        assert_eq!(
736            "zed/assets/themes/summercamp/LICENSE",
737            result.files[1].path.to_string_lossy()
738        );
739        assert_eq!(
740            "zed/assets/themes/summercamp/subdir/LICENSE",
741            result.files[2].path.to_string_lossy()
742        );
743        assert_eq!(
744            "zed/assets/themes/summercamp/subdir/subsubdir/LICENSE",
745            result.files[3].path.to_string_lossy()
746        );
747        assert_eq!("subsubdir", result.files[4].path.to_string_lossy());
748        assert_eq!("subdir", result.files[5].path.to_string_lossy());
749        assert_eq!("summercamp", result.files[6].path.to_string_lossy());
750        assert_eq!("zed/assets/themes", result.files[7].path.to_string_lossy());
751
752        // Ensure that the project lasts until after the last await
753        drop(project);
754    }
755}