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