extension_suggest.rs

  1use std::collections::HashMap;
  2use std::path::Path;
  3use std::sync::{Arc, OnceLock};
  4
  5use db::kvp::KEY_VALUE_STORE;
  6use editor::Editor;
  7use extension_host::ExtensionStore;
  8use gpui::{AppContext as _, Context, Entity, SharedString, Window};
  9use language::Buffer;
 10use ui::prelude::*;
 11use workspace::notifications::simple_message_notification::MessageNotification;
 12use workspace::{Workspace, notifications::NotificationId};
 13
 14const SUGGESTIONS_BY_EXTENSION_ID: &[(&str, &[&str])] = &[
 15    ("astro", &["astro"]),
 16    ("beancount", &["beancount"]),
 17    ("clojure", &["bb", "clj", "cljc", "cljs", "edn"]),
 18    ("neocmake", &["CMakeLists.txt", "cmake"]),
 19    ("csharp", &["cs"]),
 20    ("cython", &["pyx", "pxd", "pxi"]),
 21    ("dart", &["dart"]),
 22    ("dockerfile", &["Dockerfile"]),
 23    ("elisp", &["el"]),
 24    ("elixir", &["ex", "exs", "heex"]),
 25    ("elm", &["elm"]),
 26    ("erlang", &["erl", "hrl"]),
 27    ("fish", &["fish"]),
 28    (
 29        "git-firefly",
 30        &[
 31            ".gitconfig",
 32            ".gitignore",
 33            "COMMIT_EDITMSG",
 34            "EDIT_DESCRIPTION",
 35            "MERGE_MSG",
 36            "NOTES_EDITMSG",
 37            "TAG_EDITMSG",
 38            "git-rebase-todo",
 39        ],
 40    ),
 41    ("gleam", &["gleam"]),
 42    ("glsl", &["vert", "frag"]),
 43    ("graphql", &["gql", "graphql"]),
 44    ("haskell", &["hs"]),
 45    ("html", &["htm", "html", "shtml"]),
 46    ("java", &["java"]),
 47    ("kotlin", &["kt"]),
 48    ("latex", &["tex"]),
 49    ("log", &["log"]),
 50    ("lua", &["lua"]),
 51    ("make", &["Makefile"]),
 52    ("nim", &["nim"]),
 53    ("nix", &["nix"]),
 54    ("nu", &["nu"]),
 55    ("ocaml", &["ml", "mli"]),
 56    ("php", &["php"]),
 57    ("prisma", &["prisma"]),
 58    ("proto", &["proto"]),
 59    ("purescript", &["purs"]),
 60    ("r", &["r", "R"]),
 61    ("racket", &["rkt"]),
 62    ("rescript", &["res", "resi"]),
 63    ("rst", &["rst"]),
 64    ("ruby", &["rb", "erb"]),
 65    ("scheme", &["scm"]),
 66    ("scss", &["scss"]),
 67    ("sql", &["sql"]),
 68    ("svelte", &["svelte"]),
 69    ("swift", &["swift"]),
 70    ("templ", &["templ"]),
 71    ("terraform", &["tf", "tfvars", "hcl"]),
 72    ("toml", &["Cargo.lock", "toml"]),
 73    ("vue", &["vue"]),
 74    ("wgsl", &["wgsl"]),
 75    ("wit", &["wit"]),
 76    ("zig", &["zig"]),
 77];
 78
 79fn suggested_extensions() -> &'static HashMap<&'static str, Arc<str>> {
 80    static SUGGESTIONS_BY_PATH_SUFFIX: OnceLock<HashMap<&str, Arc<str>>> = OnceLock::new();
 81    SUGGESTIONS_BY_PATH_SUFFIX.get_or_init(|| {
 82        SUGGESTIONS_BY_EXTENSION_ID
 83            .iter()
 84            .flat_map(|(name, path_suffixes)| {
 85                let name = Arc::<str>::from(*name);
 86                path_suffixes
 87                    .iter()
 88                    .map(move |suffix| (*suffix, name.clone()))
 89            })
 90            .collect()
 91    })
 92}
 93
 94#[derive(Debug, PartialEq, Eq, Clone)]
 95struct SuggestedExtension {
 96    pub extension_id: Arc<str>,
 97    pub file_name_or_extension: Arc<str>,
 98}
 99
100/// Returns the suggested extension for the given [`Path`].
101fn suggested_extension(path: impl AsRef<Path>) -> Option<SuggestedExtension> {
102    let path = path.as_ref();
103
104    let file_extension: Option<Arc<str>> = path
105        .extension()
106        .and_then(|extension| Some(extension.to_str()?.into()));
107    let file_name: Option<Arc<str>> = path
108        .file_name()
109        .and_then(|file_name| Some(file_name.to_str()?.into()));
110
111    let (file_name_or_extension, extension_id) = None
112        // We suggest against file names first, as these suggestions will be more
113        // specific than ones based on the file extension.
114        .or_else(|| {
115            file_name.clone().zip(
116                file_name
117                    .as_deref()
118                    .and_then(|file_name| suggested_extensions().get(file_name)),
119            )
120        })
121        .or_else(|| {
122            file_extension.clone().zip(
123                file_extension
124                    .as_deref()
125                    .and_then(|file_extension| suggested_extensions().get(file_extension)),
126            )
127        })?;
128
129    Some(SuggestedExtension {
130        extension_id: extension_id.clone(),
131        file_name_or_extension,
132    })
133}
134
135fn language_extension_key(extension_id: &str) -> String {
136    format!("{}_extension_suggest", extension_id)
137}
138
139pub(crate) fn suggest(buffer: Entity<Buffer>, window: &mut Window, cx: &mut Context<Workspace>) {
140    let Some(file) = buffer.read(cx).file().cloned() else {
141        return;
142    };
143
144    let Some(SuggestedExtension {
145        extension_id,
146        file_name_or_extension,
147    }) = suggested_extension(file.path())
148    else {
149        return;
150    };
151
152    let key = language_extension_key(&extension_id);
153    let Ok(None) = KEY_VALUE_STORE.read_kvp(&key) else {
154        return;
155    };
156
157    cx.on_next_frame(window, move |workspace, _, cx| {
158        let Some(editor) = workspace.active_item_as::<Editor>(cx) else {
159            return;
160        };
161
162        if editor.read(cx).buffer().read(cx).as_singleton().as_ref() != Some(&buffer) {
163            return;
164        }
165
166        struct ExtensionSuggestionNotification;
167
168        let notification_id = NotificationId::composite::<ExtensionSuggestionNotification>(
169            SharedString::from(extension_id.clone()),
170        );
171
172        workspace.show_notification(notification_id, cx, |cx| {
173            cx.new(move |cx| {
174                MessageNotification::new(
175                    format!(
176                        "Do you want to install the recommended '{}' extension for '{}' files?",
177                        extension_id, file_name_or_extension
178                    ),
179                    cx,
180                )
181                .primary_message("Yes, install extension")
182                .primary_icon(IconName::Check)
183                .primary_icon_color(Color::Success)
184                .primary_on_click({
185                    let extension_id = extension_id.clone();
186                    move |_window, cx| {
187                        let extension_id = extension_id.clone();
188                        let extension_store = ExtensionStore::global(cx);
189                        extension_store.update(cx, move |store, cx| {
190                            store.install_latest_extension(extension_id, cx);
191                        });
192                    }
193                })
194                .secondary_message("No, don't install it")
195                .secondary_icon(IconName::Close)
196                .secondary_icon_color(Color::Error)
197                .secondary_on_click(move |_window, cx| {
198                    let key = language_extension_key(&extension_id);
199                    db::write_and_log(cx, move || {
200                        KEY_VALUE_STORE.write_kvp(key, "dismissed".to_string())
201                    });
202                })
203            })
204        });
205    })
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    pub fn test_suggested_extension() {
214        assert_eq!(
215            suggested_extension("Cargo.toml"),
216            Some(SuggestedExtension {
217                extension_id: "toml".into(),
218                file_name_or_extension: "toml".into()
219            })
220        );
221        assert_eq!(
222            suggested_extension("Cargo.lock"),
223            Some(SuggestedExtension {
224                extension_id: "toml".into(),
225                file_name_or_extension: "Cargo.lock".into()
226            })
227        );
228        assert_eq!(
229            suggested_extension("Dockerfile"),
230            Some(SuggestedExtension {
231                extension_id: "dockerfile".into(),
232                file_name_or_extension: "Dockerfile".into()
233            })
234        );
235        assert_eq!(
236            suggested_extension("a/b/c/d/.gitignore"),
237            Some(SuggestedExtension {
238                extension_id: "git-firefly".into(),
239                file_name_or_extension: ".gitignore".into()
240            })
241        );
242        assert_eq!(
243            suggested_extension("a/b/c/d/test.gleam"),
244            Some(SuggestedExtension {
245                extension_id: "gleam".into(),
246                file_name_or_extension: "gleam".into()
247            })
248        );
249    }
250}