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    ("nix", &["nix"]),
 53    ("nu", &["nu"]),
 54    ("ocaml", &["ml", "mli"]),
 55    ("php", &["php"]),
 56    ("prisma", &["prisma"]),
 57    ("proto", &["proto"]),
 58    ("purescript", &["purs"]),
 59    ("r", &["r", "R"]),
 60    ("racket", &["rkt"]),
 61    ("rescript", &["res", "resi"]),
 62    ("ruby", &["rb", "erb"]),
 63    ("scheme", &["scm"]),
 64    ("scss", &["scss"]),
 65    ("sql", &["sql"]),
 66    ("svelte", &["svelte"]),
 67    ("swift", &["swift"]),
 68    ("templ", &["templ"]),
 69    ("terraform", &["tf", "tfvars", "hcl"]),
 70    ("toml", &["Cargo.lock", "toml"]),
 71    ("vue", &["vue"]),
 72    ("wgsl", &["wgsl"]),
 73    ("wit", &["wit"]),
 74    ("zig", &["zig"]),
 75];
 76
 77fn suggested_extensions() -> &'static HashMap<&'static str, Arc<str>> {
 78    static SUGGESTIONS_BY_PATH_SUFFIX: OnceLock<HashMap<&str, Arc<str>>> = OnceLock::new();
 79    SUGGESTIONS_BY_PATH_SUFFIX.get_or_init(|| {
 80        SUGGESTIONS_BY_EXTENSION_ID
 81            .iter()
 82            .flat_map(|(name, path_suffixes)| {
 83                let name = Arc::<str>::from(*name);
 84                path_suffixes
 85                    .iter()
 86                    .map(move |suffix| (*suffix, name.clone()))
 87            })
 88            .collect()
 89    })
 90}
 91
 92#[derive(Debug, PartialEq, Eq, Clone)]
 93struct SuggestedExtension {
 94    pub extension_id: Arc<str>,
 95    pub file_name_or_extension: Arc<str>,
 96}
 97
 98/// Returns the suggested extension for the given [`Path`].
 99fn suggested_extension(path: impl AsRef<Path>) -> Option<SuggestedExtension> {
100    let path = path.as_ref();
101
102    let file_extension: Option<Arc<str>> = path
103        .extension()
104        .and_then(|extension| Some(extension.to_str()?.into()));
105    let file_name: Option<Arc<str>> = path
106        .file_name()
107        .and_then(|file_name| Some(file_name.to_str()?.into()));
108
109    let (file_name_or_extension, extension_id) = None
110        // We suggest against file names first, as these suggestions will be more
111        // specific than ones based on the file extension.
112        .or_else(|| {
113            file_name.clone().zip(
114                file_name
115                    .as_deref()
116                    .and_then(|file_name| suggested_extensions().get(file_name)),
117            )
118        })
119        .or_else(|| {
120            file_extension.clone().zip(
121                file_extension
122                    .as_deref()
123                    .and_then(|file_extension| suggested_extensions().get(file_extension)),
124            )
125        })?;
126
127    Some(SuggestedExtension {
128        extension_id: extension_id.clone(),
129        file_name_or_extension,
130    })
131}
132
133fn language_extension_key(extension_id: &str) -> String {
134    format!("{}_extension_suggest", extension_id)
135}
136
137pub(crate) fn suggest(buffer: Entity<Buffer>, window: &mut Window, cx: &mut Context<Workspace>) {
138    let Some(file) = buffer.read(cx).file().cloned() else {
139        return;
140    };
141
142    let Some(SuggestedExtension {
143        extension_id,
144        file_name_or_extension,
145    }) = suggested_extension(file.path())
146    else {
147        return;
148    };
149
150    let key = language_extension_key(&extension_id);
151    let Ok(None) = KEY_VALUE_STORE.read_kvp(&key) else {
152        return;
153    };
154
155    cx.on_next_frame(window, move |workspace, _, cx| {
156        let Some(editor) = workspace.active_item_as::<Editor>(cx) else {
157            return;
158        };
159
160        if editor.read(cx).buffer().read(cx).as_singleton().as_ref() != Some(&buffer) {
161            return;
162        }
163
164        struct ExtensionSuggestionNotification;
165
166        let notification_id = NotificationId::composite::<ExtensionSuggestionNotification>(
167            SharedString::from(extension_id.clone()),
168        );
169
170        workspace.show_notification(notification_id, cx, |cx| {
171            cx.new(move |cx| {
172                MessageNotification::new(
173                    format!(
174                        "Do you want to install the recommended '{}' extension for '{}' files?",
175                        extension_id, file_name_or_extension
176                    ),
177                    cx,
178                )
179                .primary_message("Yes, install extension")
180                .primary_icon(IconName::Check)
181                .primary_icon_color(Color::Success)
182                .primary_on_click({
183                    let extension_id = extension_id.clone();
184                    move |_window, cx| {
185                        let extension_id = extension_id.clone();
186                        let extension_store = ExtensionStore::global(cx);
187                        extension_store.update(cx, move |store, cx| {
188                            store.install_latest_extension(extension_id, cx);
189                        });
190                    }
191                })
192                .secondary_message("No, don't install it")
193                .secondary_icon(IconName::Close)
194                .secondary_icon_color(Color::Error)
195                .secondary_on_click(move |_window, cx| {
196                    let key = language_extension_key(&extension_id);
197                    db::write_and_log(cx, move || {
198                        KEY_VALUE_STORE.write_kvp(key, "dismissed".to_string())
199                    });
200                })
201            })
202        });
203    })
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    pub fn test_suggested_extension() {
212        assert_eq!(
213            suggested_extension("Cargo.toml"),
214            Some(SuggestedExtension {
215                extension_id: "toml".into(),
216                file_name_or_extension: "toml".into()
217            })
218        );
219        assert_eq!(
220            suggested_extension("Cargo.lock"),
221            Some(SuggestedExtension {
222                extension_id: "toml".into(),
223                file_name_or_extension: "Cargo.lock".into()
224            })
225        );
226        assert_eq!(
227            suggested_extension("Dockerfile"),
228            Some(SuggestedExtension {
229                extension_id: "dockerfile".into(),
230                file_name_or_extension: "Dockerfile".into()
231            })
232        );
233        assert_eq!(
234            suggested_extension("a/b/c/d/.gitignore"),
235            Some(SuggestedExtension {
236                extension_id: "git-firefly".into(),
237                file_name_or_extension: ".gitignore".into()
238            })
239        );
240        assert_eq!(
241            suggested_extension("a/b/c/d/test.gleam"),
242            Some(SuggestedExtension {
243                extension_id: "gleam".into(),
244                file_name_or_extension: "gleam".into()
245            })
246        );
247    }
248}