1mod capability_granter;
2pub mod extension_settings;
3pub mod headless_host;
4pub mod wasm_host;
5
6#[cfg(test)]
7mod extension_store_test;
8
9use anyhow::{Context as _, Result, anyhow, bail};
10use async_compression::futures::bufread::GzipDecoder;
11use async_tar::Archive;
12use client::ExtensionProvides;
13use client::{Client, ExtensionMetadata, GetExtensionsResponse, proto, telemetry::Telemetry};
14use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
15pub use extension::ExtensionManifest;
16use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
17use extension::{
18 ExtensionContextServerProxy, ExtensionDebugAdapterProviderProxy, ExtensionEvents,
19 ExtensionGrammarProxy, ExtensionHostProxy, ExtensionLanguageProxy,
20 ExtensionLanguageServerProxy, ExtensionSlashCommandProxy, ExtensionSnippetProxy,
21 ExtensionThemeProxy,
22};
23use fs::{Fs, RemoveOptions};
24use futures::future::join_all;
25use futures::{
26 AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
27 channel::{
28 mpsc::{UnboundedSender, unbounded},
29 oneshot,
30 },
31 io::BufReader,
32 select_biased,
33};
34use gpui::{
35 App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, Task, WeakEntity,
36 actions,
37};
38use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
39use language::{
40 LanguageConfig, LanguageMatcher, LanguageName, LanguageQueries, LoadedLanguage,
41 QUERY_FILENAME_PREFIXES, Rope,
42};
43use node_runtime::NodeRuntime;
44use project::ContextProviderWithTasks;
45use release_channel::ReleaseChannel;
46use remote::{RemoteClient, RemoteConnectionOptions};
47use semantic_version::SemanticVersion;
48use serde::{Deserialize, Serialize};
49use settings::Settings;
50use std::ops::RangeInclusive;
51use std::str::FromStr;
52use std::{
53 cmp::Ordering,
54 path::{self, Path, PathBuf},
55 sync::Arc,
56 time::{Duration, Instant},
57};
58use url::Url;
59use util::{ResultExt, paths::RemotePathBuf};
60use wasm_host::{
61 WasmExtension, WasmHost,
62 wit::{is_supported_wasm_api_version, wasm_api_version_range},
63};
64
65pub use extension::{
66 ExtensionLibraryKind, GrammarManifestEntry, OldExtensionManifest, SchemaVersion,
67};
68pub use extension_settings::ExtensionSettings;
69
70pub const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
71const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
72
73/// The current extension [`SchemaVersion`] supported by Zed.
74const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
75
76/// Extensions that should no longer be loaded or downloaded.
77///
78/// These snippets should no longer be downloaded or loaded, because their
79/// functionality has been integrated into the core editor.
80const SUPPRESSED_EXTENSIONS: &[&str] = &["snippets", "ruff", "ty", "basedpyright"];
81
82/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
83pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
84 SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
85}
86
87/// Returns whether the given extension version is compatible with this version of Zed.
88pub fn is_version_compatible(
89 release_channel: ReleaseChannel,
90 extension_version: &ExtensionMetadata,
91) -> bool {
92 let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
93 if CURRENT_SCHEMA_VERSION.0 < schema_version {
94 return false;
95 }
96
97 if let Some(wasm_api_version) = extension_version
98 .manifest
99 .wasm_api_version
100 .as_ref()
101 .and_then(|wasm_api_version| SemanticVersion::from_str(wasm_api_version).ok())
102 && !is_supported_wasm_api_version(release_channel, wasm_api_version)
103 {
104 return false;
105 }
106
107 true
108}
109
110pub struct ExtensionStore {
111 pub proxy: Arc<ExtensionHostProxy>,
112 pub builder: Arc<ExtensionBuilder>,
113 pub extension_index: ExtensionIndex,
114 pub fs: Arc<dyn Fs>,
115 pub http_client: Arc<HttpClientWithUrl>,
116 pub telemetry: Option<Arc<Telemetry>>,
117 pub reload_tx: UnboundedSender<Option<Arc<str>>>,
118 pub reload_complete_senders: Vec<oneshot::Sender<()>>,
119 pub installed_dir: PathBuf,
120 pub outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
121 pub index_path: PathBuf,
122 pub modified_extensions: HashSet<Arc<str>>,
123 pub wasm_host: Arc<WasmHost>,
124 pub wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
125 pub tasks: Vec<Task<()>>,
126 pub remote_clients: HashMap<RemoteConnectionOptions, WeakEntity<RemoteClient>>,
127 pub ssh_registered_tx: UnboundedSender<()>,
128}
129
130#[derive(Clone, Copy)]
131pub enum ExtensionOperation {
132 Upgrade,
133 Install,
134 Remove,
135}
136
137#[derive(Clone)]
138pub enum Event {
139 ExtensionsUpdated,
140 StartedReloading,
141 ExtensionInstalled(Arc<str>),
142 ExtensionUninstalled(Arc<str>),
143 ExtensionFailedToLoad(Arc<str>),
144}
145
146impl EventEmitter<Event> for ExtensionStore {}
147
148struct GlobalExtensionStore(Entity<ExtensionStore>);
149
150impl Global for GlobalExtensionStore {}
151
152#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
153pub struct ExtensionIndex {
154 pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
155 pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
156 #[serde(default)]
157 pub icon_themes: BTreeMap<Arc<str>, ExtensionIndexIconThemeEntry>,
158 pub languages: BTreeMap<LanguageName, ExtensionIndexLanguageEntry>,
159}
160
161#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
162pub struct ExtensionIndexEntry {
163 pub manifest: Arc<ExtensionManifest>,
164 pub dev: bool,
165}
166
167#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
168pub struct ExtensionIndexThemeEntry {
169 pub extension: Arc<str>,
170 pub path: PathBuf,
171}
172
173#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
174pub struct ExtensionIndexIconThemeEntry {
175 pub extension: Arc<str>,
176 pub path: PathBuf,
177}
178
179#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
180pub struct ExtensionIndexLanguageEntry {
181 pub extension: Arc<str>,
182 pub path: PathBuf,
183 pub matcher: LanguageMatcher,
184 pub hidden: bool,
185 pub grammar: Option<Arc<str>>,
186}
187
188actions!(
189 zed,
190 [
191 /// Reloads all installed extensions.
192 ReloadExtensions
193 ]
194);
195
196pub fn init(
197 extension_host_proxy: Arc<ExtensionHostProxy>,
198 fs: Arc<dyn Fs>,
199 client: Arc<Client>,
200 node_runtime: NodeRuntime,
201 cx: &mut App,
202) {
203 let store = cx.new(move |cx| {
204 ExtensionStore::new(
205 paths::extensions_dir().clone(),
206 None,
207 extension_host_proxy,
208 fs,
209 client.http_client(),
210 client.http_client(),
211 Some(client.telemetry().clone()),
212 node_runtime,
213 cx,
214 )
215 });
216
217 cx.on_action(|_: &ReloadExtensions, cx| {
218 let store = cx.global::<GlobalExtensionStore>().0.clone();
219 store.update(cx, |store, cx| drop(store.reload(None, cx)));
220 });
221
222 cx.set_global(GlobalExtensionStore(store));
223}
224
225impl ExtensionStore {
226 pub fn try_global(cx: &App) -> Option<Entity<Self>> {
227 cx.try_global::<GlobalExtensionStore>()
228 .map(|store| store.0.clone())
229 }
230
231 pub fn global(cx: &App) -> Entity<Self> {
232 cx.global::<GlobalExtensionStore>().0.clone()
233 }
234
235 pub fn new(
236 extensions_dir: PathBuf,
237 build_dir: Option<PathBuf>,
238 extension_host_proxy: Arc<ExtensionHostProxy>,
239 fs: Arc<dyn Fs>,
240 http_client: Arc<HttpClientWithUrl>,
241 builder_client: Arc<dyn HttpClient>,
242 telemetry: Option<Arc<Telemetry>>,
243 node_runtime: NodeRuntime,
244 cx: &mut Context<Self>,
245 ) -> Self {
246 let work_dir = extensions_dir.join("work");
247 let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
248 let installed_dir = extensions_dir.join("installed");
249 let index_path = extensions_dir.join("index.json");
250
251 let (reload_tx, mut reload_rx) = unbounded();
252 let (connection_registered_tx, mut connection_registered_rx) = unbounded();
253 let mut this = Self {
254 proxy: extension_host_proxy.clone(),
255 extension_index: Default::default(),
256 installed_dir,
257 index_path,
258 builder: Arc::new(ExtensionBuilder::new(builder_client, build_dir)),
259 outstanding_operations: Default::default(),
260 modified_extensions: Default::default(),
261 reload_complete_senders: Vec::new(),
262 wasm_host: WasmHost::new(
263 fs.clone(),
264 http_client.clone(),
265 node_runtime,
266 extension_host_proxy,
267 work_dir,
268 cx,
269 ),
270 wasm_extensions: Vec::new(),
271 fs,
272 http_client,
273 telemetry,
274 reload_tx,
275 tasks: Vec::new(),
276
277 remote_clients: HashMap::default(),
278 ssh_registered_tx: connection_registered_tx,
279 };
280
281 // The extensions store maintains an index file, which contains a complete
282 // list of the installed extensions and the resources that they provide.
283 // This index is loaded synchronously on startup.
284 let (index_content, index_metadata, extensions_metadata) =
285 cx.background_executor().block(async {
286 futures::join!(
287 this.fs.load(&this.index_path),
288 this.fs.metadata(&this.index_path),
289 this.fs.metadata(&this.installed_dir),
290 )
291 });
292
293 // Normally, there is no need to rebuild the index. But if the index file
294 // is invalid or is out-of-date according to the filesystem mtimes, then
295 // it must be asynchronously rebuilt.
296 let mut extension_index = ExtensionIndex::default();
297 let mut extension_index_needs_rebuild = true;
298 if let Ok(index_content) = index_content
299 && let Some(index) = serde_json::from_str(&index_content).log_err()
300 {
301 extension_index = index;
302 if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
303 (index_metadata, extensions_metadata)
304 && index_metadata
305 .mtime
306 .bad_is_greater_than(extensions_metadata.mtime)
307 {
308 extension_index_needs_rebuild = false;
309 }
310 }
311
312 // Immediately load all of the extensions in the initial manifest. If the
313 // index needs to be rebuild, then enqueue
314 let load_initial_extensions = this.extensions_updated(extension_index, cx);
315 let mut reload_future = None;
316 if extension_index_needs_rebuild {
317 reload_future = Some(this.reload(None, cx));
318 }
319
320 cx.spawn(async move |this, cx| {
321 if let Some(future) = reload_future {
322 future.await;
323 }
324 this.update(cx, |this, cx| this.auto_install_extensions(cx))
325 .ok();
326 this.update(cx, |this, cx| this.check_for_updates(cx)).ok();
327 })
328 .detach();
329
330 // Perform all extension loading in a single task to ensure that we
331 // never attempt to simultaneously load/unload extensions from multiple
332 // parallel tasks.
333 this.tasks.push(cx.spawn(async move |this, cx| {
334 async move {
335 load_initial_extensions.await;
336
337 let mut index_changed = false;
338 let mut debounce_timer = cx.background_spawn(futures::future::pending()).fuse();
339 loop {
340 select_biased! {
341 _ = debounce_timer => {
342 if index_changed {
343 let index = this
344 .update(cx, |this, cx| this.rebuild_extension_index(cx))?
345 .await;
346 this.update( cx, |this, cx| this.extensions_updated(index, cx))?
347 .await;
348 index_changed = false;
349 }
350
351 Self::update_ssh_clients(&this, cx).await?;
352 }
353 _ = connection_registered_rx.next() => {
354 debounce_timer = cx
355 .background_executor()
356 .timer(RELOAD_DEBOUNCE_DURATION)
357 .fuse();
358 }
359 extension_id = reload_rx.next() => {
360 let Some(extension_id) = extension_id else { break; };
361 this.update(cx, |this, _| {
362 this.modified_extensions.extend(extension_id);
363 })?;
364 index_changed = true;
365 debounce_timer = cx
366 .background_executor()
367 .timer(RELOAD_DEBOUNCE_DURATION)
368 .fuse();
369 }
370 }
371 }
372
373 anyhow::Ok(())
374 }
375 .map(drop)
376 .await;
377 }));
378
379 // Watch the installed extensions directory for changes. Whenever changes are
380 // detected, rebuild the extension index, and load/unload any extensions that
381 // have been added, removed, or modified.
382 this.tasks.push(cx.background_spawn({
383 let fs = this.fs.clone();
384 let reload_tx = this.reload_tx.clone();
385 let installed_dir = this.installed_dir.clone();
386 async move {
387 let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
388 while let Some(events) = paths.next().await {
389 for event in events {
390 let Ok(event_path) = event.path.strip_prefix(&installed_dir) else {
391 continue;
392 };
393
394 if let Some(path::Component::Normal(extension_dir_name)) =
395 event_path.components().next()
396 && let Some(extension_id) = extension_dir_name.to_str()
397 {
398 reload_tx.unbounded_send(Some(extension_id.into())).ok();
399 }
400 }
401 }
402 }
403 }));
404
405 this
406 }
407
408 pub fn reload(
409 &mut self,
410 modified_extension: Option<Arc<str>>,
411 cx: &mut Context<Self>,
412 ) -> impl Future<Output = ()> + use<> {
413 let (tx, rx) = oneshot::channel();
414 self.reload_complete_senders.push(tx);
415 self.reload_tx
416 .unbounded_send(modified_extension)
417 .expect("reload task exited");
418 cx.emit(Event::StartedReloading);
419
420 async move {
421 rx.await.ok();
422 }
423 }
424
425 fn extensions_dir(&self) -> PathBuf {
426 self.installed_dir.clone()
427 }
428
429 pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
430 &self.outstanding_operations
431 }
432
433 pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
434 &self.extension_index.extensions
435 }
436
437 pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
438 self.extension_index
439 .extensions
440 .values()
441 .filter_map(|extension| extension.dev.then_some(&extension.manifest))
442 }
443
444 pub fn extension_manifest_for_id(&self, extension_id: &str) -> Option<&Arc<ExtensionManifest>> {
445 self.extension_index
446 .extensions
447 .get(extension_id)
448 .map(|extension| &extension.manifest)
449 }
450
451 /// Returns the names of themes provided by extensions.
452 pub fn extension_themes<'a>(
453 &'a self,
454 extension_id: &'a str,
455 ) -> impl Iterator<Item = &'a Arc<str>> {
456 self.extension_index
457 .themes
458 .iter()
459 .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
460 }
461
462 /// Returns the path to the theme file within an extension, if there is an
463 /// extension that provides the theme.
464 pub fn path_to_extension_theme(&self, theme_name: &str) -> Option<PathBuf> {
465 let entry = self.extension_index.themes.get(theme_name)?;
466
467 Some(
468 self.extensions_dir()
469 .join(entry.extension.as_ref())
470 .join(&entry.path),
471 )
472 }
473
474 /// Returns the names of icon themes provided by extensions.
475 pub fn extension_icon_themes<'a>(
476 &'a self,
477 extension_id: &'a str,
478 ) -> impl Iterator<Item = &'a Arc<str>> {
479 self.extension_index
480 .icon_themes
481 .iter()
482 .filter_map(|(name, icon_theme)| {
483 icon_theme
484 .extension
485 .as_ref()
486 .eq(extension_id)
487 .then_some(name)
488 })
489 }
490
491 /// Returns the path to the icon theme file within an extension, if there is
492 /// an extension that provides the icon theme.
493 pub fn path_to_extension_icon_theme(
494 &self,
495 icon_theme_name: &str,
496 ) -> Option<(PathBuf, PathBuf)> {
497 let entry = self.extension_index.icon_themes.get(icon_theme_name)?;
498
499 let icon_theme_path = self
500 .extensions_dir()
501 .join(entry.extension.as_ref())
502 .join(&entry.path);
503 let icons_root_path = self.extensions_dir().join(entry.extension.as_ref());
504
505 Some((icon_theme_path, icons_root_path))
506 }
507
508 pub fn fetch_extensions(
509 &self,
510 search: Option<&str>,
511 provides_filter: Option<&BTreeSet<ExtensionProvides>>,
512 cx: &mut Context<Self>,
513 ) -> Task<Result<Vec<ExtensionMetadata>>> {
514 let version = CURRENT_SCHEMA_VERSION.to_string();
515 let mut query = vec![("max_schema_version", version.as_str())];
516 if let Some(search) = search {
517 query.push(("filter", search));
518 }
519
520 let provides_filter = provides_filter.map(|provides_filter| {
521 provides_filter
522 .iter()
523 .map(|provides| provides.to_string())
524 .collect::<Vec<_>>()
525 .join(",")
526 });
527 if let Some(provides_filter) = provides_filter.as_deref() {
528 query.push(("provides", provides_filter));
529 }
530
531 self.fetch_extensions_from_api("/extensions", &query, cx)
532 }
533
534 pub fn fetch_extensions_with_update_available(
535 &mut self,
536 cx: &mut Context<Self>,
537 ) -> Task<Result<Vec<ExtensionMetadata>>> {
538 let schema_versions = schema_version_range();
539 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
540 let extension_settings = ExtensionSettings::get_global(cx);
541 let extension_ids = self
542 .extension_index
543 .extensions
544 .iter()
545 .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
546 .map(|(id, _)| id.as_ref())
547 .collect::<Vec<_>>()
548 .join(",");
549 let task = self.fetch_extensions_from_api(
550 "/extensions/updates",
551 &[
552 ("min_schema_version", &schema_versions.start().to_string()),
553 ("max_schema_version", &schema_versions.end().to_string()),
554 (
555 "min_wasm_api_version",
556 &wasm_api_versions.start().to_string(),
557 ),
558 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
559 ("ids", &extension_ids),
560 ],
561 cx,
562 );
563 cx.spawn(async move |this, cx| {
564 let extensions = task.await?;
565 this.update(cx, |this, _cx| {
566 extensions
567 .into_iter()
568 .filter(|extension| {
569 this.extension_index
570 .extensions
571 .get(&extension.id)
572 .is_none_or(|installed_extension| {
573 installed_extension.manifest.version != extension.manifest.version
574 })
575 })
576 .collect()
577 })
578 })
579 }
580
581 pub fn fetch_extension_versions(
582 &self,
583 extension_id: &str,
584 cx: &mut Context<Self>,
585 ) -> Task<Result<Vec<ExtensionMetadata>>> {
586 self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
587 }
588
589 /// Installs any extensions that should be included with Zed by default.
590 ///
591 /// This can be used to make certain functionality provided by extensions
592 /// available out-of-the-box.
593 pub fn auto_install_extensions(&mut self, cx: &mut Context<Self>) {
594 if cfg!(test) {
595 return;
596 }
597
598 let extension_settings = ExtensionSettings::get_global(cx);
599
600 let extensions_to_install = extension_settings
601 .auto_install_extensions
602 .keys()
603 .filter(|extension_id| extension_settings.should_auto_install(extension_id))
604 .filter(|extension_id| {
605 let is_already_installed = self
606 .extension_index
607 .extensions
608 .contains_key(extension_id.as_ref());
609 !is_already_installed && !SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref())
610 })
611 .cloned()
612 .collect::<Vec<_>>();
613
614 cx.spawn(async move |this, cx| {
615 for extension_id in extensions_to_install {
616 this.update(cx, |this, cx| {
617 this.install_latest_extension(extension_id.clone(), cx);
618 })
619 .ok();
620 }
621 })
622 .detach();
623 }
624
625 pub fn check_for_updates(&mut self, cx: &mut Context<Self>) {
626 let task = self.fetch_extensions_with_update_available(cx);
627 cx.spawn(async move |this, cx| Self::upgrade_extensions(this, task.await?, cx).await)
628 .detach();
629 }
630
631 async fn upgrade_extensions(
632 this: WeakEntity<Self>,
633 extensions: Vec<ExtensionMetadata>,
634 cx: &mut AsyncApp,
635 ) -> Result<()> {
636 for extension in extensions {
637 let task = this.update(cx, |this, cx| {
638 if let Some(installed_extension) =
639 this.extension_index.extensions.get(&extension.id)
640 {
641 let installed_version =
642 SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
643 let latest_version =
644 SemanticVersion::from_str(&extension.manifest.version).ok()?;
645
646 if installed_version >= latest_version {
647 return None;
648 }
649 }
650
651 Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
652 })?;
653
654 if let Some(task) = task {
655 task.await.log_err();
656 }
657 }
658 anyhow::Ok(())
659 }
660
661 fn fetch_extensions_from_api(
662 &self,
663 path: &str,
664 query: &[(&str, &str)],
665 cx: &mut Context<ExtensionStore>,
666 ) -> Task<Result<Vec<ExtensionMetadata>>> {
667 let url = self.http_client.build_zed_api_url(path, query);
668 let http_client = self.http_client.clone();
669 cx.spawn(async move |_, _| {
670 let mut response = http_client
671 .get(url?.as_ref(), AsyncBody::empty(), true)
672 .await?;
673
674 let mut body = Vec::new();
675 response
676 .body_mut()
677 .read_to_end(&mut body)
678 .await
679 .context("error reading extensions")?;
680
681 if response.status().is_client_error() {
682 let text = String::from_utf8_lossy(body.as_slice());
683 bail!(
684 "status error {}, response: {text:?}",
685 response.status().as_u16()
686 );
687 }
688
689 let mut response: GetExtensionsResponse = serde_json::from_slice(&body)?;
690
691 response
692 .data
693 .retain(|extension| !SUPPRESSED_EXTENSIONS.contains(&extension.id.as_ref()));
694
695 Ok(response.data)
696 })
697 }
698
699 pub fn install_extension(
700 &mut self,
701 extension_id: Arc<str>,
702 version: Arc<str>,
703 cx: &mut Context<Self>,
704 ) {
705 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
706 .detach_and_log_err(cx);
707 }
708
709 fn install_or_upgrade_extension_at_endpoint(
710 &mut self,
711 extension_id: Arc<str>,
712 url: Url,
713 operation: ExtensionOperation,
714 cx: &mut Context<Self>,
715 ) -> Task<Result<()>> {
716 let extension_dir = self.installed_dir.join(extension_id.as_ref());
717 let http_client = self.http_client.clone();
718 let fs = self.fs.clone();
719
720 match self.outstanding_operations.entry(extension_id.clone()) {
721 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
722 btree_map::Entry::Vacant(e) => e.insert(operation),
723 };
724 cx.notify();
725
726 cx.spawn(async move |this, cx| {
727 let _finish = cx.on_drop(&this, {
728 let extension_id = extension_id.clone();
729 move |this, cx| {
730 this.outstanding_operations.remove(extension_id.as_ref());
731 cx.notify();
732 }
733 });
734
735 let mut response = http_client
736 .get(url.as_ref(), Default::default(), true)
737 .await
738 .context("downloading extension")?;
739
740 fs.remove_dir(
741 &extension_dir,
742 RemoveOptions {
743 recursive: true,
744 ignore_if_not_exists: true,
745 },
746 )
747 .await?;
748
749 let content_length = response
750 .headers()
751 .get(http_client::http::header::CONTENT_LENGTH)
752 .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
753
754 let mut body = BufReader::new(response.body_mut());
755 let mut tar_gz_bytes = Vec::new();
756 body.read_to_end(&mut tar_gz_bytes).await?;
757
758 if let Some(content_length) = content_length {
759 let actual_len = tar_gz_bytes.len();
760 if content_length != actual_len {
761 bail!("downloaded extension size {actual_len} does not match content length {content_length}");
762 }
763 }
764 let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
765 let archive = Archive::new(decompressed_bytes);
766 archive.unpack(extension_dir).await?;
767 this.update( cx, |this, cx| {
768 this.reload(Some(extension_id.clone()), cx)
769 })?
770 .await;
771
772 if let ExtensionOperation::Install = operation {
773 this.update( cx, |this, cx| {
774 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
775 if let Some(events) = ExtensionEvents::try_global(cx)
776 && let Some(manifest) = this.extension_manifest_for_id(&extension_id) {
777 events.update(cx, |this, cx| {
778 this.emit(
779 extension::Event::ExtensionInstalled(manifest.clone()),
780 cx,
781 )
782 });
783 }
784 })
785 .ok();
786 }
787
788 anyhow::Ok(())
789 })
790 }
791
792 pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
793 log::info!("installing extension {extension_id} latest version");
794
795 let schema_versions = schema_version_range();
796 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
797
798 let Some(url) = self
799 .http_client
800 .build_zed_api_url(
801 &format!("/extensions/{extension_id}/download"),
802 &[
803 ("min_schema_version", &schema_versions.start().to_string()),
804 ("max_schema_version", &schema_versions.end().to_string()),
805 (
806 "min_wasm_api_version",
807 &wasm_api_versions.start().to_string(),
808 ),
809 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
810 ],
811 )
812 .log_err()
813 else {
814 return;
815 };
816
817 self.install_or_upgrade_extension_at_endpoint(
818 extension_id,
819 url,
820 ExtensionOperation::Install,
821 cx,
822 )
823 .detach_and_log_err(cx);
824 }
825
826 pub fn upgrade_extension(
827 &mut self,
828 extension_id: Arc<str>,
829 version: Arc<str>,
830 cx: &mut Context<Self>,
831 ) -> Task<Result<()>> {
832 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
833 }
834
835 fn install_or_upgrade_extension(
836 &mut self,
837 extension_id: Arc<str>,
838 version: Arc<str>,
839 operation: ExtensionOperation,
840 cx: &mut Context<Self>,
841 ) -> Task<Result<()>> {
842 log::info!("installing extension {extension_id} {version}");
843 let Some(url) = self
844 .http_client
845 .build_zed_api_url(
846 &format!("/extensions/{extension_id}/{version}/download"),
847 &[],
848 )
849 .log_err()
850 else {
851 return Task::ready(Ok(()));
852 };
853
854 self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
855 }
856
857 pub fn uninstall_extension(
858 &mut self,
859 extension_id: Arc<str>,
860 cx: &mut Context<Self>,
861 ) -> Task<Result<()>> {
862 let extension_dir = self.installed_dir.join(extension_id.as_ref());
863 let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
864 let fs = self.fs.clone();
865
866 let extension_manifest = self.extension_manifest_for_id(&extension_id).cloned();
867
868 match self.outstanding_operations.entry(extension_id.clone()) {
869 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
870 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
871 };
872
873 cx.spawn(async move |extension_store, cx| {
874 let _finish = cx.on_drop(&extension_store, {
875 let extension_id = extension_id.clone();
876 move |this, cx| {
877 this.outstanding_operations.remove(extension_id.as_ref());
878 cx.notify();
879 }
880 });
881
882 fs.remove_dir(
883 &extension_dir,
884 RemoveOptions {
885 recursive: true,
886 ignore_if_not_exists: true,
887 },
888 )
889 .await
890 .with_context(|| format!("Removing extension dir {extension_dir:?}"))?;
891
892 extension_store
893 .update(cx, |extension_store, cx| extension_store.reload(None, cx))?
894 .await;
895
896 // There's a race between wasm extension fully stopping and the directory removal.
897 // On Windows, it's impossible to remove a directory that has a process running in it.
898 for i in 0..3 {
899 cx.background_executor()
900 .timer(Duration::from_millis(i * 100))
901 .await;
902 let removal_result = fs
903 .remove_dir(
904 &work_dir,
905 RemoveOptions {
906 recursive: true,
907 ignore_if_not_exists: true,
908 },
909 )
910 .await;
911 match removal_result {
912 Ok(()) => break,
913 Err(e) => {
914 if i == 2 {
915 log::error!("Failed to remove extension work dir {work_dir:?} : {e}");
916 }
917 }
918 }
919 }
920
921 extension_store.update(cx, |_, cx| {
922 cx.emit(Event::ExtensionUninstalled(extension_id.clone()));
923 if let Some(events) = ExtensionEvents::try_global(cx)
924 && let Some(manifest) = extension_manifest
925 {
926 events.update(cx, |this, cx| {
927 this.emit(extension::Event::ExtensionUninstalled(manifest.clone()), cx)
928 });
929 }
930 })?;
931
932 anyhow::Ok(())
933 })
934 }
935
936 pub fn install_dev_extension(
937 &mut self,
938 extension_source_path: PathBuf,
939 cx: &mut Context<Self>,
940 ) -> Task<Result<()>> {
941 let extensions_dir = self.extensions_dir();
942 let fs = self.fs.clone();
943 let builder = self.builder.clone();
944
945 cx.spawn(async move |this, cx| {
946 let mut extension_manifest =
947 ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
948 let extension_id = extension_manifest.id.clone();
949
950 if let Some(uninstall_task) = this
951 .update(cx, |this, cx| {
952 this.extension_index
953 .extensions
954 .get(extension_id.as_ref())
955 .is_some_and(|index_entry| !index_entry.dev)
956 .then(|| this.uninstall_extension(extension_id.clone(), cx))
957 })
958 .ok()
959 .flatten()
960 {
961 uninstall_task.await.log_err();
962 }
963
964 if !this.update(cx, |this, cx| {
965 match this.outstanding_operations.entry(extension_id.clone()) {
966 btree_map::Entry::Occupied(_) => return false,
967 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Install),
968 };
969 cx.notify();
970 true
971 })? {
972 return Ok(());
973 }
974
975 let _finish = cx.on_drop(&this, {
976 let extension_id = extension_id.clone();
977 move |this, cx| {
978 this.outstanding_operations.remove(extension_id.as_ref());
979 cx.notify();
980 }
981 });
982
983 cx.background_spawn({
984 let extension_source_path = extension_source_path.clone();
985 async move {
986 builder
987 .compile_extension(
988 &extension_source_path,
989 &mut extension_manifest,
990 CompileExtensionOptions { release: false },
991 )
992 .await
993 }
994 })
995 .await
996 .inspect_err(|error| {
997 util::log_err(error);
998 })?;
999
1000 let output_path = &extensions_dir.join(extension_id.as_ref());
1001 if let Some(metadata) = fs.metadata(output_path).await? {
1002 if metadata.is_symlink {
1003 fs.remove_file(
1004 output_path,
1005 RemoveOptions {
1006 recursive: false,
1007 ignore_if_not_exists: true,
1008 },
1009 )
1010 .await?;
1011 } else {
1012 bail!("extension {extension_id} is still installed");
1013 }
1014 }
1015
1016 fs.create_symlink(output_path, extension_source_path)
1017 .await?;
1018
1019 this.update(cx, |this, cx| this.reload(None, cx))?.await;
1020 this.update(cx, |this, cx| {
1021 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
1022 if let Some(events) = ExtensionEvents::try_global(cx)
1023 && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
1024 {
1025 events.update(cx, |this, cx| {
1026 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
1027 });
1028 }
1029 })?;
1030
1031 Ok(())
1032 })
1033 }
1034
1035 pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
1036 let path = self.installed_dir.join(extension_id.as_ref());
1037 let builder = self.builder.clone();
1038 let fs = self.fs.clone();
1039
1040 match self.outstanding_operations.entry(extension_id.clone()) {
1041 btree_map::Entry::Occupied(_) => return,
1042 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
1043 };
1044
1045 cx.notify();
1046 let compile = cx.background_spawn(async move {
1047 let mut manifest = ExtensionManifest::load(fs, &path).await?;
1048 builder
1049 .compile_extension(
1050 &path,
1051 &mut manifest,
1052 CompileExtensionOptions { release: true },
1053 )
1054 .await
1055 });
1056
1057 cx.spawn(async move |this, cx| {
1058 let result = compile.await;
1059
1060 this.update(cx, |this, cx| {
1061 this.outstanding_operations.remove(&extension_id);
1062 cx.notify();
1063 })?;
1064
1065 if result.is_ok() {
1066 this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
1067 .await;
1068 }
1069
1070 result
1071 })
1072 .detach_and_log_err(cx)
1073 }
1074
1075 /// Updates the set of installed extensions.
1076 ///
1077 /// First, this unloads any themes, languages, or grammars that are
1078 /// no longer in the manifest, or whose files have changed on disk.
1079 /// Then it loads any themes, languages, or grammars that are newly
1080 /// added to the manifest, or whose files have changed on disk.
1081 fn extensions_updated(
1082 &mut self,
1083 mut new_index: ExtensionIndex,
1084 cx: &mut Context<Self>,
1085 ) -> Task<()> {
1086 let old_index = &self.extension_index;
1087
1088 new_index
1089 .extensions
1090 .retain(|extension_id, _| !SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()));
1091
1092 // Determine which extensions need to be loaded and unloaded, based
1093 // on the changes to the manifest and the extensions that we know have been
1094 // modified.
1095 let mut extensions_to_unload = Vec::default();
1096 let mut extensions_to_load = Vec::default();
1097 {
1098 let mut old_keys = old_index.extensions.iter().peekable();
1099 let mut new_keys = new_index.extensions.iter().peekable();
1100 loop {
1101 match (old_keys.peek(), new_keys.peek()) {
1102 (None, None) => break,
1103 (None, Some(_)) => {
1104 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1105 }
1106 (Some(_), None) => {
1107 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1108 }
1109 (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1110 Ordering::Equal => {
1111 let (old_key, old_value) = old_keys.next().unwrap();
1112 let (new_key, new_value) = new_keys.next().unwrap();
1113 if old_value != new_value || self.modified_extensions.contains(old_key)
1114 {
1115 extensions_to_unload.push(old_key.clone());
1116 extensions_to_load.push(new_key.clone());
1117 }
1118 }
1119 Ordering::Less => {
1120 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1121 }
1122 Ordering::Greater => {
1123 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1124 }
1125 },
1126 }
1127 }
1128 self.modified_extensions.clear();
1129 }
1130
1131 if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1132 return Task::ready(());
1133 }
1134
1135 let reload_count = extensions_to_unload
1136 .iter()
1137 .filter(|id| extensions_to_load.contains(id))
1138 .count();
1139
1140 log::info!(
1141 "extensions updated. loading {}, reloading {}, unloading {}",
1142 extensions_to_load.len() - reload_count,
1143 reload_count,
1144 extensions_to_unload.len() - reload_count
1145 );
1146
1147 let extension_ids = extensions_to_load
1148 .iter()
1149 .filter_map(|id| {
1150 Some((
1151 id.clone(),
1152 new_index.extensions.get(id)?.manifest.version.clone(),
1153 ))
1154 })
1155 .collect::<Vec<_>>();
1156
1157 telemetry::event!("Extensions Loaded", id_and_versions = extension_ids);
1158
1159 let themes_to_remove = old_index
1160 .themes
1161 .iter()
1162 .filter_map(|(name, entry)| {
1163 if extensions_to_unload.contains(&entry.extension) {
1164 Some(name.clone().into())
1165 } else {
1166 None
1167 }
1168 })
1169 .collect::<Vec<_>>();
1170 let icon_themes_to_remove = old_index
1171 .icon_themes
1172 .iter()
1173 .filter_map(|(name, entry)| {
1174 if extensions_to_unload.contains(&entry.extension) {
1175 Some(name.clone().into())
1176 } else {
1177 None
1178 }
1179 })
1180 .collect::<Vec<_>>();
1181 let languages_to_remove = old_index
1182 .languages
1183 .iter()
1184 .filter_map(|(name, entry)| {
1185 if extensions_to_unload.contains(&entry.extension) {
1186 Some(name.clone())
1187 } else {
1188 None
1189 }
1190 })
1191 .collect::<Vec<_>>();
1192 let mut grammars_to_remove = Vec::new();
1193 let mut server_removal_tasks = Vec::with_capacity(extensions_to_unload.len());
1194 for extension_id in &extensions_to_unload {
1195 let Some(extension) = old_index.extensions.get(extension_id) else {
1196 continue;
1197 };
1198 grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1199 for (language_server_name, config) in &extension.manifest.language_servers {
1200 for language in config.languages() {
1201 server_removal_tasks.push(self.proxy.remove_language_server(
1202 &language,
1203 language_server_name,
1204 cx,
1205 ));
1206 }
1207 }
1208
1209 for server_id in extension.manifest.context_servers.keys() {
1210 self.proxy.unregister_context_server(server_id.clone(), cx);
1211 }
1212 for adapter in extension.manifest.debug_adapters.keys() {
1213 self.proxy.unregister_debug_adapter(adapter.clone());
1214 }
1215 for locator in extension.manifest.debug_locators.keys() {
1216 self.proxy.unregister_debug_locator(locator.clone());
1217 }
1218 for command_name in extension.manifest.slash_commands.keys() {
1219 self.proxy.unregister_slash_command(command_name.clone());
1220 }
1221 }
1222
1223 self.wasm_extensions
1224 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1225 self.proxy.remove_user_themes(themes_to_remove);
1226 self.proxy.remove_icon_themes(icon_themes_to_remove);
1227 self.proxy
1228 .remove_languages(&languages_to_remove, &grammars_to_remove);
1229
1230 let mut grammars_to_add = Vec::new();
1231 let mut themes_to_add = Vec::new();
1232 let mut icon_themes_to_add = Vec::new();
1233 let mut snippets_to_add = Vec::new();
1234 for extension_id in &extensions_to_load {
1235 let Some(extension) = new_index.extensions.get(extension_id) else {
1236 continue;
1237 };
1238
1239 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1240 let mut grammar_path = self.installed_dir.clone();
1241 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1242 grammar_path.push(grammar_name.as_ref());
1243 grammar_path.set_extension("wasm");
1244 (grammar_name.clone(), grammar_path)
1245 }));
1246 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1247 let mut path = self.installed_dir.clone();
1248 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1249 path
1250 }));
1251 icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1252 |icon_theme_path| {
1253 let mut path = self.installed_dir.clone();
1254 path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1255
1256 let mut icons_root_path = self.installed_dir.clone();
1257 icons_root_path.extend([Path::new(extension_id.as_ref())]);
1258
1259 (path, icons_root_path)
1260 },
1261 ));
1262 snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1263 let mut path = self.installed_dir.clone();
1264 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1265 path
1266 }));
1267 }
1268
1269 self.proxy.register_grammars(grammars_to_add);
1270 let languages_to_add = new_index
1271 .languages
1272 .iter()
1273 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1274 .collect::<Vec<_>>();
1275 for (language_name, language) in languages_to_add {
1276 let mut language_path = self.installed_dir.clone();
1277 language_path.extend([
1278 Path::new(language.extension.as_ref()),
1279 language.path.as_path(),
1280 ]);
1281 self.proxy.register_language(
1282 language_name.clone(),
1283 language.grammar.clone(),
1284 language.matcher.clone(),
1285 language.hidden,
1286 Arc::new(move || {
1287 let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1288 let config: LanguageConfig = ::toml::from_str(&config)?;
1289 let queries = load_plugin_queries(&language_path);
1290 let context_provider =
1291 std::fs::read_to_string(language_path.join("tasks.json"))
1292 .ok()
1293 .and_then(|contents| {
1294 let definitions =
1295 serde_json_lenient::from_str(&contents).log_err()?;
1296 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1297 });
1298
1299 Ok(LoadedLanguage {
1300 config,
1301 queries,
1302 context_provider,
1303 toolchain_provider: None,
1304 manifest_name: None,
1305 })
1306 }),
1307 );
1308 }
1309
1310 let fs = self.fs.clone();
1311 let wasm_host = self.wasm_host.clone();
1312 let root_dir = self.installed_dir.clone();
1313 let proxy = self.proxy.clone();
1314 let extension_entries = extensions_to_load
1315 .iter()
1316 .filter_map(|name| new_index.extensions.get(name).cloned())
1317 .collect::<Vec<_>>();
1318 self.extension_index = new_index;
1319 cx.notify();
1320 cx.emit(Event::ExtensionsUpdated);
1321
1322 cx.spawn(async move |this, cx| {
1323 cx.background_spawn({
1324 let fs = fs.clone();
1325 async move {
1326 let _ = join_all(server_removal_tasks).await;
1327 for theme_path in themes_to_add {
1328 proxy
1329 .load_user_theme(theme_path, fs.clone())
1330 .await
1331 .log_err();
1332 }
1333
1334 for (icon_theme_path, icons_root_path) in icon_themes_to_add {
1335 proxy
1336 .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1337 .await
1338 .log_err();
1339 }
1340
1341 for snippets_path in &snippets_to_add {
1342 match fs
1343 .load(snippets_path)
1344 .await
1345 .with_context(|| format!("Loading snippets from {snippets_path:?}"))
1346 {
1347 Ok(snippets_contents) => {
1348 proxy
1349 .register_snippet(snippets_path, &snippets_contents)
1350 .log_err();
1351 }
1352 Err(e) => log::error!("Cannot load snippets: {e:#}"),
1353 }
1354 }
1355 }
1356 })
1357 .await;
1358
1359 let mut wasm_extensions = Vec::new();
1360 for extension in extension_entries {
1361 if extension.manifest.lib.kind.is_none() {
1362 continue;
1363 };
1364
1365 let extension_path = root_dir.join(extension.manifest.id.as_ref());
1366 let wasm_extension = WasmExtension::load(
1367 &extension_path,
1368 &extension.manifest,
1369 wasm_host.clone(),
1370 cx,
1371 )
1372 .await
1373 .with_context(|| format!("Loading extension from {extension_path:?}"));
1374
1375 match wasm_extension {
1376 Ok(wasm_extension) => {
1377 wasm_extensions.push((extension.manifest.clone(), wasm_extension))
1378 }
1379 Err(e) => {
1380 log::error!("Failed to load extension: {e:#}");
1381 this.update(cx, |_, cx| {
1382 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1383 })
1384 .ok();
1385 }
1386 }
1387 }
1388
1389 this.update(cx, |this, cx| {
1390 this.reload_complete_senders.clear();
1391
1392 for (manifest, wasm_extension) in &wasm_extensions {
1393 let extension = Arc::new(wasm_extension.clone());
1394
1395 for (language_server_id, language_server_config) in &manifest.language_servers {
1396 for language in language_server_config.languages() {
1397 this.proxy.register_language_server(
1398 extension.clone(),
1399 language_server_id.clone(),
1400 language.clone(),
1401 );
1402 }
1403 }
1404
1405 for (slash_command_name, slash_command) in &manifest.slash_commands {
1406 this.proxy.register_slash_command(
1407 extension.clone(),
1408 extension::SlashCommand {
1409 name: slash_command_name.to_string(),
1410 description: slash_command.description.to_string(),
1411 // We don't currently expose this as a configurable option, as it currently drives
1412 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1413 // defined in extensions, as they are not able to be added to the menu.
1414 tooltip_text: String::new(),
1415 requires_argument: slash_command.requires_argument,
1416 },
1417 );
1418 }
1419
1420 for id in manifest.context_servers.keys() {
1421 this.proxy
1422 .register_context_server(extension.clone(), id.clone(), cx);
1423 }
1424
1425 for (debug_adapter, meta) in &manifest.debug_adapters {
1426 let mut path = root_dir.clone();
1427 path.push(Path::new(manifest.id.as_ref()));
1428 if let Some(schema_path) = &meta.schema_path {
1429 path.push(schema_path);
1430 } else {
1431 path.push("debug_adapter_schemas");
1432 path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1433 }
1434
1435 this.proxy.register_debug_adapter(
1436 extension.clone(),
1437 debug_adapter.clone(),
1438 &path,
1439 );
1440 }
1441
1442 for debug_adapter in manifest.debug_locators.keys() {
1443 this.proxy
1444 .register_debug_locator(extension.clone(), debug_adapter.clone());
1445 }
1446 }
1447
1448 this.wasm_extensions.extend(wasm_extensions);
1449 this.proxy.set_extensions_loaded();
1450 this.proxy.reload_current_theme(cx);
1451 this.proxy.reload_current_icon_theme(cx);
1452
1453 if let Some(events) = ExtensionEvents::try_global(cx) {
1454 events.update(cx, |this, cx| {
1455 this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1456 });
1457 }
1458 })
1459 .ok();
1460 })
1461 }
1462
1463 fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1464 let fs = self.fs.clone();
1465 let work_dir = self.wasm_host.work_dir.clone();
1466 let extensions_dir = self.installed_dir.clone();
1467 let index_path = self.index_path.clone();
1468 let proxy = self.proxy.clone();
1469 cx.background_spawn(async move {
1470 let start_time = Instant::now();
1471 let mut index = ExtensionIndex::default();
1472
1473 fs.create_dir(&work_dir).await.log_err();
1474 fs.create_dir(&extensions_dir).await.log_err();
1475
1476 let extension_paths = fs.read_dir(&extensions_dir).await;
1477 if let Ok(mut extension_paths) = extension_paths {
1478 while let Some(extension_dir) = extension_paths.next().await {
1479 let Ok(extension_dir) = extension_dir else {
1480 continue;
1481 };
1482
1483 if extension_dir
1484 .file_name()
1485 .is_some_and(|file_name| file_name == ".DS_Store")
1486 {
1487 continue;
1488 }
1489
1490 Self::add_extension_to_index(
1491 fs.clone(),
1492 extension_dir,
1493 &mut index,
1494 proxy.clone(),
1495 )
1496 .await
1497 .log_err();
1498 }
1499 }
1500
1501 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1502 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1503 .await
1504 .context("failed to save extension index")
1505 .log_err();
1506 }
1507
1508 log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1509 index
1510 })
1511 }
1512
1513 async fn add_extension_to_index(
1514 fs: Arc<dyn Fs>,
1515 extension_dir: PathBuf,
1516 index: &mut ExtensionIndex,
1517 proxy: Arc<ExtensionHostProxy>,
1518 ) -> Result<()> {
1519 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1520 let extension_id = extension_manifest.id.clone();
1521
1522 if SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()) {
1523 return Ok(());
1524 }
1525
1526 // TODO: distinguish dev extensions more explicitly, by the absence
1527 // of a checksum file that we'll create when downloading normal extensions.
1528 let is_dev = fs
1529 .metadata(&extension_dir)
1530 .await?
1531 .context("directory does not exist")?
1532 .is_symlink;
1533
1534 if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1535 while let Some(language_path) = language_paths.next().await {
1536 let language_path = language_path?;
1537 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1538 continue;
1539 };
1540 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1541 continue;
1542 };
1543 if !fs_metadata.is_dir {
1544 continue;
1545 }
1546 let config = fs.load(&language_path.join("config.toml")).await?;
1547 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1548
1549 let relative_path = relative_path.to_path_buf();
1550 if !extension_manifest.languages.contains(&relative_path) {
1551 extension_manifest.languages.push(relative_path.clone());
1552 }
1553
1554 index.languages.insert(
1555 config.name.clone(),
1556 ExtensionIndexLanguageEntry {
1557 extension: extension_id.clone(),
1558 path: relative_path,
1559 matcher: config.matcher,
1560 hidden: config.hidden,
1561 grammar: config.grammar,
1562 },
1563 );
1564 }
1565 }
1566
1567 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1568 while let Some(theme_path) = theme_paths.next().await {
1569 let theme_path = theme_path?;
1570 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1571 continue;
1572 };
1573
1574 let Some(theme_families) = proxy
1575 .list_theme_names(theme_path.clone(), fs.clone())
1576 .await
1577 .log_err()
1578 else {
1579 continue;
1580 };
1581
1582 let relative_path = relative_path.to_path_buf();
1583 if !extension_manifest.themes.contains(&relative_path) {
1584 extension_manifest.themes.push(relative_path.clone());
1585 }
1586
1587 for theme_name in theme_families {
1588 index.themes.insert(
1589 theme_name.into(),
1590 ExtensionIndexThemeEntry {
1591 extension: extension_id.clone(),
1592 path: relative_path.clone(),
1593 },
1594 );
1595 }
1596 }
1597 }
1598
1599 if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1600 while let Some(icon_theme_path) = icon_theme_paths.next().await {
1601 let icon_theme_path = icon_theme_path?;
1602 let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1603 continue;
1604 };
1605
1606 let Some(icon_theme_families) = proxy
1607 .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1608 .await
1609 .log_err()
1610 else {
1611 continue;
1612 };
1613
1614 let relative_path = relative_path.to_path_buf();
1615 if !extension_manifest.icon_themes.contains(&relative_path) {
1616 extension_manifest.icon_themes.push(relative_path.clone());
1617 }
1618
1619 for icon_theme_name in icon_theme_families {
1620 index.icon_themes.insert(
1621 icon_theme_name.into(),
1622 ExtensionIndexIconThemeEntry {
1623 extension: extension_id.clone(),
1624 path: relative_path.clone(),
1625 },
1626 );
1627 }
1628 }
1629 }
1630
1631 let extension_wasm_path = extension_dir.join("extension.wasm");
1632 if fs.is_file(&extension_wasm_path).await {
1633 extension_manifest
1634 .lib
1635 .kind
1636 .get_or_insert(ExtensionLibraryKind::Rust);
1637 }
1638
1639 index.extensions.insert(
1640 extension_id.clone(),
1641 ExtensionIndexEntry {
1642 dev: is_dev,
1643 manifest: Arc::new(extension_manifest),
1644 },
1645 );
1646
1647 Ok(())
1648 }
1649
1650 fn prepare_remote_extension(
1651 &mut self,
1652 extension_id: Arc<str>,
1653 is_dev: bool,
1654 tmp_dir: PathBuf,
1655 cx: &mut Context<Self>,
1656 ) -> Task<Result<()>> {
1657 let src_dir = self.extensions_dir().join(extension_id.as_ref());
1658 let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1659 else {
1660 return Task::ready(Err(anyhow!("extension no longer installed")));
1661 };
1662 let fs = self.fs.clone();
1663 cx.background_spawn(async move {
1664 const EXTENSION_TOML: &str = "extension.toml";
1665 const EXTENSION_WASM: &str = "extension.wasm";
1666 const CONFIG_TOML: &str = "config.toml";
1667
1668 if is_dev {
1669 let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1670 fs.save(
1671 &tmp_dir.join(EXTENSION_TOML),
1672 &Rope::from(manifest_toml),
1673 language::LineEnding::Unix,
1674 )
1675 .await?;
1676 } else {
1677 fs.copy_file(
1678 &src_dir.join(EXTENSION_TOML),
1679 &tmp_dir.join(EXTENSION_TOML),
1680 fs::CopyOptions::default(),
1681 )
1682 .await?
1683 }
1684
1685 if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1686 fs.copy_file(
1687 &src_dir.join(EXTENSION_WASM),
1688 &tmp_dir.join(EXTENSION_WASM),
1689 fs::CopyOptions::default(),
1690 )
1691 .await?
1692 }
1693
1694 for language_path in loaded_extension.manifest.languages.iter() {
1695 if fs
1696 .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1697 .await
1698 {
1699 fs.create_dir(&tmp_dir.join(language_path)).await?;
1700 fs.copy_file(
1701 &src_dir.join(language_path).join(CONFIG_TOML),
1702 &tmp_dir.join(language_path).join(CONFIG_TOML),
1703 fs::CopyOptions::default(),
1704 )
1705 .await?
1706 }
1707 }
1708
1709 for (adapter_name, meta) in loaded_extension.manifest.debug_adapters.iter() {
1710 let schema_path = &extension::build_debug_adapter_schema_path(adapter_name, meta);
1711
1712 if fs.is_file(&src_dir.join(schema_path)).await {
1713 if let Some(parent) = schema_path.parent() {
1714 fs.create_dir(&tmp_dir.join(parent)).await?
1715 }
1716 fs.copy_file(
1717 &src_dir.join(schema_path),
1718 &tmp_dir.join(schema_path),
1719 fs::CopyOptions::default(),
1720 )
1721 .await?
1722 }
1723 }
1724
1725 Ok(())
1726 })
1727 }
1728
1729 async fn sync_extensions_over_ssh(
1730 this: &WeakEntity<Self>,
1731 client: WeakEntity<RemoteClient>,
1732 cx: &mut AsyncApp,
1733 ) -> Result<()> {
1734 let extensions = this.update(cx, |this, _cx| {
1735 this.extension_index
1736 .extensions
1737 .iter()
1738 .filter_map(|(id, entry)| {
1739 if !entry.manifest.allow_remote_load() {
1740 return None;
1741 }
1742 Some(proto::Extension {
1743 id: id.to_string(),
1744 version: entry.manifest.version.to_string(),
1745 dev: entry.dev,
1746 })
1747 })
1748 .collect()
1749 })?;
1750
1751 let response = client
1752 .update(cx, |client, _cx| {
1753 client
1754 .proto_client()
1755 .request(proto::SyncExtensions { extensions })
1756 })?
1757 .await?;
1758 let path_style = client.read_with(cx, |client, _| client.path_style())?;
1759
1760 for missing_extension in response.missing_extensions.into_iter() {
1761 let tmp_dir = tempfile::tempdir()?;
1762 this.update(cx, |this, cx| {
1763 this.prepare_remote_extension(
1764 missing_extension.id.clone().into(),
1765 missing_extension.dev,
1766 tmp_dir.path().to_owned(),
1767 cx,
1768 )
1769 })?
1770 .await?;
1771 let dest_dir = RemotePathBuf::new(
1772 path_style
1773 .join(&response.tmp_dir, &missing_extension.id)
1774 .with_context(|| {
1775 format!(
1776 "failed to construct destination path: {:?}, {:?}",
1777 response.tmp_dir, missing_extension.id,
1778 )
1779 })?,
1780 path_style,
1781 );
1782 log::info!("Uploading extension {}", missing_extension.clone().id);
1783
1784 client
1785 .update(cx, |client, cx| {
1786 client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1787 })?
1788 .await?;
1789
1790 log::info!(
1791 "Finished uploading extension {}",
1792 missing_extension.clone().id
1793 );
1794
1795 client
1796 .update(cx, |client, _cx| {
1797 client.proto_client().request(proto::InstallExtension {
1798 tmp_dir: dest_dir.to_proto(),
1799 extension: Some(missing_extension),
1800 })
1801 })?
1802 .await?;
1803 }
1804
1805 anyhow::Ok(())
1806 }
1807
1808 pub async fn update_ssh_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1809 let clients = this.update(cx, |this, _cx| {
1810 this.remote_clients.retain(|_k, v| v.upgrade().is_some());
1811 this.remote_clients.values().cloned().collect::<Vec<_>>()
1812 })?;
1813
1814 for client in clients {
1815 Self::sync_extensions_over_ssh(this, client, cx)
1816 .await
1817 .log_err();
1818 }
1819
1820 anyhow::Ok(())
1821 }
1822
1823 pub fn register_remote_client(&mut self, client: Entity<RemoteClient>, cx: &mut Context<Self>) {
1824 let options = client.read(cx).connection_options();
1825
1826 if let Some(existing_client) = self.remote_clients.get(&options)
1827 && existing_client.upgrade().is_some()
1828 {
1829 return;
1830 }
1831
1832 self.remote_clients.insert(options, client.downgrade());
1833 self.ssh_registered_tx.unbounded_send(()).ok();
1834 }
1835}
1836
1837fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1838 let mut result = LanguageQueries::default();
1839 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1840 for entry in entries {
1841 let Some(entry) = entry.log_err() else {
1842 continue;
1843 };
1844 let path = entry.path();
1845 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1846 if !remainder.ends_with(".scm") {
1847 continue;
1848 }
1849 for (name, query) in QUERY_FILENAME_PREFIXES {
1850 if remainder.starts_with(name) {
1851 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1852 match query(&mut result) {
1853 None => *query(&mut result) = Some(contents.into()),
1854 Some(r) => r.to_mut().push_str(contents.as_ref()),
1855 }
1856 }
1857 break;
1858 }
1859 }
1860 }
1861 }
1862 }
1863 result
1864}