extension_suggest.rs

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