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