file_command.rs

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