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