file_command.rs

  1use super::{SlashCommand, SlashCommandOutput};
  2use anyhow::{anyhow, Result};
  3use assistant_slash_command::SlashCommandOutputSection;
  4use fuzzy::PathMatch;
  5use gpui::{AppContext, RenderOnce, SharedString, Task, View, WeakView};
  6use language::{LineEnding, LspAdapterDelegate};
  7use project::PathMatchCandidateSet;
  8use std::{
  9    fmt::Write,
 10    ops::Range,
 11    path::{Path, PathBuf},
 12    sync::{atomic::AtomicBool, Arc},
 13};
 14use ui::{prelude::*, ButtonLike, ElevationIndex};
 15use workspace::Workspace;
 16
 17pub(crate) struct FileSlashCommand;
 18
 19impl FileSlashCommand {
 20    fn search_paths(
 21        &self,
 22        query: String,
 23        cancellation_flag: Arc<AtomicBool>,
 24        workspace: &View<Workspace>,
 25        cx: &mut AppContext,
 26    ) -> Task<Vec<PathMatch>> {
 27        if query.is_empty() {
 28            let workspace = workspace.read(cx);
 29            let project = workspace.project().read(cx);
 30            let entries = workspace.recent_navigation_history(Some(10), cx);
 31            let path_prefix: Arc<str> = "".into();
 32            Task::ready(
 33                entries
 34                    .into_iter()
 35                    .filter_map(|(entry, _)| {
 36                        let worktree = project.worktree_for_id(entry.worktree_id, cx)?;
 37                        let mut full_path = PathBuf::from(worktree.read(cx).root_name());
 38                        full_path.push(&entry.path);
 39                        Some(PathMatch {
 40                            score: 0.,
 41                            positions: Vec::new(),
 42                            worktree_id: entry.worktree_id.to_usize(),
 43                            path: full_path.into(),
 44                            path_prefix: path_prefix.clone(),
 45                            distance_to_relative_ancestor: 0,
 46                        })
 47                    })
 48                    .collect(),
 49            )
 50        } else {
 51            let worktrees = workspace.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 52            let candidate_sets = worktrees
 53                .into_iter()
 54                .map(|worktree| {
 55                    let worktree = worktree.read(cx);
 56                    PathMatchCandidateSet {
 57                        snapshot: worktree.snapshot(),
 58                        include_ignored: worktree
 59                            .root_entry()
 60                            .map_or(false, |entry| entry.is_ignored),
 61                        include_root_name: true,
 62                        candidates: project::Candidates::Files,
 63                    }
 64                })
 65                .collect::<Vec<_>>();
 66
 67            let executor = cx.background_executor().clone();
 68            cx.foreground_executor().spawn(async move {
 69                fuzzy::match_path_sets(
 70                    candidate_sets.as_slice(),
 71                    query.as_str(),
 72                    None,
 73                    false,
 74                    100,
 75                    &cancellation_flag,
 76                    executor,
 77                )
 78                .await
 79            })
 80        }
 81    }
 82}
 83
 84impl SlashCommand for FileSlashCommand {
 85    fn name(&self) -> String {
 86        "file".into()
 87    }
 88
 89    fn description(&self) -> String {
 90        "insert file".into()
 91    }
 92
 93    fn menu_text(&self) -> String {
 94        "Insert File".into()
 95    }
 96
 97    fn requires_argument(&self) -> bool {
 98        true
 99    }
100
101    fn complete_argument(
102        &self,
103        query: String,
104        cancellation_flag: Arc<AtomicBool>,
105        workspace: Option<WeakView<Workspace>>,
106        cx: &mut AppContext,
107    ) -> Task<Result<Vec<String>>> {
108        let Some(workspace) = workspace.and_then(|workspace| workspace.upgrade()) else {
109            return Task::ready(Err(anyhow!("workspace was dropped")));
110        };
111
112        let paths = self.search_paths(query, cancellation_flag, &workspace, cx);
113        cx.background_executor().spawn(async move {
114            Ok(paths
115                .await
116                .into_iter()
117                .map(|path_match| {
118                    format!(
119                        "{}{}",
120                        path_match.path_prefix,
121                        path_match.path.to_string_lossy()
122                    )
123                })
124                .collect())
125        })
126    }
127
128    fn run(
129        self: Arc<Self>,
130        argument: Option<&str>,
131        workspace: WeakView<Workspace>,
132        _delegate: Arc<dyn LspAdapterDelegate>,
133        cx: &mut WindowContext,
134    ) -> Task<Result<SlashCommandOutput>> {
135        let Some(workspace) = workspace.upgrade() else {
136            return Task::ready(Err(anyhow!("workspace was dropped")));
137        };
138
139        let Some(argument) = argument else {
140            return Task::ready(Err(anyhow!("missing path")));
141        };
142
143        let path = PathBuf::from(argument);
144        let abs_path = workspace
145            .read(cx)
146            .visible_worktrees(cx)
147            .find_map(|worktree| {
148                let worktree = worktree.read(cx);
149                let worktree_root_path = Path::new(worktree.root_name());
150                let relative_path = path.strip_prefix(worktree_root_path).ok()?;
151                worktree.absolutize(&relative_path).ok()
152            });
153
154        let Some(abs_path) = abs_path else {
155            return Task::ready(Err(anyhow!("missing path")));
156        };
157
158        let fs = workspace.read(cx).app_state().fs.clone();
159        let text = cx.background_executor().spawn({
160            let path = path.clone();
161            async move {
162                let mut content = fs.load(&abs_path).await?;
163                LineEnding::normalize(&mut content);
164                let mut output = String::new();
165                output.push_str(&codeblock_fence_for_path(Some(&path), None));
166                output.push_str(&content);
167                if !output.ends_with('\n') {
168                    output.push('\n');
169                }
170                output.push_str("```");
171                anyhow::Ok(output)
172            }
173        });
174        cx.foreground_executor().spawn(async move {
175            let text = text.await?;
176            let range = 0..text.len();
177            Ok(SlashCommandOutput {
178                text,
179                sections: vec![SlashCommandOutputSection {
180                    range,
181                    render_placeholder: Arc::new(move |id, unfold, _cx| {
182                        FilePlaceholder {
183                            path: Some(path.clone()),
184                            line_range: None,
185                            id,
186                            unfold,
187                        }
188                        .into_any_element()
189                    }),
190                }],
191                run_commands_in_text: false,
192            })
193        })
194    }
195}
196
197#[derive(IntoElement)]
198pub struct FilePlaceholder {
199    pub path: Option<PathBuf>,
200    pub line_range: Option<Range<u32>>,
201    pub id: ElementId,
202    pub unfold: Arc<dyn Fn(&mut WindowContext)>,
203}
204
205impl RenderOnce for FilePlaceholder {
206    fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
207        let unfold = self.unfold;
208        let title = if let Some(path) = self.path.as_ref() {
209            SharedString::from(path.to_string_lossy().to_string())
210        } else {
211            SharedString::from("untitled")
212        };
213
214        ButtonLike::new(self.id)
215            .style(ButtonStyle::Filled)
216            .layer(ElevationIndex::ElevatedSurface)
217            .child(Icon::new(IconName::File))
218            .child(Label::new(title))
219            .when_some(self.line_range, |button, line_range| {
220                button.child(Label::new(":")).child(Label::new(format!(
221                    "{}-{}",
222                    line_range.start, line_range.end
223                )))
224            })
225            .on_click(move |_, cx| unfold(cx))
226    }
227}
228
229pub fn codeblock_fence_for_path(path: Option<&Path>, row_range: Option<Range<u32>>) -> String {
230    let mut text = String::new();
231    write!(text, "```").unwrap();
232
233    if let Some(path) = path {
234        if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
235            write!(text, "{} ", extension).unwrap();
236        }
237
238        write!(text, "{}", path.display()).unwrap();
239    } else {
240        write!(text, "untitled").unwrap();
241    }
242
243    if let Some(row_range) = row_range {
244        write!(text, ":{}-{}", row_range.start + 1, row_range.end + 1).unwrap();
245    }
246
247    text.push('\n');
248    text
249}